We wrote 42 queries covering the SQL people look up most and ran each one on an invented table of 4,734 sales orders in DuckDB 2.0.1 and 1.3.2, pasting the real output under it. Then we ran the same 42 queries, unchanged, in PostgreSQL 16.15 and MySQL 8.4.13 in Docker and in SQLite 3.50.4 through Python, checked 43 dialect details across the four, and timed four queries on a generated million-row table with and without an index.
The short answer: SQL is written SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, but runs FROM and joins first, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY and LIMIT. That is why WHERE can't filter on SUM() and HAVING can. The patterns worth keeping on one page: LEFT JOIN plus IS NULL for rows with no match, ROW_NUMBER() for the top row per group, LAG() for change since last month, SUM() OVER (ORDER BY ...) for a running total, and ON CONFLICT for an upsert. Dialects differ in the details: SQL Server writes TOP (10), MySQL reads || as OR, and ILIKE works in Postgres and DuckDB but not in MySQL or SQLite. Checked 3 December 2026.
Fastero
Connect your database. Ask questions. Get dashboards.
Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.
Try free →SQL dialect differences at a glance
We ran the Postgres, DuckDB, MySQL and SQLite cells on 3 December 2026. The SQL Server column is from Microsoft's documentation, since we had no SQL Server to run.
| Task | Postgres, DuckDB | MySQL 8.4 | SQL Server | SQLite |
|---|---|---|---|---|
| First 10 rows | LIMIT 10 |
LIMIT 10 |
SELECT TOP (10) ... |
LIMIT 10 |
| Join strings | a || b |
CONCAT(a, b); || is OR |
a + b; || from 2025 |
a || b |
| Start of month | date_trunc('month', d) |
DATE_FORMAT(d, '%Y-%m-01') |
DATETRUNC(month, d), 2022+ |
date(d, 'start of month') |
| Days between | d2 - d1 |
DATEDIFF(d2, d1) |
DATEDIFF(day, d1, d2) |
julianday(d2) - julianday(d1) |
| Ignore case | ILIKE |
LIKE already ignores case |
LIKE, by collation |
LIKE, ASCII letters only |
| Upsert | ON CONFLICT (k) DO UPDATE |
ON DUPLICATE KEY UPDATE |
MERGE |
ON CONFLICT (k) DO UPDATE |
| Booleans | BOOLEAN, true and false |
BOOL is TINYINT(1) |
bit, 1 and 0 |
Integers 1 and 0 |
| Recursive CTE | WITH RECURSIVE |
WITH RECURSIVE, 1,000 levels |
WITH, 100 levels |
WITH, RECURSIVE optional |
BigQuery, where it differs (from Google's docs, not run): DATE_TRUNC(d, MONTH), DATE_DIFF(d2, d1, DAY), MERGE for upserts, BOOL, and no ILIKE: compare LOWER(x) or use a case-insensitive collation. It writes LIMIT and accepts ||.
The same expressions returned four different answers:
| Expression | Postgres 16 | MySQL 8.4 | SQLite 3.50 | DuckDB 2.0 |
|---|---|---|---|---|
7 / 2 |
3 | 3.5000 | 3 | 3.5 |
1 / 0 |
Error | NULL and a warning | NULL | inf |
'a' || 'b' |
ab | 0 and three warnings | ab | ab |
CONCAT('a', NULL, 'b') |
ab | NULL | ab | ab |
'Desk' LIKE 'desk' |
false | true | true | false |
NULLs in ORDER BY x |
Last | First | First | Last |
| 31 January plus 1 month | 2026-02-28 | 2026-02-28 | 2026-03-03 | 2026-02-28 |
SELECT TRUE |
t | 1 | 1 | true |
ROUND(double, 2) |
Error | Works | Works | Works |
FULL OUTER JOIN |
Works | Error | Works | Works |
DuckDB's date_diff('month', ...) counts month boundaries: from 31 January to 1 February it returned 1, where MySQL's TIMESTAMPDIFF(MONTH, ...) and Postgres's age() returned 0. Microsoft's docs say SQL Server's DATEDIFF also counts "datepart boundaries crossed".
How portable is this cheat sheet?
We ran all 42 queries on this page as written. Postgres failed only on DuckDB extras: SEMI JOIN, ANTI JOIN, QUALIFY and dayname(). MySQL failed on 18, including FULL OUTER JOIN, ||, FILTER, ON CONFLICT, RETURNING and date_trunc. The one different answer in SQLite and MySQL is the same query: LIKE '%desk%' matched 685 rows there and 340 in DuckDB and Postgres, because their LIKE ignores case.

Each of the 42 queries run as written on the sample sales table in each database, measured 3 December 2026.
Basic SQL commands: SELECT, WHERE, ORDER BY and LIMIT
Every example uses one table, sales: invented orders from November 2024 to October 2026 with the columns order_id, order_date, region, channel, segment, category, product, quantity, unit_price and revenue. Outputs are from DuckDB 2.0.1, shown in psql's layout.
SELECT order_id, order_date, region, product, revenue
FROM sales
WHERE region = 'West'
AND order_date >= '2026-01-01'
AND product IN ('Standing desk', 'Office chair')
ORDER BY revenue DESC, order_id
LIMIT 3; order_id | order_date | region | product | revenue
----------+------------+--------+---------------+---------
14121 | 2026-08-09 | West | Standing desk | 1808.6
12703 | 2026-02-10 | West | Standing desk | 1806.48
13174 | 2026-04-22 | West | Standing desk | 1806.48
(3 rows)The second sort key matters. Orders 12703 and 13174 tie on revenue, and MySQL returned them in the opposite order until we added order_id. Without a unique tiebreaker, LIMIT can return different rows on different runs.
More filters, with the rows each returned:
SELECT DISTINCT region FROM sales; -- 4 rows
-- BETWEEN includes both ends
SELECT * FROM sales WHERE revenue BETWEEN 100 AND 200; -- 1,294
SELECT * FROM sales WHERE product LIKE 'S%'; -- 1,062
SELECT * FROM sales WHERE product NOT IN ('Cable kit', 'Desk lamp'); -- 3,824
SELECT * FROM sales WHERE region = 'West' OR quantity >= 10; -- 1,662
SELECT * FROM sales WHERE product ILIKE '%desk%'; -- 685
SELECT * FROM sales WHERE product LIKE '%desk%'; -- 340
-- page 3 of 10 rows per page
SELECT * FROM sales ORDER BY order_date DESC, order_id LIMIT 10 OFFSET 20;The order SQL runs in
| Step | Clause | What it can use |
|---|---|---|
| 1 | FROM, JOIN | Tables |
| 2 | WHERE | Columns of each row, no aggregates |
| 3 | GROUP BY | Columns, expressions |
| 4 | HAVING | Aggregates such as SUM(revenue) |
| 5 | SELECT | Everything above; aliases are born here |
| 6 | ORDER BY | Aliases from SELECT |
| 7 | LIMIT, OFFSET | The sorted result |
Postgres's manual puts the alias rule plainly: "An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead." DuckDB and SQLite are more lenient: both accepted SELECT 2*3 AS x WHERE x > 5 in our test.
GROUP BY, HAVING and aggregate functions
SELECT category,
COUNT(*) AS orders,
COUNT(DISTINCT product) AS products,
ROUND(SUM(revenue)) AS revenue,
ROUND(AVG(revenue), 2) AS avg_order
FROM sales
WHERE order_date >= '2026-01-01'
GROUP BY category
HAVING SUM(revenue) > 100000
ORDER BY revenue DESC; category | orders | products | revenue | avg_order
----------+--------+----------+----------+-----------
Hardware | 659 | 4 | 340685.0 | 516.97
Software | 622 | 3 | 170672.0 | 274.39
(2 rows)WHERE drops rows before grouping; HAVING drops groups after. COUNT(*) counts rows, COUNT(col) counts non-NULL values, and every column in SELECT must be in GROUP BY or inside an aggregate. In Postgres, ROUND(x, 2) needs a numeric: there is no two-argument ROUND for double precision, so write ROUND(AVG(revenue)::numeric, 2) there.
SQL joins cheat sheet, with example tables
Three customers and four orders. Cy has no orders, and order 104 belongs to a customer who isn't in the table:
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Ben'), (3, 'Cy');
CREATE TABLE orders (order_id INTEGER, customer_id INTEGER, amount INTEGER);
INSERT INTO orders VALUES (101, 1, 50), (102, 1, 20), (103, 2, 35), (104, 4, 10);
SELECT c.name, o.order_id, o.amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
ORDER BY c.id, o.order_id; name | order_id | amount
------+----------+--------
Ada | 101 | 50
Ada | 102 | 20
Ben | 103 | 35
Cy | NULL | NULL
(4 rows)Swap the join keyword and the same two tables give:
| Join | Rows | What you get |
|---|---|---|
JOIN (inner) |
3 | Orders with a known customer: Ada twice, Ben once |
LEFT JOIN |
4 | Every customer; Cy with NULLs |
RIGHT JOIN |
4 | Every order; 104 with a NULL name |
FULL OUTER JOIN |
5 | Both: Cy and order 104 included |
CROSS JOIN |
12 | Every customer paired with every order, 3 × 4 |
Semi join (EXISTS) |
2 | Ada and Ben, once each |
Anti join (NOT EXISTS) |
1 | Cy |
Semi, anti and self joins, with their output as comments:
-- semi join: customers with at least one order, each listed once
SELECT c.name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
ORDER BY c.name; -- Ada, Ben
-- anti join, two ways: customers with no orders
SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id); -- Cy
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.order_id IS NULL; -- Cy
-- DuckDB spells them out
SELECT * FROM customers SEMI JOIN orders ON orders.customer_id = customers.id
ORDER BY id; -- 1 Ada, 2 Ben
SELECT * FROM customers ANTI JOIN orders ON orders.customer_id = customers.id; -- 3 Cy
-- self join on staff(id, name, manager_id):
-- (1, Dana, NULL), (2, Eli, 1), (3, Fay, 1), (4, Gus, 2)
SELECT e.name AS employee, m.name AS manager
FROM staff e
LEFT JOIN staff m ON m.id = e.manager_id
ORDER BY e.id; -- Dana NULL, Eli Dana, Fay Dana, Gus EliAn inner join repeats Ada once per order; EXISTS returns her once. Prefer NOT EXISTS to NOT IN for anti joins: if the subquery returns a NULL, NOT IN matches nothing (see NULLs below). MySQL 8.4 has no FULL OUTER JOIN; the usual workaround is a LEFT JOIN UNION a RIGHT JOIN.
Subqueries and CTEs (WITH)
-- scalar subquery: orders above the average order
SELECT COUNT(*) AS above_avg
FROM sales
WHERE revenue > (SELECT AVG(revenue) FROM sales); -- 1423
-- correlated subquery: each region's largest order
SELECT region, order_id, revenue
FROM sales s
WHERE revenue = (SELECT MAX(revenue) FROM sales WHERE region = s.region)
ORDER BY region;
-- East 11012 1809.48 | North 10063 1800.16 | South 11957 1811.0 | West 14121 1808.6
-- CTE: name a step, then query it
WITH monthly AS (
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
SUM(revenue) AS revenue
FROM sales
GROUP BY 1
)
SELECT month, ROUND(revenue) AS revenue
FROM monthly
ORDER BY revenue DESC
LIMIT 3;
-- 2026-08-01 87202.0 | 2026-07-01 84137.0 | 2026-06-01 78969.0Cast date_trunc to DATE: it returns a timestamp in Postgres and in DuckDB 2.0, though DuckDB 1.3.2 returned a DATE.
Recursive CTE
A recursive CTE has a starting query, UNION ALL, and a query that joins back to the CTE until it returns no rows. Walking the staff table from the top:
WITH RECURSIVE chain AS (
SELECT id, name, 1 AS level, name AS path
FROM staff
WHERE manager_id IS NULL
UNION ALL
SELECT s.id, s.name, c.level + 1, c.path || ' > ' || s.name
FROM staff s
JOIN chain c ON s.manager_id = c.id
)
SELECT level, name, path FROM chain ORDER BY path; level | name | path
-------+------+------------------
1 | Dana | Dana
2 | Eli | Dana > Eli
3 | Gus | Dana > Eli > Gus
2 | Fay | Dana > Fay
(4 rows)And a date spine, the usual way to show days with no sales as zero. The sample has no orders on 7 March 2026:
WITH RECURSIVE days(d) AS (
SELECT DATE '2026-03-04'
UNION ALL
SELECT d + 1 FROM days WHERE d < DATE '2026-03-09'
)
SELECT d AS day, COUNT(s.order_id) AS orders
FROM days
LEFT JOIN sales s ON s.order_date = d
GROUP BY d
ORDER BY d; day | orders
------------+--------
2026-03-04 | 11
2026-03-05 | 3
2026-03-06 | 5
2026-03-07 | 0
2026-03-08 | 6
2026-03-09 | 5
(6 rows)Four traps we hit:
- Postgres:
d + INTERVAL '1 day'failed, because the first row is a date and the recursive part returns a timestamp.d + 1keeps a date. - MySQL: write
CONCAT(c.path, ' > ', s.name)andd + INTERVAL 1 DAY. Column widths come from the first query, and with a VARCHAR(10) name MySQL stopped withData too long for column 'path';CAST(name AS CHAR(200)) AS pathfixed it. - Depth: MySQL aborted a 1,500-level series after 1,001 iterations (
cte_max_recursion_depthis 1,000), and SQL Server's docs say of MAXRECURSION: "The server-wide default is 100." Postgres, SQLite and DuckDB ran all 1,500. - SQL Server writes plain
WITH, no RECURSIVE.
More patterns: recursive SQL for hierarchies.
Window functions: ROW_NUMBER, RANK, LAG and running totals
Window functions add a value to every row without collapsing rows the way GROUP BY does. Ties first:
WITH t(score) AS (SELECT 100 UNION ALL SELECT 90 UNION ALL SELECT 90 UNION ALL SELECT 80)
SELECT score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num,
RANK() OVER (ORDER BY score DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rnk
FROM t
ORDER BY score DESC, row_num; score | row_num | rnk | dense_rnk
-------+---------+-----+-----------
100 | 1 | 1 | 1
90 | 2 | 2 | 2
90 | 3 | 2 | 2
80 | 4 | 4 | 3
(4 rows)RANK skips to 4 after a tie; DENSE_RANK doesn't. We avoided rank and row_number as aliases because MySQL 8.4 treats them as reserved words and rejected SELECT 1 AS rank.
Top 2 products per region:
WITH product_rev AS (
SELECT region, product, ROUND(SUM(revenue)) AS revenue
FROM sales
GROUP BY region, product
)
SELECT region, product, revenue
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC) AS rn
FROM product_rev
) ranked
WHERE rn <= 2
ORDER BY region; region | product | revenue
--------+---------------+----------
East | Standing desk | 76548.0
East | Office chair | 54286.0
North | Standing desk | 112052.0
North | Team plan | 59077.0
South | Standing desk | 79608.0
South | Office chair | 47467.0
West | Standing desk | 101992.0
West | Office chair | 62257.0
(8 rows)DuckDB and BigQuery skip the subquery with QUALIFY. Postgres and SQLite rejected it, and MySQL 8.4 accepts it only with its hypergraph optimizer switched on:
SELECT region, product, ROUND(SUM(revenue)) AS revenue
FROM sales
GROUP BY region, product
QUALIFY ROW_NUMBER() OVER (PARTITION BY region ORDER BY SUM(revenue) DESC) = 1
ORDER BY region; -- Standing desk in all four regionsMonth-over-month change, a running total and a 3-month moving average in one query:
WITH m AS (
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
SUM(revenue) AS rev
FROM sales
WHERE order_date >= '2026-01-01'
GROUP BY 1
)
SELECT month,
ROUND(rev) AS revenue,
ROUND(LAG(rev) OVER (ORDER BY month)) AS prev_month,
ROUND(100 * (rev / NULLIF(LAG(rev) OVER (ORDER BY month), 0) - 1), 1)
AS pct_change,
ROUND(SUM(rev) OVER (ORDER BY month)) AS running_total,
ROUND(AVG(rev) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW))
AS avg_3_months
FROM m
ORDER BY month; month | revenue | prev_month | pct_change | running_total | avg_3_months
------------+---------+------------+------------+---------------+--------------
2026-01-01 | 56810.0 | NULL | NULL | 56810.0 | 56810.0
2026-02-01 | 52738.0 | 56810.0 | -7.2 | 109548.0 | 54774.0
2026-03-01 | 61622.0 | 52738.0 | 16.8 | 171169.0 | 57056.0
...
2026-09-01 | 64819.0 | 87202.0 | -25.7 | 634533.0 | 78720.0
2026-10-01 | 57518.0 | 64819.0 | -11.3 | 692051.0 | 69846.0
(10 rows)LAG is NULL on the first row; NULLIF only guards a month whose revenue is zero. LEAD looks forward the same way.
ROWS versus RANGE. With ORDER BY and no frame, the default is RANGE, which treats tied rows as one:
WITH t(day, amount) AS (
SELECT 1, 10 UNION ALL SELECT 2, 20 UNION ALL SELECT 2, 30 UNION ALL SELECT 3, 40
)
SELECT day, amount,
SUM(amount) OVER (ORDER BY day) AS default_frame,
SUM(amount) OVER (ORDER BY day ROWS UNBOUNDED PRECEDING) AS rows_frame
FROM t
ORDER BY day, amount; day | amount | default_frame | rows_frame
-----+--------+---------------+------------
1 | 10 | 10 | 10
2 | 20 | 60 | 30
2 | 30 | 60 | 60
3 | 40 | 100 | 100
(4 rows)Apart from QUALIFY, and date_trunc in the monthly query, every window query here gave the same result in all four databases. More examples: SQL window functions.
Connect any database. Ask in plain English.
Start free →CASE WHEN
SELECT CASE
WHEN revenue >= 1000 THEN 'large'
WHEN revenue >= 250 THEN 'medium'
ELSE 'small'
END AS order_size,
COUNT(*) AS orders,
ROUND(SUM(revenue)) AS revenue
FROM sales
GROUP BY order_size
ORDER BY revenue DESC;
-- medium 1604 772662.0 | small 2889 366858.0 | large 241 334181.0
-- pivot: one column per channel
SELECT region,
ROUND(SUM(CASE WHEN channel = 'Online' THEN revenue ELSE 0 END)) AS online,
ROUND(SUM(CASE WHEN channel = 'Partner' THEN revenue ELSE 0 END)) AS partner,
ROUND(SUM(revenue) FILTER (WHERE channel = 'Sales team')) AS sales_team
FROM sales
GROUP BY region
ORDER BY region; region | online | partner | sales_team
--------+----------+---------+------------
East | 151488.0 | 64769.0 | 119927.0
North | 213297.0 | 88855.0 | 115330.0
South | 142073.0 | 67118.0 | 97320.0
West | 201271.0 | 83592.0 | 128660.0
(4 rows)CASE checks its branches in order, so >= 250 only sees orders under 1,000. FILTER (WHERE ...) worked in Postgres, SQLite and DuckDB; MySQL needs the CASE form. More on pivoting in SQL.
NULL handling
SELECT NULL = NULL AS null_eq_null,
NULL IS NULL AS is_null,
3 NOT IN (1, 2, NULL) AS not_in_with_null,
NULL IS DISTINCT FROM 1 AS distinct_from,
COALESCE(NULL, 'n/a') AS coalesce,
10 / NULLIF(0, 0) AS safe_divide,
concat('a', NULL, 'b') AS concat_fn,
'a' || NULL AS pipes_null;null_eq_null | NULL
is_null | True
not_in_with_null | NULL
distinct_from | True
coalesce | n/a
safe_divide | NULL
concat_fn | ab
pipes_null | NULL
(1 row)NULL means unknown, so = NULL is never true: test with IS NULL. 3 NOT IN (1, 2, NULL) is NULL rather than true, which is why a NOT IN subquery that returns one NULL filters out every row. MySQL has no IS DISTINCT FROM; its NULL-safe equals is <=>.
Aggregates skip NULLs, and SUM over no rows is NULL, not 0. Cy, who has no orders:
SELECT COUNT(*) AS all_rows,
COUNT(o.order_id) AS with_order,
SUM(o.amount) AS total,
COALESCE(SUM(o.amount), 0) AS total_or_zero
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE c.name = 'Cy'; all_rows | with_order | total | total_or_zero
----------+------------+-------+---------------
1 | 0 | NULL | 0
(1 row)Dates
SELECT order_date,
CAST(date_trunc('month', order_date) AS DATE) AS month_start,
EXTRACT(year FROM order_date) AS yr,
dayname(order_date) AS weekday,
order_date + INTERVAL '30 days' AS plus_30_days,
last_day(order_date) AS month_end,
date_diff('day', DATE '2026-01-01', order_date) AS days_since_jan_1,
strftime(order_date, '%Y-%m') AS ym
FROM sales
WHERE order_id = 14734;order_date | 2026-10-31
month_start | 2026-10-01
yr | 2026
weekday | Saturday
plus_30_days | 2026-11-30 00:00:00
month_end | 2026-10-31
days_since_jan_1 | 303
ym | 2026-10
(1 row)Adding an INTERVAL returns a timestamp; order_date + 30 keeps a date in Postgres and DuckDB, but MySQL turned DATE '2026-01-01' + 1 into the number 20260102. Postgres has no dayname(): use to_char(d, 'FMDay'). Postgres writes INTERVAL '30 days', MySQL INTERVAL 30 DAY, and DuckDB accepts both. For the last 30 days of a table that ends before today, count back from its newest row:
SELECT COUNT(*) AS orders, ROUND(SUM(revenue)) AS revenue
FROM sales
WHERE order_date > (SELECT MAX(order_date) FROM sales) - INTERVAL '30 days';
-- 197 orders, 56189.0
-- orders by weekday, Monday first
SELECT dayname(order_date) AS weekday, COUNT(*) AS orders
FROM sales
GROUP BY weekday, isodow(order_date)
ORDER BY isodow(order_date);
-- Monday 678, Tuesday 662, Wednesday 703, Thursday 650, Friday 702,
-- Saturday 653, Sunday 686Grouping by month and region gives the series a chart needs:
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
region,
ROUND(SUM(revenue)) AS revenue
FROM sales
GROUP BY 1, 2
ORDER BY 1, 2; -- 96 rows: 24 months x 4 regions
The query above on the invented sample sales table, run in DuckDB 1.3.2 on 3 December 2026.
Strings
SELECT product,
upper(product) AS upper,
length(product) AS len,
substr(product, 1, 4) AS first_4,
replace(product, ' ', '_') AS snake,
split_part(product, ' ', 2) AS word_2,
region || ' / ' || channel AS label
FROM sales
WHERE order_id = 10001;
-- Team plan | TEAM PLAN | 9 | Team | Team_plan | plan | North / Partner
SELECT category,
string_agg(DISTINCT product, ', ' ORDER BY product) AS products
FROM sales
GROUP BY category
ORDER BY category; category | products
----------+-------------------------------------------------------
Hardware | Desk lamp, Monitor stand, Office chair, Standing desk
Services | Setup session, Support pack, Training day
Software | Reporting add-on, Starter plan, Team plan
Supplies | Cable kit, Label rolls, Notebook set
(4 rows)MySQL writes GROUP_CONCAT(... SEPARATOR ', ') instead of string_agg and SUBSTRING_INDEX instead of split_part. SQLite has string_agg but rejected DISTINCT with a separator. Postgres documents ILIKE as "not in the SQL standard but is a PostgreSQL extension"; elsewhere, compare lower(product) LIKE '%desk%'.
INSERT, UPDATE, DELETE and UPSERT
CREATE TABLE targets (region VARCHAR(20) PRIMARY KEY, goal INTEGER NOT NULL);
INSERT INTO targets VALUES ('North', 200000), ('South', 150000);
INSERT INTO targets (region, goal) SELECT 'East', 160000;
UPDATE targets SET goal = goal + 15000 WHERE region = 'South';
DELETE FROM targets WHERE region = 'East';
INSERT INTO targets VALUES ('North', 210000), ('West', 205000)
ON CONFLICT (region) DO UPDATE SET goal = excluded.goal;
SELECT * FROM targets ORDER BY region; region | goal
--------+--------
North | 210000
South | 165000
West | 205000
(3 rows)excluded is the row that failed to insert. RETURNING hands back the changed rows in Postgres, SQLite and DuckDB; MySQL rejected it:
UPDATE targets SET goal = goal + 5000 WHERE region = 'West' RETURNING region, goal;
-- West | 210000Before any UPDATE or DELETE, run a SELECT with the same WHERE to see which rows it will touch.
The upsert in other dialects, each run with a key that already existed:
-- MySQL 8.4: the row alias replaces the deprecated VALUES()
INSERT INTO u2 VALUES (1, 20), (2, 30) AS new
ON DUPLICATE KEY UPDATE v = new.v; -- 1:20 | 2:30
-- Postgres 15+ and DuckDB; SQL Server and BigQuery write MERGE the same way
MERGE INTO u3 USING (VALUES (1, 20), (2, 30)) AS s(k, v) ON u3.k = s.k
WHEN MATCHED THEN UPDATE SET v = s.v
WHEN NOT MATCHED THEN INSERT VALUES (s.k, s.v); -- 1:20 | 2:30
-- SQLite and DuckDB shorthand: replaces the whole row
INSERT OR REPLACE INTO u4 VALUES (1, 20); -- 20MySQL's manual: "The use of VALUES() to refer to the new row and columns is deprecated, and subject to removal in a future version of MySQL."
CREATE TABLE and indexes
CREATE TABLE orders_demo (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
order_date DATE NOT NULL DEFAULT (CURRENT_DATE),
status VARCHAR(20) CHECK (status IN ('open', 'paid', 'refunded')),
amount DECIMAL(10, 2)
);
CREATE INDEX idx_orders_customer ON orders_demo (customer_id);
CREATE INDEX idx_orders_cust_date ON orders_demo (customer_id, order_date);
CREATE TABLE west_2026 AS
SELECT * FROM sales WHERE region = 'West' AND order_date >= '2026-01-01';
DROP INDEX idx_orders_customer;
SELECT COUNT(*) AS rows_copied FROM west_2026; -- 687
INSERT INTO orders_demo (order_id, customer_id, status, amount)
VALUES (1, 7, 'shipped', 9.99);
-- Constraint Error: CHECK constraint failed on table "orders_demo" ...All four databases rejected the 'shipped' row. For MySQL, keep DEFAULT (CURRENT_DATE) in parentheses (without them it was a syntax error), write DROP INDEX ... ON orders_demo, and use VARCHAR rather than TEXT for a key column (error 1170: a TEXT key needs a length). A two-column index serves filters on customer_id alone or on both columns, not on order_date alone.
How much faster does an index make a query?
We generated a million orders in SQLite in memory, timed four queries, added two indexes and timed them again. The script needs only Python:
import random, sqlite3, statistics, time
from datetime import date, timedelta
random.seed(42)
con = sqlite3.connect(":memory:")
con.execute("""CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER,
order_date TEXT, region TEXT, amount REAL)""")
start = date(2024, 1, 1)
con.executemany("INSERT INTO orders VALUES (?, ?, ?, ?, ?)", (
(i, random.randint(1, 100_000), str(start + timedelta(days=random.randrange(1096))),
random.choice(["North", "South", "East", "West"]), round(random.uniform(5, 500), 2))
for i in range(1, 1_000_001)))
QUERIES = {
"one customer": "SELECT * FROM orders WHERE customer_id = 4242",
"one week": "SELECT COUNT(*), SUM(amount) FROM orders "
"WHERE order_date BETWEEN '2026-03-01' AND '2026-03-07'",
"latest 10": "SELECT * FROM orders ORDER BY order_date DESC LIMIT 10",
"total by region": "SELECT region, SUM(amount) FROM orders GROUP BY region",
}
def ms(sql, runs=7):
times = []
for _ in range(runs):
t = time.perf_counter()
con.execute(sql).fetchall()
times.append((time.perf_counter() - t) * 1000)
return statistics.median(times)
before = {name: ms(sql) for name, sql in QUERIES.items()}
t = time.perf_counter()
con.execute("CREATE INDEX idx_customer ON orders (customer_id)")
con.execute("CREATE INDEX idx_date ON orders (order_date)")
print(f"building both indexes: {(time.perf_counter() - t) * 1000:.0f} ms")
for name, sql in QUERIES.items():
after = ms(sql)
plan = con.execute("EXPLAIN QUERY PLAN " + sql).fetchall()[-1][-1]
print(f"{name:16} {before[name]:7.2f} ms -> {after:6.2f} ms")
print(f"{'':16} {plan}")On Windows 11 with Python 3.14.3 and SQLite 3.50.4, the third of three runs (the other two were within a factor of two of it):
building both indexes: 1476 ms
one customer 58.95 ms -> 0.03 ms
SEARCH orders USING INDEX idx_customer (customer_id=?)
one week 71.33 ms -> 7.33 ms
SEARCH orders USING INDEX idx_date (order_date>? AND order_date<?)
latest 10 96.58 ms -> 0.06 ms
SCAN orders USING INDEX idx_date
total by region 560.75 ms -> 567.57 ms
USE TEMP B-TREE FOR GROUP BY
Median of 7 runs per query, SQLite 3.50.4 in memory, measured 3 December 2026 on a shared laptop.
An index pays off when a query needs few rows: one customer, one week, the newest 10. A total over every row reads every row either way. The indexes took 1.5 seconds to build, and every later insert has to update them too. DuckDB works differently: its docs say ART indexes are "mainly used to ensure primary key constraints and to speed up point and very highly selective (i.e., < 0.1%) queries", and it keeps min-max statistics on every column without being asked.
Where Fastero fits
Fastero is an AI and data platform where people and AI agents work together on a team's data, in the browser. Every new account has this post's sales table: the same invented orders, ready in the SQL editor, so every example above that queries sales runs as written straight away. Fastero also ships a sample dashboard, notebook and Streamlit app built on it.

