SELECT

v3.2.0

Read rows: joins in written order, conditions with AND, OR and subqueries, aggregates, set operations, ordering and pagination.

In this article

Reads rows from one table or a chain of joined tables. The statement is the plan: tables are visited in the order the FROM clause lists them, and how each one is accessed is decided from the statement’s shape and the catalog, never from data statistics.

Syntax

SELECT [DISTINCT] { * | <item> [AS <alias>] [, ...] }
FROM <table> [AS <alias>]
    [{ [INNER] JOIN | LEFT | RIGHT | FULL [OUTER] JOIN } <table> [AS <alias>] { ON <condition> | USING (<column>, ...) }] ...
    [CROSS JOIN <table> [AS <alias>]] ...
[WHERE <condition>]
[GROUP BY <item> [, ...]]
[HAVING <condition>]
[ORDER BY <item> [ASC | DESC] [, ...]]
[LIMIT <n>] [OFFSET <m>]

<select> { UNION | INTERSECT | EXCEPT } [ALL | DISTINCT] <select>

The clauses must appear in this order. A <table> can also be a derived table, (SELECT ...) AS <name>. Column names match ignoring case.

How a statement runs

A SELECT runs on one of two paths. The reply is the same kind of result either way; what differs is how the work is done.

PathRunsStatements
Step chainOne step per table, in written order, each with a direct access method (key lookup, range, index, Cabin, scan)Columns and aggregates in the select list; inner equi-joins; WHERE; GROUP BY over columns; ORDER BY over columns; LIMIT and OFFSET
Query layerEach table is read by its own step chain, carrying the WHERE conditions that read that table alone. Joins, the remaining conditions, grouping, the select list and the order are then computed over the rows in hand.Everything else: expressions and aliases in the select list, SELECT * across a join, outer and cross joins, ON conditions that are not one column equality, DISTINCT, HAVING, ORDER BY over grouped results or by position or alias, set operations, derived tables, subqueries in the select list

The engine tries the step chain first and falls back to the query layer when the step chain refuses the statement. A query-layer statement:

  • holds every row it reads in memory, bounded by sort_max_rows (default 1,048,576). Exceeding it fails the statement; nothing is truncated;
  • records no Waystone trail and cannot be run under ANALYZE;
  • hashes a join on the column equalities among its ON condition’s top-level AND terms, and tests the whole ON for each candidate pair.

Examples

Point lookup

SELECT * FROM items WHERE id = 1;

Join

SELECT p.name, t.baggage_kg
FROM passengers AS p JOIN tickets AS t ON t.passenger_id = p.id
WHERE t.baggage_kg BETWEEN 10 AND 25;

Outer join

SELECT p.name, t.seat FROM passengers AS p LEFT JOIN tickets AS t ON t.passenger_id = p.id;

A row of passengers with no ticket comes back with NULL for t.seat.

Subquery

SELECT * FROM passengers AS p
WHERE NOT EXISTS (SELECT * FROM tickets AS t WHERE t.passenger_id = p.id AND t.checked_in = 1);

Conditions with OR, IN and LIKE

SELECT * FROM flights WHERE id IN (1, 3);
SELECT name FROM passengers WHERE (member = 1 AND joined_on < '2020-01-01') OR id = 8;
SELECT name FROM passengers WHERE name LIKE 'K%';

Aggregate

SELECT flight_id, COUNT(*), SUM(baggage_kg) FROM tickets GROUP BY flight_id;
SELECT flight_id, COUNT(*) AS n FROM tickets GROUP BY flight_id HAVING COUNT(*) >= 3 ORDER BY n DESC;

Expressions in the select list

SELECT code, base_fare * 2 AS doubled FROM flights ORDER BY doubled DESC LIMIT 2;
  code  doubled
------  -------
KE0303  2360.00
KE0101   425.00

Set operations and derived tables

SELECT id FROM items EXCEPT SELECT item_id FROM purchases;
SELECT x.n FROM (SELECT COUNT(*) AS n FROM tickets) AS x;

Order and page

