Postgres-powered SQL
Standard SQL gets you far. PostgreSQL adds features that turn multi-step application code into a single, fast query. These are the ones experienced Postgres developers reach for constantly.
Upserts: INSERT … ON CONFLICT
"Insert this row, or update it if it already exists" is called an upsert. Doing it in app code ("SELECT, then INSERT or UPDATE") has a race condition. Postgres does it atomically:
EXCLUDED refers to the row you tried to insert:
ON CONFLICT DO NOTHING silently skips duplicates, which is perfect for idempotent imports.
MERGE
MERGE (standard SQL) syncs a table with incoming data in one statement, with separate actions for matching and new rows:
RETURNING old and new values
From PostgreSQL 18, RETURNING can show values before and after a change:
DISTINCT ON: the first row per group
"The latest order for each customer" is awkward in standard SQL. DISTINCT ON keeps the first row of each group, according to ORDER BY:
FILTER: conditional aggregates
Aggregating into strings and arrays
generate_series: rows from nothing
generate_series produces a sequence of numbers or dates. It's brilliant for test data and for reports with no gaps:
Days with no orders still appear with a count of 0. A plain GROUP BY order_date would skip them.
Recursive CTEs: walking trees
A recursive CTE repeatedly joins a query to its own results. It's how you walk hierarchies like categories, org charts or comment threads:
LATERAL: a subquery per row
LATERAL lets a subquery refer to columns from earlier in the FROM clause, like a loop. "The top 2 most recent orders for each customer":
Practice
- Write an upsert into a
stock_levels(product text PRIMARY KEY, qty int)table that adds to the quantity when the product already exists. - Using
DISTINCT ON, list each category's most expensive product. - Using
generate_seriesand aLEFT JOIN, show order counts for every day of October 2024 (including zeros).
1.What's the safest way to "insert or update" a row?
2.In ON CONFLICT (id) DO UPDATE SET price = EXCLUDED.price, what is EXCLUDED?
3.What does DISTINCT ON (customer_id) … ORDER BY customer_id, order_date DESC return?