SQLSQL

SQL: More snippets – code examples

Contents

CASE WHEN

Control flow#case#if#conditionCompare in all languages
Use case: Classify values, e.g. price tiers, customer segments, or status names in a report.
SELECT name, preis,
  CASE
    WHEN preis >= 500 THEN 'premium'
    WHEN preis >= 50  THEN 'medium'
    ELSE 'budget'
  END AS klasse
FROM produkte
ORDER BY preis DESC;

CASE WHEN is the if/elif/else of SQL – as an expression, not a statement. The conditions are checked in order, and the first match wins.

Recursive CTE as a Loop

Control flow#recursive#loop#generate_seriesCompare in all languages
Use case: Generate number or date series, e.g. for calendar reports without gaps.
WITH RECURSIVE zaehler(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM zaehler WHERE n < 5
)
SELECT n, n * n AS quadrat FROM zaehler;
-- PostgreSQL shorter: SELECT n, n*n FROM generate_series(1, 5) AS n;

SQL is set-oriented; there are no real loops. A recursive CTE repeats the second SELECT until the WHERE condition yields nothing more. PostgreSQL has a shortcut with generate_series.

Function and Aggregate Function

Functions#function#aggregate#create functionCompare in all languages
Use case: Define a calculation such as the gross price centrally and reuse it everywhere.
-- Built-in aggregate functions
SELECT COUNT(*) AS anzahl, ROUND(AVG(preis), 2) AS schnitt, MAX(preis) AS teuerstes
FROM produkte;

-- Custom function (PostgreSQL)
CREATE FUNCTION brutto(netto NUMERIC, satz NUMERIC DEFAULT 0.19)
RETURNS NUMERIC
LANGUAGE sql IMMUTABLE
AS $$ SELECT ROUND(netto * (1 + satz), 2) $$;

SELECT name, brutto(preis) FROM produkte;

SQL comes with many functions: aggregates (COUNT, SUM, AVG …) summarize many rows. Custom functions depend on the dialect: PostgreSQL CREATE FUNCTION … LANGUAGE sql/plpgsql, MySQL CREATE FUNCTION … BEGIN … END; SQLite does not support SQL functions, where the host language registers them instead.

Result List and IN List

Data structures#in#values#listCompare in all languages
Use case: Select records from a fixed set of values, e.g. certain categories or ids.
SELECT id, name, kategorie
FROM produkte
WHERE kategorie IN ('Elektronik', 'Möbel')
ORDER BY name;

-- List as a table with VALUES
WITH farben(id, name) AS (VALUES (1, 'rot'), (2, 'grün'), (3, 'blau'))
SELECT * FROM farben;

The result of a SELECT is always a table, i.e. a "list of rows". IN (…) checks membership in a list of values, and VALUES creates a table directly from literals.

GROUP BY – Mapping Key to Value

Data structures#group by#aggregate#mapCompare in all languages
Use case: Evaluate revenue, counts, or averages per category, month, or customer.
SELECT kategorie,
       COUNT(*)              AS anzahl,
       ROUND(AVG(preis), 2)  AS schnitt,
       MAX(preis)            AS teuerstes
FROM produkte
GROUP BY kategorie
ORDER BY anzahl DESC, kategorie;

GROUP BY creates one value (aggregate) per key (category) – the SQL counterpart to a dictionary/map with a counter. Every column in the SELECT must be either grouped or aggregated.

CREATE TABLE with Constraints

Schema#create table#constraint#schemaCompare in all languages
Use case: Define a new data model and enforce data quality directly in the database.
CREATE TABLE bewertungen (
  id         INTEGER PRIMARY KEY,
  kunde_id   INTEGER NOT NULL REFERENCES kunden(id) ON DELETE CASCADE,
  produkt_id INTEGER NOT NULL REFERENCES produkte(id),
  sterne     INTEGER NOT NULL CHECK (sterne BETWEEN 1 AND 5),
  kommentar  TEXT,
  UNIQUE (kunde_id, produkt_id)
);

A table corresponds to a class: columns are attributes with a type, rows are instances. Constraints (NOT NULL, CHECK, UNIQUE, FOREIGN KEY) are the invariants the database guarantees for every row. There is no inheritance; relationships work through foreign keys.

View for Recurring Queries

Schema#view#create view
Use case: Define complex join logic once and reuse it in reporting or for BI tools.
CREATE VIEW v_bestellwert AS
SELECT b.id AS bestellung_id, b.kunde_id, b.datum,
       SUM(bp.menge * p.preis) AS wert
FROM bestellungen b
JOIN bestellpositionen bp ON bp.bestellung_id = b.id
JOIN produkte p ON p.id = bp.produkt_id
GROUP BY b.id, b.kunde_id, b.datum;

SELECT * FROM v_bestellwert WHERE wert > 100 ORDER BY wert DESC;

A view stores the query, not the data – it is always up to date. PostgreSQL additionally has MATERIALIZED VIEW with a cached result.

