Skip to content

SELECT statement

View as Markdown

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.

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 the FROM clause; 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 AS to give an expression an alias; aliases can be used in GROUP BY, HAVING and ORDER BY. Column positions start at 1.
  • variable_comma_list: stores the selected values in session variables (TO :var or INTO :var).
  • single_table_spec: with class inheritance, ONLY reads just the named super class, ALL reads it and its subclasses, and EXCEPT excludes the listed subclasses. See Class inheritance.

Return each distinct contact title used by customers (the first five, alphabetically):

SELECT DISTINCT contact_title
FROM customer
ORDER BY contact_title
LIMIT 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_on
FROM orders
ORDER BY placed_on DESC, order_no
LIMIT 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 country
FROM countries
ORDER BY country
LIMIT 5;
country
Argentina (ARG)
Australia (AUS)
Austria (AUT)
Belgium (BEL)
Brazil (BRA)

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

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.

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_order
FROM (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_cost
FROM orders o
WHERE 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.id
LIMIT 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

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:

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_cost
FROM orders
WHERE order_date >= DATE'2025-12-01'
AND (shipped_date IS NULL OR shipping_cost = 0)
ORDER BY id
LIMIT 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 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 HAVING condition 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 orders
FROM orders
GROUP BY yr
ORDER 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 shipping
FROM orders
WHERE order_date >= DATE'2025-01-01'
GROUP BY customer_id
HAVING COUNT(*) >= 5
ORDER BY orders DESC, customer_id
LIMIT 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 orders
FROM orders
WHERE 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 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 ASC and last with DESC.

Most recently shipped orders, with the orders that are not shipped yet (NULL shipped_date) on top:

SELECT id, order_date, shipped_date
FROM orders
ORDER BY shipped_date DESC NULLS FIRST, id
LIMIT 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 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 ? * ?, so LIMIT works in prepared statements.
  • INST_NUM() and ROWNUM cannot be used in the WHERE clause of a query with LIMIT, and LIMIT cannot be combined with HAVING GROUPBY_NUM().

The 11th to 15th most recent orders (a typical "page 3" with five rows per page):

SELECT id, order_date
FROM orders
ORDER BY order_date DESC, id
LIMIT 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;

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 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_name
FROM orders o
INNER JOIN customer cu ON cu.id = o.customer_id
WHERE 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

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 orders
FROM customer cu
LEFT OUTER JOIN orders o ON o.customer_id = cu.id
GROUP BY cu.id, cu.company_name
ORDER BY orders, cu.company_name
LIMIT 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 exist
SELECT COUNT(*) AS rows_returned
FROM customer cu
LEFT 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 remain
SELECT COUNT(*) AS rows_returned
FROM customer cu
LEFT OUTER JOIN orders o ON o.customer_id = cu.id
WHERE 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_orders
FROM customer cu
LEFT OUTER JOIN orders o ON o.customer_id = cu.id
WHERE o.id IS NULL;
SELECT COUNT(*) AS customers_without_orders
FROM customer cu, orders o
WHERE 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.

A cross join returns the cartesian product of the two sources. CROSS JOIN can be replaced by a comma.

SELECT COUNT(*) AS combinations
FROM countries CROSS JOIN category; -- 25 countries x 32 categories
combinations
800

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 orders
FROM (SELECT id AS customer_id, company_name FROM customer) c
NATURAL JOIN (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) o
ORDER BY o.n DESC, c.customer_id
LIMIT 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.

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 orders
FROM MATCH (cu:customer)-[:resides_in]->(ci:city),
orders o
WHERE o.customer_id = cu.id
AND ci.name = 'London'
GROUP BY cu.company_name
ORDER BY orders DESC, cu.company_name
LIMIT 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.

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.

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 customer
FROM orders o
ORDER BY o.id
LIMIT 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

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 cities
FROM countries c
WHERE 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 followers
FROM MATCH (cu:customer)-[:follows]->(b:brand)
GROUP BY b.name
ORDER BY followers DESC, b.name
LIMIT 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.

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 shipping
UNION ALL SELECT 2, 'express'
UNION ALL SELECT 3, 'pickup';

As a derived table, joined with a real table:

SELECT t.code, c.name
FROM (VALUES ('FRA'), ('DEU'), ('ITA')) AS t(code)
INNER JOIN countries c ON c.code = t.code
ORDER BY c.name;
code name
FRA France
DEU Germany
ITA Italy

VALUES with several rows is also used in INSERT.

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 FROM clause whose rows are locked. Without OF, all tables and views of the FROM clause are locked.

Lock the orders that still have to be shipped, then mark them as shipped in the same transaction:

SELECT id, shipped_date
FROM orders
WHERE shipped_date IS NULL
ORDER BY id
FOR 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.id
WHERE o.shipped_date IS NULL
FOR UPDATE OF o; -- lock only the orders rows
SELECT * FROM orders o
INNER JOIN (SELECT * FROM order_items WHERE quantity > 5) big ON big.order_id = o.id
WHERE o.shipped_date IS NULL
FOR UPDATE; -- a derived table can be referenced