Fastero's SQL editor in a demo workspace: leads by channel and month, pivoted with FILTER (WHERE ...).
For your own data, connect Postgres, MySQL, SQL Server, Redshift, Oracle or BigQuery (all but BigQuery can go through an SSH tunnel), or upload a CSV or Excel file and query it with SQL. Save queries, chart them, and put them on a dashboard that refreshes on a schedule; viewers are free. The database has to be reachable from the internet or a tunnel, and Fastero doesn't host databases, so for a scratch database see free online SQL compilers or sample databases. The Free plan has no end date and needs no card; plans are on the pricing page.
FAQ
What is the order of execution of a SQL query?
FROM and joins run first, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY and finally LIMIT or OFFSET. That is why WHERE can't use an aggregate and ORDER BY can use a SELECT alias. Postgres also refuses a SELECT alias in WHERE, while DuckDB and SQLite accepted one in our test.
What is the difference between WHERE and HAVING?
WHERE filters rows before they are grouped, so it can't refer to SUM() or COUNT(). HAVING filters groups after aggregation. Put every condition that doesn't need an aggregate in WHERE: the database then groups fewer rows.
What is the difference between RANK, DENSE_RANK and ROW_NUMBER?
On scores of 100, 90, 90 and 80, ROW_NUMBER gave 1, 2, 3, 4, RANK gave 1, 2, 2, 4 and DENSE_RANK gave 1, 2, 2, 3. Use ROW_NUMBER to pick exactly one row per group, RANK for competition-style places and DENSE_RANK when you want no gaps.
How do you write an upsert in SQL?
Postgres, SQLite and DuckDB add ON CONFLICT (key) DO UPDATE to the INSERT and read the new values from excluded. MySQL adds AS new ON DUPLICATE KEY UPDATE and reads them from new. SQL Server and BigQuery use MERGE, which Postgres has had since version 15 and which also ran in DuckDB 2.0.1.
Is SQL the same in every database?
Mostly. SELECT, GROUP BY, inner and left joins, CTEs and window functions gave the same results in all four databases we tested, as long as they avoided dialect functions. Dates, string functions, LIMIT versus TOP, upserts, FULL OUTER JOIN and case sensitivity differ. Of this page's 42 queries, Postgres ran 37 unchanged and MySQL 23.
Where can I practice SQL for free?
A browser tool such as an online SQL compiler runs SQLite, DuckDB or Postgres with no install, and our list of sample databases has practice data with real joins. For interview-style problems, see SQL interview questions; if you work in Python, see the pandas cheat sheet.
Sources
Read on 3 December 2026:
- PostgreSQL: SELECT, INSERT and ON CONFLICT, date and time functions, pattern matching, WITH queries, boolean type, version 15 release notes (MERGE)
- MySQL 8.4 manual: ON DUPLICATE KEY UPDATE, SQL modes, numeric types, WITH, case sensitivity in searches
- Microsoft: TOP, DATETRUNC, DATEDIFF, the || operator, MERGE, bit, WITH, LIKE, STRING_AGG
- SQLite: UPSERT, date functions, expressions and LIKE, data types, RETURNING
- DuckDB 2.0: date functions, pattern matching, INSERT, QUALIFY, indexes, numeric operators, FROM and joins, text functions
- Google BigQuery: date functions, operators, DML and MERGE, query syntax, string functions
- Our runs: Windows 11, Python 3.14.3; DuckDB 2.0.1 (Python) and 1.3.2 (Node.js); SQLite 3.50.4; Docker images
postgres:16-alpine(PostgreSQL 16.15) andmysql:8.4(MySQL 8.4.13, default SQL mode); the inventedsample-sales.csv, 4,734 rows
Try Fastero free: run every DuckDB query on this page against the same sample sales table, then connect your own database. No credit card required.
Fastero Dev Team