SQLSQL
IntermediateLesson 9 of 15

CASE, NULL Handling & Functions – SQL

Conditional values, COALESCE, text, number, and date functions including dialect differences.

CASE is the if/else of SQL and returns a value – usable in SELECT, WHERE, ORDER BY, and even inside aggregates (pivot!). The form CASE WHEN condition THEN ... ELSE ... END checks in order; without ELSE, the result is NULL.

SELECT name, preis,
  CASE WHEN preis >= 500 THEN 'premium'
       WHEN preis >= 50  THEN 'medium'
       ELSE 'budget' END AS klasse
FROM produkte;

-- Pivot with CASE: number of orders per status as columns
SELECT SUM(CASE WHEN status = 'bezahlt'   THEN 1 ELSE 0 END) AS bezahlt,
       SUM(CASE WHEN status = 'offen'     THEN 1 ELSE 0 END) AS offen,
       SUM(CASE WHEN status = 'storniert' THEN 1 ELSE 0 END) AS storniert
FROM bestellungen;    -- 3, 2, 1

COALESCE(a, b, ...) returns the first non-NULL value, NULLIF(a, b) returns NULL if both are equal (the classic guard against division by 0). CAST(x AS type) converts types.

SELECT name, COALESCE(stadt, 'unknown') AS stadt FROM kunden;
SELECT 100.0 / NULLIF(0, 0);                    -- NULL instead of an error
SELECT CAST('42' AS INTEGER) + 1;               -- 43
SELECT ROUND(2.567, 1), ABS(-5), UPPER('sql'), LENGTH('Hello'), SUBSTR('Database', 1, 5);

Date functions differ greatly between dialects – here are the most common tasks:

  • Today: PostgreSQL CURRENT_DATE, MySQL CURDATE(), SQLite DATE('now').
  • Get year/month: PostgreSQL EXTRACT(YEAR FROM datum), MySQL YEAR(datum), SQLite STRFTIME('%Y', datum).
  • Add days: PostgreSQL datum + INTERVAL '7 days', MySQL DATE_ADD(datum, INTERVAL 7 DAY), SQLite DATE(datum, '+7 days').
  • Shorten/search text: SUBSTR/SUBSTRING, POSITION/INSTR, REPLACE, TRIM, LOWER/UPPER – available in all three dialects.
TipStore timestamps in UTC where possible and as a real date/time type (PostgreSQL TIMESTAMPTZ). ISO strings YYYY-MM-DD sort correctly, even in SQLite without a date type.