Constraint Errors and ROLLBACK

Error handling#rollback#constraint#transaction#errorCompare in all languages
Use case: Protect several related changes so that nothing stays half-saved when an error occurs.
BEGIN;
INSERT INTO produkte (name, kategorie, preis) VALUES ('Tee', 'Lebensmittel', 6.20);
-- violates CHECK (preis >= 0) -> error, the transaction is unusable
INSERT INTO produkte (name, kategorie, preis) VALUES ('Error', 'Test', -1);
ROLLBACK;   -- the first INSERT is discarded as well

-- Catching errors specifically (PostgreSQL, PL/pgSQL):
-- BEGIN ... EXCEPTION WHEN check_violation THEN RAISE NOTICE 'invalid price'; END;

SQL has no try/catch: errors arise from constraints, and the database reports them to the client. Transactions replace the "cleanup": ROLLBACK undoes everything since BEGIN. Only procedural extensions (PL/pgSQL, T-SQL) have error handling in code.

Import and Export CSV

Files#csv#import#export#copyCompare in all languages
Use case: Load data from Excel/CSV or pass results on as a file.
-- SQLite (sqlite3 shell)
.mode csv
.import produkte.csv produkte_import
.headers on
.output export.csv
SELECT * FROM produkte;
.output stdout

-- PostgreSQL (psql, client-side)
\copy produkte FROM 'produkte.csv' WITH (FORMAT csv, HEADER true)
\copy (SELECT * FROM produkte) TO 'export.csv' WITH (FORMAT csv, HEADER true)

-- MySQL
LOAD DATA LOCAL INFILE 'produkte.csv' INTO TABLE produkte
FIELDS TERMINATED BY ',' IGNORE 1 LINES;

File access is not part of the SQL standard but a matter for the tools: .import (SQLite), COPY or copy (PostgreSQL), LOAD DATA (MySQL). copy runs on the client, COPY on the server and needs file permissions there.

Customers without an Order

Joins#left join#anti-join#not exists
Use case: Find inactive customers for a reactivation email or track down orphaned records.
SELECT k.id, k.name
FROM kunden k
LEFT JOIN bestellungen b ON b.kunde_id = k.id
WHERE b.id IS NULL;

-- equivalent, NULL-safe:
SELECT k.id, k.name FROM kunden k
WHERE NOT EXISTS (SELECT 1 FROM bestellungen b WHERE b.kunde_id = k.id);

A LEFT JOIN returns NULLs on the right when there is no match – WHERE b.id IS NULL filters exactly those cases (anti-join). With the sample data, Eva comes out.

Top-N per Group with ROW_NUMBER

Window functions#window#row_number#top-n#partition
Use case: The most expensive product per category or the latest order per customer.
SELECT kategorie, name, preis
FROM (
  SELECT kategorie, name, preis,
         ROW_NUMBER() OVER (PARTITION BY kategorie ORDER BY preis DESC) AS rn
  FROM produkte
) t
WHERE rn = 1;

ROW_NUMBER numbers rows within each partition according to the sort order; rn = 1 is the winner. Without window functions you would need a correlated subquery. Available in PostgreSQL, MySQL 8+, and SQLite 3.25+.

Running Total and Previous Period

Window functions#window#sum over#lag#time series
Use case: Cumulative revenue over time or comparison with the previous month.
WITH monat AS (
  SELECT SUBSTR(datum, 1, 7) AS monat, COUNT(*) AS bestellungen
  FROM bestellungen
  GROUP BY SUBSTR(datum, 1, 7)
)
SELECT monat, bestellungen,
       SUM(bestellungen) OVER (ORDER BY monat) AS kumuliert,
       LAG(bestellungen) OVER (ORDER BY monat) AS vormonat
FROM monat
ORDER BY monat;

SUM() OVER (ORDER BY …) gives the running total, LAG() the value of the preceding row (NULL for the first month). The month is cut from the ISO date here with SUBSTR (SQLite/PostgreSQL/MySQL); in PostgreSQL alternatively TO_CHAR(datum, 'YYYY-MM').

UPSERT (ON CONFLICT)

Modifying data#upsert#on conflict#returning
Use case: Synchronize records: insert if new, otherwise update – without a race condition.
INSERT INTO produkte (id, name, kategorie, preis)
VALUES (4, 'Kaffee', 'Lebensmittel', 9.20)
ON CONFLICT (id) DO UPDATE
SET preis = excluded.preis
RETURNING id, name, preis;

-- MySQL:  INSERT ... ON DUPLICATE KEY UPDATE preis = VALUES(preis);

ON CONFLICT (PostgreSQL, SQLite) catches key conflicts; excluded is the row that was supposed to be inserted. RETURNING returns the result. MySQL uses ON DUPLICATE KEY UPDATE.

UPDATE Based on Another Table

Modifying data#update#join#import
Use case: Copy values from one table to another, e.g. price changes from an import table.
-- portable (correlated subquery)
UPDATE produkte
SET preis = (SELECT n.preis FROM preis_import n WHERE n.produkt_id = produkte.id)
WHERE id IN (SELECT produkt_id FROM preis_import);

