GameParticles
Developer

SQL Cheat Sheet: Core Queries, Joins and Formatting Rules

A SQL cheat sheet with ready-to-run examples of SELECT, JOIN, GROUP BY, INSERT, UPDATE and DELETE, plus the SQL formatting rules that keep queries readable.

Updated

This SQL cheat sheet covers the statements that make up most day-to-day work: SELECT with filtering and sorting, JOIN, GROUP BY, and the three statements that change data, INSERT, UPDATE and DELETE. Every example is standard SQL that runs with little or no change on PostgreSQL, MySQL, SQLite and SQL Server. The final sections cover SQL formatting conventions.

The examples use two tables: customers (id, name, country) and orders (id, customer_id, total, created_at).

SELECT: reading data

  • All columns: SELECT * FROM customers;
  • Chosen columns: SELECT name, country FROM customers;
  • Rename a column in the output: SELECT name AS customer_name FROM customers;
  • Unique values: SELECT DISTINCT country FROM customers;
  • Sort: SELECT * FROM orders ORDER BY created_at DESC;
  • First ten rows: SELECT * FROM orders ORDER BY total DESC LIMIT 10;

LIMIT works in PostgreSQL, MySQL and SQLite. SQL Server uses SELECT TOP 10 ... or OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY after an ORDER BY. Without ORDER BY, the order of rows is not guaranteed.

WHERE: filtering rows

ConditionExample
Equals, not equalsWHERE country = 'DE', WHERE country <> 'DE'
ComparisonWHERE total >= 100
Both, eitherWHERE total > 50 AND country = 'US', WHERE a = 1 OR b = 2
In a listWHERE country IN ('US', 'CA', 'MX')
In a range, inclusiveWHERE total BETWEEN 10 AND 20
Pattern matchWHERE name LIKE 'A%'
Missing valueWHERE country IS NULL, WHERE country IS NOT NULL

Three things to remember. Strings use single quotes. In LIKE, % matches any run of characters and _ matches exactly one. And NULL is never equal to anything, including another NULL, so WHERE country = NULL matches no rows; always use IS NULL.

When mixing AND and OR, add parentheses. AND binds tighter, so a OR b AND c means a OR (b AND c).

JOIN: combining tables

  • Matching rows only: SELECT o.id, c.name, o.total FROM orders o INNER JOIN customers c ON c.id = o.customer_id;
  • All customers, with orders if any: SELECT c.name, o.total FROM customers c LEFT JOIN orders o ON o.customer_id = c.id;
  • Customers with no orders: SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;
Join typeReturns
INNER JOINRows with a match in both tables
LEFT JOINEvery left row, plus matches from the right or NULL
RIGHT JOINEvery right row, plus matches from the left or NULL
FULL JOINEvery row from both sides, matched where possible
CROSS JOINEvery combination of left and right rows

Plain JOIN means INNER JOIN. o and c are table aliases, which keep long queries short. A missing or wrong ON condition is the classic cause of a result with far too many rows.

GROUP BY: summarizing

The aggregate functions are COUNT, SUM, AVG, MIN and MAX.

  • Count all rows: SELECT COUNT(*) FROM orders;
  • Orders and revenue per customer: SELECT customer_id, COUNT(*) AS orders, SUM(total) AS revenue FROM orders GROUP BY customer_id;
  • Only customers with five or more orders: SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id HAVING COUNT(*) >= 5;
  • Revenue per country: SELECT c.country, SUM(o.total) AS revenue FROM orders o JOIN customers c ON c.id = o.customer_id GROUP BY c.country ORDER BY revenue DESC;

The rule: every column in the SELECT list must either appear in GROUP BY or be inside an aggregate function. COUNT(*) counts rows, while COUNT(column) skips rows where that column is NULL.

The order clauses run in

You write a query as SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT, but the database evaluates it logically in this order:

  1. FROM and JOIN build the working set of rows.
  2. WHERE filters rows.
  3. GROUP BY forms groups.
  4. HAVING filters groups.
  5. SELECT computes the output columns.
  6. ORDER BY sorts.
  7. LIMIT trims.

This explains two common errors. An alias defined in SELECT cannot be used in WHERE, because WHERE runs first. And an aggregate cannot go in WHERE for the same reason; it belongs in HAVING.

INSERT, UPDATE and DELETE

  • Add a row: INSERT INTO customers (name, country) VALUES ('Ada', 'GB');
  • Add several: INSERT INTO customers (name, country) VALUES ('Grace', 'US'), ('Linus', 'FI');
  • Change rows: UPDATE customers SET country = 'UK' WHERE country = 'GB';
  • Change several columns: UPDATE orders SET total = 90, created_at = '2026-01-15' WHERE id = 17;
  • Remove rows: DELETE FROM orders WHERE id = 17;
