Database & Backend ReferenceUpdated: 2026-11-05

Mastering SQL: Queries, Joins, Aggregations & Performance Cheat Sheet

Quick lookup guide for SELECT, INNER/LEFT/RIGHT JOINs, GROUP BY, indexes, and ACID transactions.

Structured Query Language (SQL) is the domain-specific standard language used to manage, query, and manipulate data held in relational database management systems (PostgreSQL, MySQL, SQLite, SQL Server). This cheat sheet provides essential syntax patterns, visual join explanations, and optimization rules.

SQL Join Types Decoded

How relational joins merge rows across separate tables.

Join TypeDescriptionSQL Syntax Example
`INNER JOIN`Returns only rows where there is a match in BOTH tables.`SELECT * FROM users u INNER JOIN orders o ON u.id = o.user_id;`
`LEFT JOIN`Returns ALL rows from the left table, plus matched rows from the right table (NULL if no match).`SELECT * FROM users u LEFT JOIN orders o ON u.id = o.user_id;`
`RIGHT JOIN`Returns ALL rows from the right table, plus matched rows from the left table.`SELECT * FROM users u RIGHT JOIN orders o ON u.id = o.user_id;`
`FULL OUTER JOIN`Returns rows when there is a match in EITHER table (combines LEFT and RIGHT).`SELECT * FROM users u FULL OUTER JOIN orders o ON u.id = o.user_id;`

Core Query Clauses & Execution Order

Notice that SQL executes clauses in a different order than they are written!

Execution StepClausePurpose
1`FROM` / `JOIN`Identify target tables and join conditions
2`WHERE`Filter individual base rows before aggregation
3`GROUP BY`Aggregate rows into summary categories
4`HAVING`Filter aggregated groups (unlike WHERE which filters rows)
5`SELECT`Compute expressions, column aliases, and return fields
6`ORDER BY`Sort the finalized result set
7`LIMIT` / `OFFSET`Constrain number of returned rows for pagination

Essential Aggregation & Indexing Recipes

Common SQL queries for production reporting.

Group By with Having (Find Power Users)sql
SELECT user_id, COUNT(*) AS total_orders, SUM(amount) AS total_spent
FROM orders
WHERE status = 'completed'
GROUP BY user_id
HAVING COUNT(*) >= 5
ORDER BY total_spent DESC
LIMIT 20;
Filters completed orders, groups by customer, and keeps users with 5+ orders.
Composite Index Creationsql
CREATE INDEX idx_orders_user_status ON orders (user_id, status);
Accelerates queries filtering simultaneously on user_id and status.

Frequently Asked Questions

What is the exact difference between WHERE and HAVING?

`WHERE` filters individual rows BEFORE they are grouped. `HAVING` filters aggregated group metrics (like `COUNT(*)` or `SUM(revenue)`) AFTER the grouping occurs.

How do I clean and beautify messy SQL scripts?

Use DocSwift's free SQL Formatter. It formats messy inline SQL queries into indented, uppercase-keyword statements client-side.