SELECT name, joined_on FROM passengers ORDER BY joined_on DESC LIMIT 3;
SELECT * FROM tickets WHERE id > 4 LIMIT 3;   -- keyset pagination

Select list

  • Columns, qualified (p.name) or bare (name), *, <table>.*, and aggregates run on the step chain.
  • Value expressions, with an optional AS alias, run on the query layer. They use the grammar of UPDATE … SET: operators, CASE, COALESCE, CAST, the scalar functions, and a scalar subquery, which may be correlated.
  • A subquery used as a value returns one column and at most one row. More rows fail the statement: ERR a subquery used as a value returned 2 rows (byte 13); it may return at most one.
  • A column heading is the alias if there is one, then the column as written (p.name), then an aggregate in canonical form (count(*)), then the expression’s text.
  • SELECT with no FROM returns one row: SELECT 1 + 1.

FROM and JOIN

  • FROM <table> [AS <alias>]. The bare alias form FROM t a is not accepted.
  • sys.<view> reads the catalog, for example sys.tables. See catalog views.
  • Joins run in the order you write them. Nothing reorders them.
  • On the step chain, a join is an inner equi-join, JOIN <table> ON <x.col> = <y.col>, one equality per ON. A join on the joined table’s primary key is a direct key lookup per row; any other join column runs as a scan, or an index or Cabin lookup, of that table.
  • On the query layer: LEFT, RIGHT and FULL [OUTER] JOIN, CROSS JOIN and comma joins, ON over any condition, and USING (col, ...). An outer join fills the unmatched side with NULL. A WHERE condition is applied after the joins.
  • To join a table to itself, give it two aliases: FROM t AS a JOIN t AS b ON ....

WHERE

A condition is one of these forms, combined with AND, OR, NOT and parentheses:

FormExample
Compare with a valuebase_fare >= 100, operators = != < <= > >=. The value can also be on the left: 20 < baggage_kg
Compare with another columnt.flight_id = f.id
Compare with a scalar subquerybase_fare > (SELECT ...)
IN / NOT IN a listid IN (1, 3)
IN / NOT IN a subqueryid IN (SELECT passenger_id FROM tickets)
EXISTS / NOT EXISTSEXISTS (SELECT ...)
Rangebaggage_kg BETWEEN 10 AND 25, NOT BETWEEN (inclusive)
Patternname LIKE 'K%', NOT LIKE. % matches any run of bytes, _ one byte; case-sensitive
Null testnote IS NULL, note IS NOT NULL
Date and timeDATE(departs) = '2026-11-02', departs < NOW()
  • Only top-level AND terms can become a key. A condition that holds OR or NOT, a multi-value IN list, NOT BETWEEN or LIKE filters the rows its step reads and is never used for a key lookup, a range, an index or a Cabin. Write the selective part as a separate AND term.
  • Subqueries can be correlated and nested up to 4 levels deep.
  • Comparisons with NULL are unknown, so col = NULL matches nothing. Use IS NULL.
  • NOT IN (SELECT ...) is unknown, and keeps no row, when the subquery returns a NULL and no match, or when the left value is NULL and the subquery returns any row. Against an empty subquery it is true.
  • Inequality is !=. <> is not accepted.

No implicit type conversion

A comparison converts no type. A literal must be written the way the compared column’s type is written, and a mismatch is refused when the statement is compiled, with the literal’s byte position. It is refused whether or not a row would match.

Column typeWriteRefused
Integer typesn = 20n = '20', n = 20.0
char, varchars = '5's = 5
boolok = 0, ok = 1ok = 'true'
date, timestamp'2026-10-01', or the epoch integer
decimal(p, s)'12.34', 12.34, or an integer
kdbs> SELECT * FROM tickets WHERE baggage_kg = '23';
                                               ^
ERR column 'baggage_kg' literal at byte 41: expects an integer literal - unquoted, with no fraction

In a statement the query layer runs, a bool column is used as a condition by itself, WHERE checked_in or WHERE NOT checked_in; checked_in = 1 is refused there (integer literal cannot be used as bool). There are no TRUE and FALSE literals.

