SQL Console
The SQL Console runs one SQL statement at a time against open documents and CSV files: a SELECT, or an UPDATE, INSERT, or DELETE that edits a document. Conditions, data types, operators, and functions follow SQL Expressions.
SELECT category, SUM(amount) AS total
FROM customers
WHERE amount > 1000
GROUP BY category
ORDER BY total DESC;
Columns are text. amount > 1000 compares numbers because 1000 is a number, but ORDER BY amount sorts text. See Data Types.
Tables and Columns
A table is an open document or a CSV file:
- A plain name matches an open document, ignoring case: a file by its name without the extension (
customersforcustomers.csv), or an untitled document by its name (Untitled-1). Tabs restored from the last session count before they are shown. When two open documents share the name, use a path. - A path, a
file://URL,@file:, or@untitled:names one file or document. A Windows path such as"C:/data/customers.csv"works too.
Quote a name that has spaces or other special characters, and double a quote inside it.
SELECT * FROM customers;
SELECT * FROM "/path/to/file.csv";
SELECT * FROM "file:///path/to/file.csv";
SELECT * FROM "@file:/path/to/file.csv";
SELECT * FROM "@untitled:Untitled-1";
An open document is read as it is, including unsaved edits, and its table holds only the data rows between its header and footer rows. A file that is not open is read from disk.
Columns are named as in Referencing Columns. Every table has rowid, but SELECT *, table.*, NATURAL JOIN, and USING leave it out.
SELECT
SELECT supports DISTINCT, DISTINCT ON, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, joins, subqueries, UNION, INTERSECT, EXCEPT, VALUES, WITH, WITH RECURSIVE, and window functions.
As in PostgreSQL, the conditions joined by AND in WHERE can run in any order, and a condition on one table can run before a join. To keep a CAST from failing on rows that another condition excludes, guard it in the same expression: CASE WHEN q.allow = 1 THEN CAST(p.raw AS BIGINT) > 0 END.
Sorting
ORDER BY takes an output name, a 1-based column position, or an expression, with ASC or DESC and NULLS FIRST or NULLS LAST. Positions in ORDER BY and GROUP BY count the columns after * and table.* are expanded.
Text sorts in code point order, so a column of numbers sorts '10' before '9'. Sort by TRY_CAST(amount AS numeric) to sort numbers. ORDER BY rowid keeps the file’s order.
To sample up to ten rows at random, sort by RANDOM():
SELECT * FROM customers ORDER BY RANDOM() LIMIT 10;
DISTINCT ON
DISTINCT ON (keys) keeps the first row of each group of rows with equal keys. ORDER BY starts with the keys, in any order, and the expressions after them choose the first row. Without ORDER BY, any row of the group can be returned. LIMIT and OFFSET apply to the rows kept.
This query returns the latest order of each customer. It skips blank or invalid dates, compares dates written with different UTC offsets as instants, and keeps the earlier row in the file when two orders share the latest time.
SELECT DISTINCT ON (customer) *
FROM orders
WHERE TRY_CAST(ordered_at AS TIMESTAMPTZ) IS NOT NULL
ORDER BY customer, TRY_CAST(ordered_at AS TIMESTAMPTZ) DESC, rowid;
Joins
Joins are INNER, LEFT, RIGHT, FULL, and CROSS, with ON, USING, or NATURAL. After USING or NATURAL JOIN, * includes each join key once.
A LATERAL subquery can read columns from earlier items in FROM. Use it after a comma, CROSS JOIN, JOIN … ON, or LEFT JOIN … ON. This query returns the three largest orders of each customer, and one row with a NULL amount for a customer with no orders:
SELECT c.id, top.amount
FROM customers AS c
LEFT JOIN LATERAL (
SELECT o.amount::double AS amount
FROM orders AS o
WHERE o.customer_id = c.id
ORDER BY amount DESC NULLS LAST
LIMIT 3
) AS top ON true
ORDER BY c.id, top.amount DESC NULLS LAST;
Subqueries
A subquery can be a scalar value, or be used with IN, EXISTS, or a comparison with ANY or ALL, such as x = ANY (SELECT …) or x <> ALL (SELECT …). ANY and ALL treat NULL and empty results as they do with ARRAY[…].
Subtotals with ROLLUP and CUBE
ROLLUP returns detail groups, subtotals, and a grand total in one query.
SELECT region, product, SUM(amount) AS sales,
GROUPING(region, product) AS level
FROM orders
GROUP BY ROLLUP (region, product)
ORDER BY level, region, product;
Here level is 0 for a region and product, 1 for a region subtotal, and 3 for the grand total. GROUPING sets the bit of each argument to 1 when the row’s grouping set leaves that expression out, with the rightmost argument at bit 0. Each argument must match a grouping expression. A NULL in the data keeps its bit at 0, so GROUPING tells subtotal rows from NULL values.
| Grouping clause | Groups returned |
|---|---|
GROUP BY GROUPING SETS ((region), (product), ()) |
Totals by region, totals by product, and the grand total |
GROUP BY ROLLUP (region, product) |
Totals by region and product, totals by region, and the grand total |
GROUP BY CUBE (region, product) |
All four combinations, including totals by product alone |
GROUP BY year, ROLLUP (region, product) |
The three rollup levels within each year |
Repeated grouping sets return repeated groups; GROUP BY DISTINCT removes them.
Table Functions
These functions return rows in FROM. They can read columns from earlier items in FROM, take column aliases, and add WITH ORDINALITY for a 1-based ordinality column.
| Function | Rows |
|---|---|
JSON_EACH(json), JSON_EACH_TEXT(json) |
One row per object member, with key and value |
JSON_ARRAY_ELEMENTS(json), JSON_ARRAY_ELEMENTS_TEXT(json) |
One row per JSON array element, in value. For an SQL array, convert it first: JSON_ARRAY_ELEMENTS_TEXT(ARRAY_TO_JSON(ARRAY[10,20])) |
GENERATE_SERIES(start, stop [, step]) |
Numbers from start to stop, floating point when any argument is, or timestamps with an interval step. Dates are read as timestamps with time zone, as in PostgreSQL. The column is generate_series |
STRING_TO_TABLE(string, delimiter [, null_string]) |
One row per field. A NULL delimiter splits into characters, and an empty delimiter keeps the string whole. Fields equal to null_string are SQL NULL. Empty or NULL input returns no rows |
REGEXP_SPLIT_TO_TABLE(string, pattern [, flags]) |
One row per field between pattern matches, with the same patterns and flags as REGEXP_SPLIT_TO_ARRAY |
The TEXT forms of the JSON functions return text; the others return JSON.
SELECT t.name, s.tag, s.position
FROM t, STRING_TO_TABLE(t.tags, ',') WITH ORDINALITY AS s(tag, position)
ORDER BY t.name, s.position;
SELECT generate_series
FROM GENERATE_SERIES(TIMESTAMP '2024-01-01', TIMESTAMP '2024-01-03', INTERVAL '1 day');
Aggregate Functions
| Function | Description |
|---|---|
COUNT(*), COUNT(value) |
Row count, or non-NULL values |
SUM(value), AVG(value) |
Sum and average. Text is read as a number, and the sum of text is floating point. A sum of integers outside the 64-bit range is an error |
STDDEV_SAMP(value) or STDDEV(value), STDDEV_POP(value) |
Sample or population standard deviation |
VAR_SAMP(value) or VARIANCE(value), VAR_POP(value) |
Sample or population variance |
CORR(y, x), COVAR_SAMP(y, x), COVAR_POP(y, x) |
Correlation, sample covariance, or population covariance |
MIN(value), MAX(value) |
Smallest and largest. Text uses code point order. For booleans, false sorts before true |
STRING_AGG(value, delimiter) |
Join non-NULL values as text, including integers |
ARRAY_AGG(value) |
Collect values into an SQL array, keeping NULL. Arrays of the same shape, each nonempty and non-NULL, make a multidimensional array. For json or jsonb values, use JSON_AGG |
JSON_AGG(value), JSON_OBJECT_AGG(key, value) |
Collect values into a JSON array, or key/value pairs into a JSON object. NULL values become JSON null. Keys must be non-NULL scalars, and duplicate keys are kept |
BOOL_AND(value) or EVERY(value), BOOL_OR(value) |
Boolean AND or OR |
BIT_AND(value), BIT_OR(value), BIT_XOR(value) |
Bitwise AND, OR, or XOR. String and NULL literals take type BIGINT. Cast text columns to BIGINT first |
Aggregates accept FILTER (WHERE condition), and DISTINCT in calls without OVER. To skip NULL values, add FILTER (WHERE value IS NOT NULL). ORDER BY inside the call sets the order of STRING_AGG, ARRAY_AGG, and the JSON aggregates; in a window aggregate, ORDER BY in OVER does.
The standard deviation, variance, and correlation aggregates read text as numbers, skip NULL (for two-argument aggregates, a pair with either value missing), and return double precision. A result outside the finite double precision range is NULL.
Ordered-Set Aggregates
For a median, use PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x). These functions ignore NULL sort keys and return NULL when the group has no qualifying values. Use DESC to reverse the order, or append FILTER (WHERE condition) to select the input rows.
| Function | Description |
|---|---|
PERCENTILE_CONT(f) WITHIN GROUP (ORDER BY x) |
Interpolates between adjacent values. Returns a floating-point number for numbers and numeric text, or an interval for intervals |
PERCENTILE_DISC(f) WITHIN GROUP (ORDER BY x) |
Returns the first input value whose cumulative proportion reaches f. Text uses code point order |
MODE() WITHIN GROUP (ORDER BY x) |
Returns the most frequent input value. Ties go to the first value in the specified order |
The fraction f is a single number from 0 to 1, inclusive. It can depend on the group key. A NULL fraction returns NULL. If floating-point interpolation overflows, the result is NULL.
Window Functions
| Function | Description |
|---|---|
ROW_NUMBER() |
1-based position in the partition |
RANK(), DENSE_RANK() |
Rank. RANK leaves gaps after ties; DENSE_RANK does not |
PERCENT_RANK(), CUME_DIST() |
Relative rank |
NTILE(buckets) |
Bucket number |
LAG(value [, offset [, default]]), LEAD(…) |
Value from another row |
FIRST_VALUE(value), LAST_VALUE(value), NTH_VALUE(value, n) |
Value at a position in the frame |
Aggregates such as SUM also take OVER. A frame is ROWS, RANGE, or GROUPS, and may use EXCLUDE. WINDOW names a window.
SELECT
day,
SUM(amount) OVER (
PARTITION BY category
ORDER BY day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving
FROM sales;
Changing a Document
UPDATE, INSERT, and DELETE edit the document, and the file changes when you save it. One undo in that tab reverts the whole statement. A file that is not open opens in a background tab.
UPDATE customers SET price = ROUND(price * 1.1, 2) WHERE category = 'A';
INSERT INTO customers (id, name) VALUES ('101', 'Ari');
DELETE FROM customers WHERE status = 'closed';
- NULL is written as an empty cell, including the result of arithmetic on a cell that is not a number (
price * 1.1on a blank price). Other values are written as results show them. INSERTappends rows after the data and above any footer rows, and leaves unlisted columns empty. The source may beVALUESor aSELECT.UPDATE … FROMandDELETE … USINGread other tables. Name the changed table inUPDATEorDELETE, and the other tables inFROMorUSING. InSET, write the column name alone (SET price = 1). AnUPDATEfails whenFROMmatches the same row more than once.- A statement changes one table.
WITHand joins inFROM,USING, or the source query are allowed, but the changed table cannot be a common table expression or a join. RETURNING, conflict handling, andORDER BYorLIMITon the change are not supported.
Rewrites
Earlier versions of the SQL Console ran on SQLite. Write the SQL Console form for these SQLite forms.
| SQLite | SQL Console |
|---|---|
[Category] |
"Category" |
strftime('%Y', x) |
TO_CHAR(TRY_CAST(x AS TIMESTAMP), 'YYYY') |
date(x), datetime(x) |
TRY_CAST(x AS DATE), TRY_CAST(x AS TIMESTAMP) |
date('now') |
(CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date |
date('now', '-7 days') |
(CURRENT_TIMESTAMP AT TIME ZONE 'UTC' + INTERVAL '-7 days')::date |
datetime('now') |
DATE_TRUNC('second', CURRENT_TIMESTAMP AT TIME ZONE 'UTC') |
printf('%d items', n) |
FORMAT('%s items', n) |
printf('%.2f', n) |
TO_CHAR(n, 'FM999999990.00') for two decimal places, with one digit per 9. Use ROUND(n, 2) for a rounded number |
group_concat(x, ',') |
STRING_AGG(x, ',') |
json_extract(x, '$.k') |
x::json ->> 'k' |
json_each(x) |
JSON_EACH_TEXT(x) for an object, JSON_ARRAY_ELEMENTS_TEXT(x) for an array, in FROM |
instr(x, 'a') |
STRPOS(x, 'a') |
ifnull(x, ''), iif(p, a, b) |
COALESCE(x, ''), CASE WHEN p THEN a ELSE b END |
name LIKE 'a%' |
name ILIKE 'a%' to ignore case. LIKE is case-sensitive |
name REGEXP '^a' |
name ~ '^a', name ~* '^a' to ignore case, or REGEXP_LIKE(name, '^a') |
CAST(price AS REAL) > 1000 |
price > 1000 |
SELECT price * 2 AS total FROM t WHERE total > 1000 |
Write WHERE price * 2 > 1000 or filter total in an outer query. The same rule applies to HAVING |
SELECT category, price FROM t GROUP BY category |
Group price as well, or aggregate it |
rowid of the first data row is 1 |
rowid counts header rows. With one header row, the first data row is 2 |
CAST of blank or invalid numeric or date/time text is an error. Use TRY_CAST to get NULL instead.
Limits
When table data and results do not fit in memory, the desktop app moves them to temporary files, which it deletes when it exits, or on the next start after a crash. A statement stops with an error when the disk runs out of space. The web app has no temporary files, so a statement that does not fit in memory stops with an error that shows the limit.
To fit, select fewer rows or columns, or filter tables before joining them.