SQL Cheatsheet

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

When This Cheatsheet Helps Most

Use this page when you need to inspect production-like data quickly, verify joins, group records into reports, or debug JSON-heavy schemas in PostgreSQL without jumping between many docs pages.

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;

Common SQL Mistakes

Frequent mistakes include forgetting the join condition, filtering after aggregation instead of before it, and assuming NULL behaves like an empty string or zero. Those errors usually produce results that look plausible but are wrong.

Related

Knowledge is power.