An integer outside an int8, int16 or int32 column’s range is not refused; it simply matches no row. On an int64 or uint64 column, an integer outside the type’s range is refused, a negative one on uint64 included.

Two columns, in WHERE, in ON, or a column against the value of IN (SELECT ...) or a scalar subquery, can be compared only within one family:

  • integers of any width and signedness, compared by value (an int32 -1 is less than a uint64 5);
  • decimals of the same width and scale;
  • char with varchar, as text;
  • date with date, and timestamp with timestamp.

Any other pair is refused:

kdbs> SELECT p.name FROM passengers AS p JOIN tickets AS t ON t.note = p.id
                                                              ^
ERR cannot compare 'note' (varchar) with 'id' (int64); this engine converts no type implicitly at byte 56

How a condition is executed

ConditionAccess
Primary key =Direct key lookup
Primary key range or BETWEENRange walk over the key order
Other column =Secondary index if one exists, otherwise a Cabin, otherwise a filtered scan
Anything holding OR, NOT, an IN list or LIKEA filter on the rows the step reads

Aggregates

  • COUNT, SUM, MIN, MAX, AVG, with optional DISTINCT inside. COUNT(*) counts rows.
  • GROUP BY takes columns, without parentheses. On the query layer it also takes expressions, and HAVING filters groups by their keys and aggregates.
  • Every selected column must be in GROUP BY.
  • SUM is checked: overflow fails the statement. AVG of an integer column is refused (it would invent digits); AVG of decimal(p, s) returns scale s.
  • At most aggregate_max_groups groups (default 65,536). Exceeding it fails the statement.
  • Aggregates are allowed inside subqueries, for example IN (SELECT passenger_id FROM tickets GROUP BY passenger_id HAVING COUNT(*) > 1).

Set operations

  • UNION, INTERSECT and EXCEPT, each DISTINCT (the default) or ALL. INTERSECT binds tighter than the other two.
  • The two sides’ columns are paired by position and must have one type each; two text types meet as varchar. There is no implicit conversion, so SELECT NULL UNION SELECT 1 is refused: a lone NULL is varchar. Use CAST.
  • Columns are named by the left side. ORDER BY a position or an output name, LIMIT and OFFSET apply to the whole result.
  • A statement cannot begin with (: (SELECT ...) UNION ... is answered ERR unknown command. Put the parenthesized side second.

ORDER BY, LIMIT and OFFSET

  • On the step chain, without ORDER BY, the row order is still defined: tables in written order, and rows within a table in primary-key order. So LIMIT n OFFSET m without ORDER BY always returns the same rows.
  • ORDER BY takes up to 8 sort keys from any table in the statement, each ASC (default) or DESC. A sort column does not have to be selected. The query layer also accepts a position (ORDER BY 2), an output alias or an expression.
  • ORDER BY <primary key> ascending is free: rows are already in that order. Every other order is a sort.
  • NULL sorts as the largest value: last with ASC, first with DESC.
  • A sort must read every matching row before it can return the first one. LIMIT caps the memory a sort uses (offset + limit rows), not the rows it reads.
  • A sort that would hold more than sort_max_rows rows fails the statement; it never spills to disk.
  • OFFSET reads and discards the rows it skips. For deep pages, use keyset pagination: WHERE id > <last id> LIMIT n.

Limitations

  • No WITH (CTEs) and no window functions (OVER, FILTER, WINDOW, QUALIFY).
  • No NATURAL JOIN, DISTINCT ON, NULLS FIRST / NULLS LAST, LIKE ... ESCAPE, ILIKE, and no LATERAL. Several of these are answered with a parse error rather than a refusal by name, for example ERR expected 'FROM', got 'ON' at byte 16 for DISTINCT ON.
  • A derived table cannot read a column of the enclosing query.
  • USING is refused under FULL JOIN, and SELECT * over a USING join is refused.
  • sys.* views support WHERE (AND only), ORDER BY, LIMIT and OFFSET, but not joins, aggregates, OR or the query layer’s forms. See SHOW and DESCRIBE.

See also