An UPDATE or DELETE without a WHERE clause affects every row in the table. Run the same WHERE as a SELECT first to see what will be touched, and wrap risky changes in a transaction: BEGIN, run the statement, check the row count, then COMMIT or ROLLBACK.

SQL formatting conventions

The database ignores layout, so formatting is purely for readers, including you in six months. No single official style exists, but these habits are widely shared:

  • Uppercase keywords, lowercase names. SELECT name FROM customers separates the language from your schema at a glance.
  • One major clause per line. SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY each start a new line at the left margin.
  • One column per line once the list is long, indented under SELECT.
  • Each JOIN on its own line, with its ON condition on the same line or indented beneath it.
  • Each AND or OR on a new line, indented, so every condition can be read and commented out separately.
  • Use snake_case names and avoid reserved words such as order or user as table names.
  • Give tables short, meaningful aliases (o for orders, c for customers) and qualify columns whenever more than one table is involved.
  • Write AS for column aliases. SUM(total) AS revenue is clearer than SUM(total) revenue.

You do not need to do this by hand. The SQL Formatter takes a query pasted from a log, an ORM or a BI tool, usually one long line, and breaks it at each major clause with consistent indentation. You can choose two or four spaces and switch uppercase keywords on or off. It reformats the text only; it does not run the query or check it against a database.

Query results often leave the database as CSV. To turn an exported result into JSON for an API or a test fixture, use the JSON to CSV Converter in its CSV to JSON direction. Primary keys in these tables are often UUIDs; see what a UUID is.

Try it

Copy any single-line example from this page into the SQL Formatter and watch it split into clauses. Then paste the longest query in your own codebase and see whether the join conditions are what you thought they were.

Tools in this guide

Frequently asked questions

What is the difference between WHERE and HAVING?

WHERE filters individual rows before they are grouped, so it cannot use aggregate functions. HAVING filters the groups produced by GROUP BY, so it can test values such as COUNT(*) or SUM(total). A query can use both.

What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows that have a match in both tables. LEFT JOIN returns every row from the left table and fills the right table's columns with NULL where no match exists, which makes it the tool for finding missing related rows.

What is SQL formatting?

SQL formatting is laying out a query consistently so it is easy to read: keywords in uppercase, each major clause on its own line, one column or condition per line in long lists, and indented JOIN conditions. It changes nothing about how the query runs.

Should SQL keywords be uppercase?

It is a convention, not a requirement. SQL keywords are case insensitive, so select and SELECT behave identically. Uppercase keywords with lowercase table and column names is the most common style because it separates the language from your own names at a glance.

More developer guides

JSON Formatter
Developer · Format, validate and minify JSON with syntax highlighting.
↵
Base64 Encode / Decode
Developer · Encode text to Base64 or decode Base64 back to plain text.
↵
URL Encoder / Decoder
Developer · Encode or decode URL components and query strings.
↵
Hash Generator
Developer · Generate MD5, SHA-1, SHA-256 and SHA-512 hashes.
↵
UUID Generator
Developer · Generate UUIDs v4 (random) in bulk with one click.
↵
Regex Tester
Developer · Test regular expressions against text with live match highlighting.
↵
Word Counter
Text · Count words, characters, sentences, paragraphs and reading time.
↵
Case Converter
Text · Convert text between UPPER, lower, Title, camelCase, snake_case and more.
↵
List Sorter
Text · Sort, reverse, deduplicate and shuffle lists of text.
↵
Markdown Preview
Text · Write Markdown and see a live rendered preview side by side.
↵
Percentage Calculator
Numbers · Calculate percentages, increases, decreases and what % one number is of another.
↵
Color Converter
Colors · Convert colors between HEX, RGB, HSL and HSV instantly.
↵
Snake
Arcade · Eat food, grow longer, don't hit the walls. A timeless classic.
↵
2048
Puzzle · Slide tiles and combine them to reach the legendary 2048 tile.
↵
Word Grid
Puzzle · Guess the hidden five letter word in six tries using color clues.
↵
Sudoku
Puzzle · Fill the 9x9 grid with logic. Four difficulties from easy to expert.
↵
Minesweeper
Strategy · Use number clues to clear the minefield. Classic logic, three levels.
↵
Breakout
Arcade · Smash every brick with paddle and ball. Power-ups, combos, endless levels.
↵
Typing Practice
Casual · Build your WPM and accuracy with timed drills from 30 seconds to 5 minutes. Find your weak keys.
↵
TypeRunner
Arcade · Multiplayer typing race. Race friends by link, beat computer runners, or chase your own ghost.
↵
Typing Blocks
Arcade · Type each word before its wooden block lands. Miss, and the pile climbs toward the line.
↵
Bubble Shooter
Arcade · Aim, bank shots off the walls, and pop groups of three or more bubbles.
↵
Road Rush
Arcade · Race seven rivals through traffic and punch your way to the front.
↵