SELECT statement
The SELECT statement retrieves rows from one or more tables, views, derived tables or graph patterns. In CoraDB the same statement queries relational tables and graph data: vertex and edge tables can be read like ordinary tables, or traversed with a MATCH pattern in the FROM clause.
Syntax
Section titled “Syntax”SELECT [ <qualifier> ] <select_expressions> [{TO | INTO} <variable_comma_list>] [FROM <extended_table_specification_comma_list>] [WHERE <search_condition>] [GROUP BY {col_name | expr} [ASC | DESC], ... [WITH ROLLUP]] [HAVING <search_condition>] [ORDER BY {col_name | expr} [ASC | DESC], ... [NULLS {FIRST | LAST}]] [LIMIT [offset,] row_count] [USING INDEX { index_name [, index_name, ...] | NONE }] [FOR UPDATE [OF <spec_name_comma_list>]]
<qualifier> ::= ALL | DISTINCT | DISTINCTROW | UNIQUE
<select_expressions> ::= * | <expression_comma_list> | *, <expression_comma_list>
<variable_comma_list> ::= [:] identifier, [:] identifier, ...
<extended_table_specification_comma_list> ::= <table_specification> [ {, <table_specification> } ... | <join_table_specification> ... | <join_table_specification2> ... ]
<table_specification> ::= <single_table_spec> [<correlation>] | <metaclass_specification> [<correlation>] | <subquery> <correlation> | TABLE ( <expression> ) <correlation> | MATCH <graph_pattern> [, <graph_pattern> ...]
<correlation> ::= [AS] <identifier> [(<identifier_comma_list>)]
<single_table_spec> ::= [ONLY] <table_name> | ALL <table_name> [ EXCEPT <table_name> ]
<metaclass_specification> ::= CLASS <class_name>
<join_table_specification> ::= [INNER | {LEFT | RIGHT} [OUTER]] JOIN <table_specification> ON <search_condition>
<join_table_specification2> ::= { CROSS JOIN | NATURAL [ LEFT | RIGHT ] JOIN } <table_specification>- qualifier: when omitted, ALL is used.
- ALL: returns every row.
- DISTINCT: returns only unique rows. DISTINCT, DISTINCTROW and UNIQUE are synonyms.
- select_expressions:
*returns all columns of the tables in theFROMclause; table_name.*returns all columns of one table.- expression_comma_list: column names, path expressions (tbl_name.col_name), variables, arithmetic and function expressions, including aggregate functions such as AVG, COUNT, MAX, MIN and SUM. Use
ASto give an expression an alias; aliases can be used inGROUP BY,HAVINGandORDER BY. Column positions start at 1.
- variable_comma_list: stores the selected values in session variables (
TO :varorINTO :var). - single_table_spec: with class inheritance,
ONLYreads just the named super class,ALLreads it and its subclasses, andEXCEPTexcludes the listed subclasses. See Class inheritance.
Basic examples
Section titled “Basic examples”Return each distinct contact title used by customers (the first five, alphabetically):
SELECT DISTINCT contact_titleFROM customerORDER BY contact_titleLIMIT 5;| contact_title |
|---|
| Account Manager |
| Accounts Payable Clerk |
| Buyer |
| CEO |
| Category Manager |
customer is a vertex table, yet it is queried here like any relational table.
Give columns an alias and sort by the alias:
SELECT id AS order_no, order_date AS placed_onFROM ordersORDER BY placed_on DESC, order_noLIMIT 5;| order_no | placed_on |
|---|---|
| 376 | 2025-12-31 |
| 1127 | 2025-12-31 |
| 1446 | 2025-12-31 |
| 1634 | 2025-12-31 |
| 1888 | 2025-12-31 |
Build a value from several columns:
SELECT CONCAT(name, ' (', code, ')') AS countryFROM countriesORDER BY countryLIMIT 5;| country |
|---|
| Argentina (ARG) |
| Australia (AUS) |
| Austria (AUT) |
| Belgium (BEL) |
| Brazil (BRA) |
FROM clause
Section titled “FROM clause”The FROM clause names the sources the rows are read from: tables, views, vertex and edge tables, subqueries (derived tables) and graph patterns. When no table is needed, FROM can be omitted.
SELECT 1 + 1 AS sum_value;| sum_value |
|---|
| 2 |
Derived table
Section titled “Derived table”A subquery in the FROM clause creates a derived table: its result is treated as a table for the rest of the query. A derived table must have a correlation name (alias). Derived tables are also used to access the individual elements of a collection-typed column, each element becoming a row.
Subquery derived table
Section titled “Subquery derived table”FROM (subquery) [AS] [derived_table_name [(column_name [{, column_name } ... ])]]- The number of column_name entries must match the number of columns returned by the subquery.
- derived_table_name can be omitted.
Average number of lines per order, computed from a derived table that first counts the lines of each order:
SELECT AVG(lines) AS avg_lines_per_orderFROM (SELECT order_id, COUNT(*) FROM order_items GROUP BY order_id) AS t(order_id, lines);| avg_lines_per_order |
|---|
| 3.841580756013746 |
A derived table can also be correlated with the outer query. The following query lists orders whose shipping cost is more than three times the average shipping cost of the same customer:
SELECT o.id, o.customer_id, o.shipping_costFROM orders oWHERE o.shipping_cost > (SELECT AVG(s) * 3 FROM (SELECT shipping_cost FROM orders WHERE customer_id = o.customer_id) AS t(s))ORDER BY o.shipping_cost DESC, o.idLIMIT 5;| id | customer_id | shipping_cost |
|---|---|---|
| 1080 | 460 | 58.00 |
| 1675 | 855 | 50.57 |
| 995 | 634 | 50.52 |
| 1643 | 830 | 48.30 |
| 2884 | 877 | 41.90 |
WHERE clause
Section titled “WHERE clause”The WHERE clause keeps only the rows for which search_condition is true. A condition that evaluates to NULL (unknown) does not select the row.
WHERE <search_condition>
<search_condition> ::= <comparison_predicate> | <between_predicate> | <exists_predicate> | <in_predicate> | <null_predicate> | <like_predicate> | <quantified_predicate> | <set_predicate> | [NOT] MATCH <graph_pattern>The predicates are described in detail here:
- Simple comparison expression
- BETWEEN
- EXISTS
- IN
- IS NULL
- LIKE
- ANY/SOME/ALL quantifiers
- MATCH as a predicate
Combine conditions with AND, OR and NOT. They are evaluated in this order:
| Priority | Operator | Meaning |
|---|---|---|
| 1 | () |
Expressions in parentheses are evaluated first. |
| 2 | NOT | Negates the result of the expression. |
| 3 | AND | All conditions must be true. |
| 4 | OR | At least one condition must be true. |
Orders placed in December 2025 that are either not shipped yet or were shipped for free:
SELECT id, order_date, shipped_date, shipping_costFROM ordersWHERE order_date >= DATE'2025-12-01' AND (shipped_date IS NULL OR shipping_cost = 0)ORDER BY idLIMIT 5;| id | order_date | shipped_date | shipping_cost |
|---|---|---|---|
| 175 | 2025-12-22 | 2025-12-25 | 0.00 |
| 455 | 2025-12-30 | NULL | 12.35 |
| 547 | 2025-12-14 | 2025-12-15 | 0.00 |
| 707 | 2025-12-28 | 2026-01-03 | 0.00 |
| 782 | 2025-12-12 | 2025-12-14 | 0.00 |
GROUP BY ... HAVING clause
Section titled “GROUP BY ... HAVING clause”GROUP BY groups the rows that have the same values in the listed columns or expressions, so that aggregate functions are computed per group. HAVING then filters the groups.
SELECT ...GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP] [HAVING <search_condition>]- col_name | expr | position: one or more columns, expressions, aliases or column positions, separated by commas.
- ASC | DESC: sort order of the groups; ASC is the default.
- search_condition: the
HAVINGcondition can refer to grouping columns, their aliases and aggregate functions. - WITH ROLLUP: adds subtotal rows for each level of grouping and a grand total row. In those rows the rolled-up columns are NULL.
Orders per year:
SELECT EXTRACT(YEAR FROM order_date) AS yr, COUNT(*) AS ordersFROM ordersGROUP BY yrORDER BY yr;| yr | orders |
|---|---|
| 2021 | 416 |
| 2022 | 482 |
| 2023 | 551 |
| 2024 | 675 |
| 2025 | 786 |
WHERE filters rows before grouping, HAVING filters groups after it. Customers with at least five orders in 2025, and what they paid for shipping:
SELECT customer_id, COUNT(*) AS orders, SUM(shipping_cost) AS shippingFROM ordersWHERE order_date >= DATE'2025-01-01'GROUP BY customer_idHAVING COUNT(*) >= 5ORDER BY orders DESC, customer_idLIMIT 5;| customer_id | orders | shipping |
|---|---|---|
| 812 | 13 | 153.64 |
| 440 | 11 | 183.69 |
| 391 | 10 | 124.04 |
| 75 | 8 | 119.41 |
| 342 | 8 | 154.15 |
WITH ROLLUP adds a subtotal per year and a grand total:
SELECT EXTRACT(YEAR FROM order_date) AS yr, QUARTER(order_date) AS q, COUNT(*) AS ordersFROM ordersWHERE order_date >= DATE'2024-01-01'GROUP BY yr, q WITH ROLLUP;| yr | q | orders |
|---|---|---|
| 2024 | 1 | 125 |
| 2024 | 2 | 132 |
| 2024 | 3 | 152 |
| 2024 | 4 | 266 |
| NULL | NULL | 675 |
| 2025 | 1 | 147 |
| 2025 | 2 | 172 |
| 2025 | 3 | 186 |
| 2025 | 4 | 281 |
| NULL | NULL | 786 |
| NULL | NULL | 1461 |
ORDER BY clause
Section titled “ORDER BY clause”ORDER BY sorts the result. Without it, the order of the rows is not guaranteed.
SELECT ...ORDER BY {col_name | expr | position} [ASC | DESC], ... [NULLS {FIRST | LAST}]- col_name | expr | position: columns, expressions, aliases or column positions. A column that is not in the select list can also be used.
- ASC | DESC: ascending (default) or descending order.
- NULLS FIRST | NULLS LAST: where NULL values go. By default NULLs come first with
ASCand last withDESC.
Most recently shipped orders, with the orders that are not shipped yet (NULL shipped_date) on top:
SELECT id, order_date, shipped_dateFROM ordersORDER BY shipped_date DESC NULLS FIRST, idLIMIT 5;| id | order_date | shipped_date |
|---|---|---|
| 455 | 2025-12-30 | NULL |
| 933 | 2025-12-30 | NULL |
| 1325 | 2025-12-30 | NULL |
| 1421 | 2025-12-27 | NULL |
| 1634 | 2025-12-31 | NULL |
LIMIT clause
Section titled “LIMIT clause”LIMIT restricts the number of rows returned, optionally after skipping offset rows.
LIMIT {[offset,] row_count | row_count [OFFSET offset]}
<offset> ::= <limit_expression><row_count> ::= <limit_expression>- offset: number of rows to skip; the first row has offset 0 (default).
- row_count: maximum number of rows to return.
- Both can be unsigned integers, host variables (
?) or simple expressions such as? * ?, soLIMITworks in prepared statements. INST_NUM()andROWNUMcannot be used in theWHEREclause of a query withLIMIT, andLIMITcannot be combined withHAVING GROUPBY_NUM().
The 11th to 15th most recent orders (a typical "page 3" with five rows per page):
SELECT id, order_dateFROM ordersORDER BY order_date DESC, idLIMIT 5 OFFSET 10; -- same as LIMIT 10, 5| id | order_date |
|---|---|
| 414 | 2025-12-29 |
| 832 | 2025-12-29 |
| 1208 | 2025-12-29 |
| 517 | 2025-12-28 |
| 707 | 2025-12-28 |
With a prepared statement:
PREPARE recent_orders FROM 'SELECT id, order_date FROM orders ORDER BY order_date DESC, id LIMIT ?, ?';EXECUTE recent_orders USING 10, 5;Join query
Section titled “Join query”A join combines rows from two or more tables (or views, derived tables and graph patterns). The join condition compares columns of the joined sources; only combinations that satisfy it are returned. A join with = is an equi-join, a join without a condition is a cartesian product, and joining a table to itself is a self join (use aliases to tell the two copies apart).
FROM <table_specification> [{, <table_specification> | { <join_table_specification> | <join_table_specification2> }} ...]
<join_table_specification> ::= [INNER | {LEFT | RIGHT} [OUTER]] JOIN <table_specification> ON <search_condition>
<join_table_specification2> ::= { CROSS JOIN | NATURAL [ LEFT | RIGHT ] JOIN } <table_specification>- [INNER] JOIN: returns only rows that satisfy the join condition.
- {LEFT | RIGHT} [OUTER] JOIN: also returns the rows of the left (or right) source that have no match, with NULL for the other side. CoraDB does not support
FULL OUTER JOIN. - CROSS JOIN: every combination of rows, without a condition.
- NATURAL [LEFT | RIGHT] JOIN: joins on all columns that have the same name in both sources.
Inner join
Section titled “Inner join”INNER can be omitted, and the inner join can also be written with a comma and a WHERE condition. Orders placed on the last day of 2025, with the customer's company name (the customer vertex table is joined like a relational table):
SELECT o.id, o.order_date, cu.company_nameFROM orders oINNER JOIN customer cu ON cu.id = o.customer_idWHERE o.order_date = DATE'2025-12-31'ORDER BY o.id;| id | order_date | company_name |
|---|---|---|
| 376 | 2025-12-31 | Reyes, Farmer and West |
| 1127 | 2025-12-31 | Owens, Mathis and Romero |
| 1446 | 2025-12-31 | Harris-Jones |
| 1634 | 2025-12-31 | Anderson-Meyer |
| 1888 | 2025-12-31 | Price, Whitney and Carr |
Outer join
Section titled “Outer join”An outer join keeps the rows of one side even when they have no match. Customers that never ordered appear with an order count of 0:
SELECT cu.company_name, COUNT(o.id) AS ordersFROM customer cuLEFT OUTER JOIN orders o ON o.customer_id = cu.idGROUP BY cu.id, cu.company_nameORDER BY orders, cu.company_nameLIMIT 5;| company_name | orders |
|---|---|
| Adams, Pena and Hansen | 0 |
| Adams-Barnes | 0 |
| Adams-Greer | 0 |
| Adams-Obrien | 0 |
| Alexander LLC | 0 |
The tables are joined in the order they appear in the FROM clause, so write outer joins with the table order in mind. A RIGHT OUTER JOIN can always be rewritten as a LEFT OUTER JOIN by swapping the two tables.
Conditions in ON and in WHERE mean different things. In an outer join, a condition in ON only decides which rows match; every row of the preserved side is still returned. A condition in WHERE is applied after the join and removes rows:
-- condition in ON: all 1000 customers are kept, 2025 orders are attached when they existSELECT COUNT(*) AS rows_returnedFROM customer cuLEFT OUTER JOIN orders o ON o.customer_id = cu.id AND o.order_date >= DATE'2025-01-01';
-- condition in WHERE: only rows with a 2025 order remainSELECT COUNT(*) AS rows_returnedFROM customer cuLEFT OUTER JOIN orders o ON o.customer_id = cu.idWHERE o.order_date >= DATE'2025-01-01';| query | rows_returned |
|---|---|
Condition in ON |
1394 |
Condition in WHERE |
786 |
CoraDB also accepts the Oracle-style (+) notation in the WHERE clause. It is not ISO/ANSI SQL and can be ambiguous, so prefer LEFT | RIGHT OUTER JOIN. Both queries below count the 350 customers without orders:
SELECT COUNT(*) AS customers_without_ordersFROM customer cuLEFT OUTER JOIN orders o ON o.customer_id = cu.idWHERE o.id IS NULL;
SELECT COUNT(*) AS customers_without_ordersFROM customer cu, orders oWHERE cu.id = o.customer_id(+) AND o.id IS NULL;| customers_without_orders |
|---|
| 350 |
Path expressions that include subqueries and sub-columns cannot be used in the join condition of an outer join.
Cross join
Section titled “Cross join”A cross join returns the cartesian product of the two sources. CROSS JOIN can be replaced by a comma.
SELECT COUNT(*) AS combinationsFROM countries CROSS JOIN category; -- 25 countries x 32 categories| combinations |
|---|
| 800 |
Natural join
Section titled “Natural join”A natural join uses all columns with the same name as the join condition. Here both derived tables have a customer_id column:
SELECT c.customer_id, c.company_name, o.n AS ordersFROM (SELECT id AS customer_id, company_name FROM customer) cNATURAL JOIN (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) oORDER BY o.n DESC, c.customer_idLIMIT 3;| customer_id | company_name | orders |
|---|---|---|
| 440 | Mayer, Carroll and Owens | 40 |
| 812 | Young and Sons | 40 |
| 444 | Kelly Ltd | 39 |
This is the same as INNER JOIN ... ON c.customer_id = o.customer_id. NATURAL LEFT JOIN and NATURAL RIGHT JOIN are the outer-join equivalents. With SELECT *, both customer_id columns are returned, so qualify the column in ORDER BY.
Joining graph patterns and tables
Section titled “Joining graph patterns and tables”A MATCH pattern is a table specification too, so graph patterns can be joined with relational tables in the same FROM clause. London customers with the most orders:
SELECT cu.company_name, COUNT(o.id) AS ordersFROM MATCH (cu:customer)-[:resides_in]->(ci:city), orders oWHERE o.customer_id = cu.id AND ci.name = 'London'GROUP BY cu.company_nameORDER BY orders DESC, cu.company_nameLIMIT 3;| cu.company_name | orders |
|---|---|
| Hicks-Marshall | 15 |
| Jordan, Smith and Bartlett | 15 |
| Hernandez, Wilson and Johnson | 10 |
MATCH patterns also work with INNER, LEFT and RIGHT [OUTER] JOIN ... ON. See Joining MATCH patterns.
Subquery
Section titled “Subquery”A subquery can be used wherever an expression is allowed, for example in the select list or in the WHERE clause. Used as a value, it must return a single column. Subqueries are single-row or multiple-row.
Single-row subquery
Section titled “Single-row subquery”A single-row subquery returns one column of one row. If it returns no row, its value is NULL; if it returns more than one row, an error is raised.
SELECT o.id, o.order_date, (SELECT cu.company_name FROM customer cu WHERE cu.id = o.customer_id) AS customerFROM orders oORDER BY o.idLIMIT 5;| id | order_date | customer |
|---|---|---|
| 0 | 2021-11-07 | Peterson-Williams |
| 1 | 2025-10-19 | Hicks Group |
| 2 | 2022-09-05 | Doyle, Mcdonald and Lowery |
| 3 | 2023-12-27 | Washington LLC |
| 4 | 2024-09-20 | Davidson, Jefferson and Mack |
Multiple-row subquery
Section titled “Multiple-row subquery”A multiple-row subquery returns one column of several rows. With the SET, MULTISET or LIST keyword, the rows become a collection value. Use ORDER BY inside the subquery to control the order of a LIST.
SELECT c.name, LIST(SELECT ci.name FROM city ci WHERE ci.country_code = c.code ORDER BY ci.name) AS citiesFROM countries cWHERE c.code IN ('AUT', 'BEL')ORDER BY c.name;| name | cities |
|---|---|
| Austria | {'Graz', 'Salzburg'} |
| Belgium | {'Bruxelles', 'Charleroi'} |
Multiple-row subqueries can be used wherever a collection value is allowed, but not where a collection constant is required, such as the DEFAULT value of a column.
MATCH queries graph patterns over vertex tables and edge tables (created with CREATE VERTEX TABLE and CREATE EDGE TABLE). It is used in the FROM clause, and as a predicate in WHERE:
SELECT ...FROM MATCH [<path_variable> =] [ANY_SHORTEST | ALL_SHORTEST] <graph_pattern> [, <graph_pattern> ...]Brands with the most followers:
SELECT b.name, COUNT(cu) AS followersFROM MATCH (cu:customer)-[:follows]->(b:brand)GROUP BY b.nameORDER BY followers DESC, b.nameLIMIT 5;| b.name | followers |
|---|---|
| Nike | 209 |
| Adidas | 132 |
| Puma | 94 |
| Reebok | 83 |
| Under Armour | 76 |
The full syntax (directions, variable-length paths, shortest paths, path variables, MATCH predicates and joins) is described in MATCH clause: graph queries in SELECT; Relational and graph in one query shows more ways to combine patterns with tables.
VALUES
Section titled “VALUES”The VALUES clause returns the rows written in the statement. It is a short way to write a UNION ALL of constant rows, and it can be used as a derived table. All rows must have the same number of values.
VALUES (expression[, ...])[, ...]VALUES (1 AS id, 'standard' AS shipping), (2, 'express'), (3, 'pickup');| id | shipping |
|---|---|
| 1 | standard |
| 2 | express |
| 3 | pickup |
This is equivalent to:
SELECT 1 AS id, 'standard' AS shippingUNION ALL SELECT 2, 'express'UNION ALL SELECT 3, 'pickup';As a derived table, joined with a real table:
SELECT t.code, c.nameFROM (VALUES ('FRA'), ('DEU'), ('ITA')) AS t(code)INNER JOIN countries c ON c.code = t.codeORDER BY c.name;| code | name |
|---|---|
| FRA | France |
| DEU | Germany |
| ITA | Italy |
VALUES with several rows is also used in INSERT.
FOR UPDATE
Section titled “FOR UPDATE”FOR UPDATE locks the rows returned by the SELECT (with an exclusive X_LOCK) so that the transaction can update or delete them later without another transaction changing them first.
SELECT ... [FOR UPDATE [OF <spec_name_comma_list>]]
<spec_name_comma_list> ::= <spec_name> [, <spec_name>, ... ]<spec_name> ::= table_name | view_name- spec_name_comma_list: the tables or views of the
FROMclause whose rows are locked. WithoutOF, all tables and views of theFROMclause are locked.
Lock the orders that still have to be shipped, then mark them as shipped in the same transaction:
SELECT id, shipped_dateFROM ordersWHERE shipped_date IS NULLORDER BY idFOR UPDATE;
UPDATE orders SET shipped_date = SYSDATE WHERE shipped_date IS NULL;COMMIT;Other forms:
SELECT * FROM orders o INNER JOIN order_items oi ON oi.order_id = o.idWHERE o.shipped_date IS NULLFOR UPDATE OF o; -- lock only the orders rows
SELECT * FROM orders oINNER JOIN (SELECT * FROM order_items WHERE quantity > 5) big ON big.order_id = o.idWHERE o.shipped_date IS NULLFOR UPDATE; -- a derived table can be referenced