SQL Cheatsheet

Essential SQL commands, with a focus on modern PostgreSQL features. From basic queries to advanced data types.

Basics

Key / CodeDescription
SELECT * FROM usersSelect all columns from a table.
WHERE age > 18Filter rows.
ORDER BY created_at DESCSort results.
LIMIT 10 OFFSET 5Pagination.

Joins

Key / CodeDescription
INNER JOINReturns records that have matching values in both tables.
LEFT JOINReturns all records from the left table, and the matched records from the right table.
RIGHT JOINReturns all records from the right table, and the matched records from the left table.
FULL OUTER JOINReturns all records when there is a match in either left or right table.

PostgreSQL JSONB

Modern Postgres allows semi-structured data.

-- Select a value from a JSON column
SELECT data->>'name' FROM events;

-- Filter by JSON value
SELECT * FROM events WHERE data->>'status' = 'completed';

Common Table Expressions (CTE)

Use `WITH` to create temporary result sets. Makes complex queries readable.

WITH regional_sales AS (
    SELECT region, SUM(amount) as total_sales
    FROM orders
    GROUP BY region
)
SELECT * FROM regional_sales WHERE total_sales > 10000;
Knowledge is power.