SELECT
Read rows: joins in written order, conditions with AND, OR and subqueries, aggregates, set operations, ordering and pagination.
In this article
- Syntax
- How a statement runs
- Examples
- Point lookup
- Join
- Outer join
- Subquery
- Conditions with OR, IN and LIKE
- Aggregate
- Expressions in the select list
- Set operations and derived tables
- Order and page
- Select list
- FROM and JOIN
- WHERE
- No implicit type conversion
- How a condition is executed
- Aggregates
- Set operations
- ORDER BY, LIMIT and OFFSET
- Limitations
- See also
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.
| Path | Runs | Statements |
|---|---|---|
| Step chain | One 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 layer | Each 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
ONcondition’s top-levelANDterms, and tests the wholeONfor 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
ASalias, 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. SELECTwith noFROMreturns one row:SELECT 1 + 1.
FROM and JOIN
FROM <table> [AS <alias>]. The bare alias formFROM t ais not accepted.sys.<view>reads the catalog, for examplesys.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 perON. 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,RIGHTandFULL [OUTER] JOIN,CROSS JOINand comma joins,ONover any condition, andUSING (col, ...). An outer join fills the unmatched side withNULL. AWHEREcondition 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:
| Form | Example |
|---|---|
| Compare with a value | base_fare >= 100, operators = != < <= > >=. The value can also be on the left: 20 < baggage_kg |
| Compare with another column | t.flight_id = f.id |
| Compare with a scalar subquery | base_fare > (SELECT ...) |
IN / NOT IN a list | id IN (1, 3) |
IN / NOT IN a subquery | id IN (SELECT passenger_id FROM tickets) |
EXISTS / NOT EXISTS | EXISTS (SELECT ...) |
| Range | baggage_kg BETWEEN 10 AND 25, NOT BETWEEN (inclusive) |
| Pattern | name LIKE 'K%', NOT LIKE. % matches any run of bytes, _ one byte; case-sensitive |
| Null test | note IS NULL, note IS NOT NULL |
| Date and time | DATE(departs) = '2026-11-02', departs < NOW() |
- Only top-level
ANDterms can become a key. A condition that holdsORorNOT, a multi-valueINlist,NOT BETWEENorLIKEfilters 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 separateANDterm. - Subqueries can be correlated and nested up to 4 levels deep.
- Comparisons with
NULLare unknown, socol = NULLmatches nothing. UseIS NULL. NOT IN (SELECT ...)is unknown, and keeps no row, when the subquery returns aNULLand no match, or when the left value isNULLand 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 type | Write | Refused |
|---|---|---|
| Integer types | n = 20 | n = '20', n = 20.0 |
char, varchar | s = '5' | s = 5 |
bool | ok = 0, ok = 1 | ok = '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 auint645); - decimals of the same width and scale;
charwithvarchar, as text;datewithdate, andtimestampwithtimestamp.
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
| Condition | Access |
|---|---|
Primary key = | Direct key lookup |
Primary key range or BETWEEN | Range 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 LIKE | A filter on the rows the step reads |
Aggregates
COUNT,SUM,MIN,MAX,AVG, with optionalDISTINCTinside.COUNT(*)counts rows.GROUP BYtakes columns, without parentheses. On the query layer it also takes expressions, andHAVINGfilters groups by their keys and aggregates.- Every selected column must be in
GROUP BY. SUMis checked: overflow fails the statement.AVGof an integer column is refused (it would invent digits);AVGofdecimal(p, s)returns scales.- At most
aggregate_max_groupsgroups (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,INTERSECTandEXCEPT, eachDISTINCT(the default) orALL.INTERSECTbinds 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, soSELECT NULL UNION SELECT 1is refused: a loneNULLisvarchar. UseCAST. - Columns are named by the left side.
ORDER BYa position or an output name,LIMITandOFFSETapply to the whole result. - A statement cannot begin with
(:(SELECT ...) UNION ...is answeredERR 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. SoLIMIT n OFFSET mwithoutORDER BYalways returns the same rows. ORDER BYtakes up to 8 sort keys from any table in the statement, eachASC(default) orDESC. 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.NULLsorts as the largest value: last withASC, first withDESC.- A sort must read every matching row before it can return the first one.
LIMITcaps the memory a sort uses (offset + limitrows), not the rows it reads. - A sort that would hold more than
sort_max_rowsrows fails the statement; it never spills to disk. OFFSETreads 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 noLATERAL. Several of these are answered with a parse error rather than a refusal by name, for exampleERR expected 'FROM', got 'ON' at byte 16forDISTINCT ON. - A derived table cannot read a column of the enclosing query.
USINGis refused underFULL JOIN, andSELECT *over aUSINGjoin is refused.sys.*views supportWHERE(ANDonly),ORDER BY,LIMITandOFFSET, but not joins, aggregates,ORor the query layer’s forms. See SHOW and DESCRIBE.