gsql/ The SELECT Statement
Last Updated: October 20, 2018

Mastering GSQL's primary engine for graph traversal and data retrieval.

The SELECT Statement

The SELECT statement is the heart of GSQL. It defines how to traverse the graph, filter data, and perform computations using path patterns.

1. Basic Syntax (V2/V3)

GSQL uses a path-based syntax that is compatible with GQL (Graph Query Language).

gsqlterminal
Result = SELECT target_alias FROM source_alias:s -(edge_type:e)-> target_type:t WHERE t.age > 21 ACCUM t.@visited += 1;

2. The FROM Clause: Path Patterns

Path patterns define the template for traversal.

  • Vertex Pattern: (alias:Type)
  • Edge Pattern: -[alias:Type]-> (Right), <-[alias:Type]- (Left), -[alias:Type]- (Undirected).

Multi-Hop & Quantifiers

You can traverse multiple levels using quantifiers:

  • (s:Person) -[:friend*1..3]-> (t:Person): Finds friends up to 3 hops away.
  • *: 1 or more repetitions.
  • {m,n}: m to n repetitions.

3. Computational Clauses

SELECT statements are unique in GSQL because they allow computation during traversal.

ACCUM

Executes for every edge that matches the pattern. Perfect for updating accumulators based on edge/neighbor data.

gsqlterminal
ACCUM t.@score += s.weight * e.impact

POST-ACCUM

Executes once for every vertex in the source or target set after the ACCUM phase. Ideal for final calculations or filtering based on accumulated values.

gsqlterminal
POST-ACCUM s.total_score = s.@score / s.outdegree()

4. Result Refinement

  • WHERE: Filters edges and vertices during traversal.
  • ORDER BY: Sorts the resulting vertex set.
  • LIMIT: Restricts the number of vertices returned.
  • SAMPLE: Randomly samples a subset of neighbors (essential for "hub" nodes with high degrees).

5. Conjunctive Patterns

You can combine multiple paths in a single SELECT by separating them with commas. This acts as an "AND" condition.

gsqlterminal
# Find people who are both 'Friends' and 'Coworkers' Results = SELECT t FROM (s:Person) -[:Friend]-> (t:Person), (s:Person) -[:Works_With]-> (t:Person);