-- PostgreSQL / SQLite 3.33+: UPDATE ... FROM
UPDATE produkte
SET preis = n.preis
FROM preis_import n
WHERE n.produkt_id = produkte.id;

-- MySQL:  UPDATE produkte p JOIN preis_import n ON n.produkt_id = p.id SET p.preis = n.preis;

The portable variant uses subqueries; dialect-specific forms are more convenient. The WHERE id IN (…) in the first variant prevents products without an import row from being set to NULL.

Finding and Removing Duplicates

Data quality#duplicates#having#delete
Use case: Track down and clean up duplicate customers after an import.
-- Which names occur more than once?
SELECT name, COUNT(*) AS anzahl
FROM kunden
GROUP BY name
HAVING COUNT(*) > 1;

-- Delete duplicates, keeping the lowest id each time
DELETE FROM kunden
WHERE id NOT IN (SELECT MIN(id) FROM kunden GROUP BY name);

GROUP BY … HAVING COUNT(*) > 1 shows duplicates. For deletion, the smallest id remains in each group. Always check with a SELECT first and consider foreign keys (MySQL does not allow a subquery on the same table in a DELETE – wrap it in a derived table there).

Pagination with Keyset

Performance#limit#offset#keyset#pagination
Use case: Load long lists (feeds, admin tables) quickly, page by page.
-- Page 1
SELECT id, name FROM produkte ORDER BY id LIMIT 2;

-- Next page: remember the id of the last row (here 2)
SELECT id, name FROM produkte WHERE id > 2 ORDER BY id LIMIT 2;

-- classic, but slow for large offsets:
SELECT id, name FROM produkte ORDER BY id LIMIT 2 OFFSET 2;

OFFSET has to compute all skipped rows. Keyset pagination uses an index (id > last_id) and stays equally fast on every page. Prerequisite: a unique, sorted column.

Creating and Checking an Index

Performance#index#explain#performance
Use case: Speed up a slow query and prove that the index is used.
CREATE INDEX idx_bestellungen_kunde_datum
  ON bestellungen (kunde_id, datum);

-- SQLite
EXPLAIN QUERY PLAN
SELECT * FROM bestellungen WHERE kunde_id = 1 AND datum >= '2024-02-01';

-- PostgreSQL:  EXPLAIN (ANALYZE) SELECT ...;   MySQL:  EXPLAIN SELECT ...;

The composite index helps with filters on kunde_id and kunde_id + datum (leftmost prefix). EXPLAIN shows whether "SEARCH … USING INDEX" (good) or "SCAN" / Seq Scan (full table scan) was chosen.

Hierarchy with a Recursive CTE

Advanced#recursive#tree#hierarchy
Use case: Output category trees, org charts, or bills of materials with level and path.
WITH RECURSIVE kategorien(id, name, eltern_id) AS (
  VALUES (1, 'Elektronik', NULL), (2, 'Computer', 1), (3, 'Laptops', 2), (4, 'Möbel', NULL)
),
baum(id, pfad, tiefe) AS (
  SELECT id, name, 0 FROM kategorien WHERE eltern_id IS NULL
  UNION ALL
  SELECT k.id, baum.pfad || ' > ' || k.name, baum.tiefe + 1
  FROM kategorien k JOIN baum ON k.eltern_id = baum.id
)
SELECT pfad, tiefe FROM baum ORDER BY pfad;

The anchor part fetches the roots, the recursive part attaches children and builds up the path. The categories are given here as a VALUES CTE – in practice it would be a table with eltern_id. Runs like this in SQLite and PostgreSQL.

Querying JSON Columns

Advanced#json#jsonb#json_extract
Use case: Store and filter flexible extra attributes (configuration, event payloads) in a single column.
-- PostgreSQL (column type JSONB)
SELECT daten->>'farbe' AS farbe
FROM produkt_details
WHERE (daten->>'gewicht_kg')::numeric < 2;

-- SQLite (3.38+) and MySQL
SELECT JSON_EXTRACT(daten, '$.farbe') AS farbe
FROM produkt_details
WHERE JSON_EXTRACT(daten, '$.gewicht_kg') < 2;

All three dialects can process JSON, but the syntax differs. JSON is handy for variable data, but does not replace clean modeling: there are no constraints or foreign keys for JSON contents.

Atomic Transfer Booking

Transactions#transaction#commit#atomic
Use case: Book stock or money between two records without only one side being changed.
BEGIN;
UPDATE konten SET saldo = saldo - 100 WHERE id = 1 AND saldo >= 100;
-- Check the row count (0 = insufficient funds) -> ROLLBACK
UPDATE konten SET saldo = saldo + 100 WHERE id = 2;
COMMIT;

Both bookings take effect together or not at all. The condition saldo >= 100 in the UPDATE prevents overdrafts even with concurrent access, because check and change are a single atomic statement.