This SQL cheat sheet covers the most important SQL commands, syntax patterns, and quick-reference tables. Whether you are just starting out or need a refresher before an interview, bookmark this page. Every example is tested on MySQL, PostgreSQL, and T-SQL. Use our free online SQL formatter to clean up any query you write.
SQL Cheat Sheet — Quick Reference Guide for Beginners
Table of Contents
- Basic SQL Commands
- SELECT — Retrieving Data
- WHERE — Filtering Rows
- JOIN — Combining Tables
- GROUP BY — Aggregating Data
- Subqueries & CTEs
- Window Functions
- DDL — Creating & Modifying Tables
- DML — Insert, Update, Delete
- Common Data Types
- Dialect Differences at a Glance
- String Functions
- Date & Time Functions
- JSON Functions
- Transactions, Locking & Permissions
- FAQ
1. Basic SQL Commands — Quick Reference
| Command | Description | Example |
|---|---|---|
SELECT | Retrieve data from a table | SELECT * FROM users; |
INSERT | Add new rows | INSERT INTO users (name) VALUES ('Alice'); |
UPDATE | Modify existing rows | UPDATE users SET name='Bob' WHERE id=1; |
DELETE | Remove rows | DELETE FROM users WHERE id=1; |
CREATE TABLE | Create a new table | CREATE TABLE users (id INT, name TEXT); |
ALTER TABLE | Modify table structure | ALTER TABLE users ADD email TEXT; |
DROP TABLE | Delete a table | DROP TABLE users; |
TRUNCATE | Delete all rows (fast) | TRUNCATE TABLE users; |
2. SELECT — Retrieving Data
-- Select all columns
SELECT * FROM employees;
-- Select specific columns
SELECT first_name, last_name, salary FROM employees;
-- Distinct values (no duplicates)
SELECT DISTINCT department FROM employees;
-- Limit results (MySQL/PostgreSQL)
SELECT * FROM employees LIMIT 10;
-- Limit results (T-SQL)
SELECT TOP 10 * FROM employees;
-- Sort results
SELECT * FROM employees ORDER BY salary DESC;
-- Sort by multiple columns
SELECT * FROM employees ORDER BY department ASC, salary DESC;
3. WHERE — Filtering Rows
| Operator | Description | Example |
|---|---|---|
= | Equal | WHERE dept = 'Engineering' |
!= or <> | Not equal | WHERE status != 'closed' |
>, <, >=, <= | Greater/less than | WHERE salary > 50000 |
BETWEEN | Range (inclusive) | WHERE age BETWEEN 18 AND 65 |
LIKE | Pattern match | WHERE email LIKE '%@gmail.com' |
IN | Match any in list | WHERE dept IN ('Sales','HR') |
IS NULL | Null check | WHERE manager_id IS NULL |
AND / OR | Combine conditions | WHERE dept='Eng' AND salary>50k |
-- Complex filtering example
SELECT first_name, last_name, salary
FROM employees
WHERE department = 'Engineering'
AND salary > 60000
AND hire_date >= '2024-01-01'
AND (status = 'active' OR status = 'on_leave')
ORDER BY salary DESC;
4. JOIN — Combining Tables
| Type | Description |
|---|---|
INNER JOIN | Returns rows with matches in both tables |
LEFT JOIN | Returns all left-table rows + matches from right |
RIGHT JOIN | Returns all right-table rows + matches from left |
FULL OUTER JOIN | Returns all rows from both tables |
CROSS JOIN | Cartesian product (every combination) |
SELF JOIN | Join a table to itself |
-- INNER JOIN: employees with their department name
SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;
-- LEFT JOIN: all employees even if no department
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.id;
-- SELF JOIN: employee and their manager
SELECT e1.name AS employee, e2.name AS manager
FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.id;
Format Your SQL Automatically
Paste messy SQL with complex JOINs — get clean, indented output instantly.
Format SQL Now →5. GROUP BY — Aggregating Data
-- Count employees per department
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
-- Aggregate functions
SELECT
department,
COUNT(*) AS emp_count,
AVG(salary) AS avg_salary,
MAX(salary) AS max_salary,
MIN(salary) AS min_salary,
SUM(salary) AS total_payroll
FROM employees
GROUP BY department;
-- Filter groups with HAVING (after aggregation)
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 70000;
-- Common aggregate functions
-- COUNT, SUM, AVG, MAX, MIN, STRING_AGG, ARRAY_AGG
6. Subqueries & CTEs
-- Subquery in WHERE
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
-- Subquery in FROM
SELECT dept, avg_sal
FROM (SELECT department AS dept, AVG(salary) AS avg_sal FROM employees GROUP BY department) sub
WHERE avg_sal > 60000;
-- CTE (Common Table Expression) — clearer than subqueries
WITH dept_stats AS (
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
)
SELECT e.name, e.salary, ds.avg_sal
FROM employees e
JOIN dept_stats ds ON e.department = ds.department
WHERE e.salary > ds.avg_sal;
7. Window Functions
-- ROW_NUMBER: rank rows within a partition
SELECT name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;
-- RANK vs DENSE_RANK (RANK skips ties, DENSE_RANK does not)
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;
-- LAG / LEAD: access previous/next row
SELECT name, hire_date,
LAG(name) OVER (ORDER BY hire_date) AS hired_before,
LEAD(name) OVER (ORDER BY hire_date) AS hired_after
FROM employees;
-- Running total with SUM OVER
SELECT order_date, amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;
8. DDL — Creating & Modifying Tables
-- Create table with constraints
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
department_id INT REFERENCES departments(id),
salary DECIMAL(10,2) CHECK (salary > 0),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Add column
ALTER TABLE employees ADD COLUMN phone VARCHAR(20);
-- Drop column
ALTER TABLE employees DROP COLUMN phone;
-- Rename column (PostgreSQL)
ALTER TABLE employees RENAME COLUMN name TO full_name;
-- Create index
CREATE INDEX idx_employees_dept ON employees(department_id);
-- Create unique index
CREATE UNIQUE INDEX idx_employees_email ON employees(email);
9. DML — Insert, Update, Delete
-- Insert single row
INSERT INTO employees (name, email, department_id, salary)
VALUES ('Alice Chen', 'alice@company.com', 3, 75000);
-- Insert multiple rows
INSERT INTO employees (name, email, department_id, salary)
VALUES
('Bob Smith', 'bob@company.com', 2, 65000),
('Carol Wu', 'carol@company.com', 3, 82000);
-- Insert from SELECT
INSERT INTO employees_archive
SELECT * FROM employees WHERE status = 'terminated';
-- Update rows
UPDATE employees
SET salary = salary * 1.1, updated_at = NOW()
WHERE department_id = 3 AND performance = 'exceeds';
-- Delete rows
DELETE FROM employees
WHERE status = 'terminated' AND updated_at < '2024-01-01';
10. Common Data Types
| Type | MySQL | PostgreSQL | T-SQL |
|---|---|---|---|
| Integer | INT, BIGINT | INTEGER, BIGINT | INT, BIGINT |
| Decimal | DECIMAL(10,2) | NUMERIC(10,2) | DECIMAL(10,2) |
| String | VARCHAR(255) | VARCHAR(255) | NVARCHAR(255) |
| Text | TEXT | TEXT | NVARCHAR(MAX) |
| Boolean | TINYINT(1) | BOOLEAN | BIT |
| Date/Time | DATETIME | TIMESTAMP | DATETIME2 |
| Auto-increment | AUTO_INCREMENT | SERIAL | IDENTITY(1,1) |
| JSON | JSON | JSONB | NVARCHAR(MAX) |
Dialect Differences at a Glance
A large share of the questions in this cheat sheet have a different answer per engine. This table collects the ones that bite hardest when a query moves between platforms, starting with the two that fail silently instead of raising an error.
| Task | MySQL | PostgreSQL | T-SQL |
|---|---|---|---|
| Limit rows | LIMIT 10 | LIMIT 10 | SELECT TOP 10 |
| Concatenate strings | CONCAT(a, b) | a || b | a + b or CONCAT |
| Quote an identifier | `name` | "name" | [name] |
| Random row | ORDER BY RAND() | ORDER BY RANDOM() | ORDER BY NEWID() |
| Null-safe comparison | a <=> b | a IS NOT DISTINCT FROM b | a IS NOT DISTINCT FROM b (2022+) |
| Upsert | ON DUPLICATE KEY UPDATE | ON CONFLICT DO UPDATE | MERGE |
| Auto-increment | AUTO_INCREMENT | GENERATED ... AS IDENTITY | IDENTITY(1,1) |
| Regex match | REGEXP | ~ | no built-in operator |
| Execution plan | EXPLAIN | EXPLAIN ANALYZE | SET SHOWPLAN_ALL ON |
Two of these fail quietly rather than raising an error. In MySQL, || is the logical OR unless PIPES_AS_CONCAT is enabled, so 'a' || 'b' evaluates to 1 instead of 'ab'. And identifier case folding differs: PostgreSQL folds unquoted names to lower case, so a column created as EmployeeID is stored as employeeid and only resolves if you double-quote it everywhere. T-SQL follows the collation of the database, which is why one schema can behave differently on two servers.
11. String Functions
Text is the messiest data most of us handle: padded, mixed-case, half-normalized, and occasionally NULL when nobody expected it. These are the functions worth having in muscle memory, with the T-SQL spelling shown where it differs from the portable name.
| Function | What it does | Example |
|---|---|---|
UPPER / LOWER | Change case | UPPER(email) |
LENGTH / LEN | Length of a string | LENGTH(name) |
TRIM, LTRIM, RTRIM | Strip surrounding spaces | TRIM(raw_input) |
SUBSTRING | Extract part of a string | SUBSTRING(phone, 1, 3) |
REPLACE | Swap every occurrence | REPLACE(phone, '-', '') |
CONCAT | Join strings together | CONCAT(first_name, ' ', last_name) |
LEFT / RIGHT | First or last n characters | LEFT(code, 2) |
COALESCE | First non-NULL argument | COALESCE(nickname, first_name) |
NULLIF | Turn a value into NULL | NULLIF(status, 'unknown') |
CAST / CONVERT | Change the data type | CAST(id AS CHAR) |
-- Build a display name, normalise case, measure the result
SELECT
CONCAT(COALESCE(nickname, first_name), ' ', last_name) AS display_name,
UPPER(LEFT(department, 3)) AS dept_code,
LENGTH(TRIM(comment)) AS comment_length
FROM users
WHERE LOWER(email) = LOWER(?);
Nulls and concatenation
Concatenation is the classic silent failure. CONCAT('a', NULL) returns NULL in MySQL, and so does 'a' || NULL in PostgreSQL — one NULL column wipes out the whole built string, and you find out in the report rather than the test suite. T-SQL's CONCAT treats NULL as an empty string instead, and PostgreSQL's variadic concat() does the same, so two queries that look identical behave differently. If any input can be NULL, wrap it in COALESCE(col, '') before joining, or use CONCAT_WS(), which both MySQL and PostgreSQL provide and which skips NULL arguments by design.
Indexing and lengths
Every mainstream engine numbers string positions from 1, and the third argument of SUBSTRING is a length rather than an end position, so SUBSTRING(name, 1, 3) returns the first three characters. T-SQL requires all three arguments; MySQL and PostgreSQL let you omit the length to mean "through the end of the string", and MySQL alone accepts a negative start to count from the right. LENGTH() is the other portability trap: in MySQL it counts bytes while CHAR_LENGTH() counts characters, so an 8-character UTF-8 value can report 24. On any column that may hold non-ASCII text, prefer CHAR_LENGTH() in MySQL and LENGTH() elsewhere.
12. Date & Time Functions
Date arithmetic is where copy-pasting a query between engines fails most often, because the syntax changes even when the intent does not. The table maps the common operations across all three platforms.
| Task | MySQL | PostgreSQL | T-SQL |
|---|---|---|---|
| Current timestamp | NOW() | NOW() | GETDATE(), SYSDATETIME() |
| Current date | CURDATE() | CURRENT_DATE | CAST(GETDATE() AS DATE) |
| Add an interval | d + INTERVAL 7 DAY | d + INTERVAL '7 days' | DATEADD(day, 7, d) |
| Difference between two dates | DATEDIFF(a, b) | a - b | DATEDIFF(day, a, b) |
| Extract one part | EXTRACT(YEAR FROM d) | EXTRACT(YEAR FROM d) | DATEPART(year, d) |
| Truncate to first of month | DATE_FORMAT(d, '%Y-%m-01') | DATE_TRUNC('month', d) | DATETRUNC(month, d) |
| Format as text | DATE_FORMAT(d, '%Y-%m') | TO_CHAR(d, 'YYYY-MM') | FORMAT(d, 'yyyy-MM') |
-- Orders placed in the last 30 days
-- MySQL
SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL 30 DAY;
-- PostgreSQL
SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL '30 days';
-- T-SQL
SELECT * FROM orders WHERE created_at >= DATEADD(day, -30, GETDATE());
-- Revenue per month, portable between MySQL and PostgreSQL
SELECT EXTRACT(YEAR FROM paid_at) AS yr,
EXTRACT(MONTH FROM paid_at) AS mo,
SUM(amount) AS revenue
FROM orders
WHERE paid_at >= '2026-01-01'
GROUP BY 1, 2
ORDER BY 1, 2;
Date traps worth memorising
Argument order in DATEDIFF is reversed. MySQL's DATEDIFF(a, b) returns a - b in whole days, while T-SQL's DATEDIFF(day, a, b) returns b - a. Swap the arguments and you get a sign flip rather than an error, which is exactly the kind of bug that survives code review.
BETWEEN on a timestamp is a half-open range pretending not to be. created_at BETWEEN '2026-01-01' AND '2026-01-31' quietly excludes everything after midnight on the 31st. Write the half-open form instead — created_at >= '2026-01-01' AND created_at < '2026-02-01' — and it behaves correctly for dates, timestamps, and time zones alike.
Wrapping a column in a function kills the index. WHERE DATE(created_at) = '2026-09-29' forces a full scan because the index stores created_at, not DATE(created_at). Filter with a range and apply the function to the SELECT list only. Time zones follow the same logic: store UTC, since MySQL's DATETIME and T-SQL's DATETIME2 both discard the offset silently.
13. JSON Functions
JSON columns are common enough that you cannot avoid them: feature flags, webhook payloads, and audit events all tend to land as documents. Every major engine now has a JSON type and a path syntax, but the operators share almost no names.
| Task | MySQL | PostgreSQL | T-SQL |
|---|---|---|---|
| Field as JSON value | doc->'$.name' | doc->'name' | JSON_QUERY(doc, '$.name') |
| Field as text | doc->>'$.name' | doc->>'name' | JSON_VALUE(doc, '$.name') |
| Nested path | '$.user.city' | doc#>>'{user,city}' | '$.user.city' |
| Array elements as rows | JSON_TABLE(...) | jsonb_array_elements(doc) | OPENJSON(doc) |
| Index for filtering | generated column + index | GIN index on the jsonb column | computed column + index |
-- PostgreSQL: filter on a JSON field, then cast the extracted text
SELECT id, payload->>'status' AS status
FROM events
WHERE payload->>'type' = 'signup'
AND (payload->>'amount')::numeric > 100;
-- MySQL: same idea, dollar-rooted paths
SELECT id, payload->>'$.status' AS status
FROM events
WHERE payload->>'$.type' = 'signup'
AND CAST(payload->>'$.amount' AS DECIMAL(10,2)) > 100;
-- T-SQL: JSON lives in NVARCHAR(MAX) and is parsed on read
SELECT id, JSON_VALUE(payload, '$.status') AS status
FROM events
WHERE JSON_VALUE(payload, '$.type') = 'signup';
What to watch out for
Single arrow versus double arrow. In both MySQL and PostgreSQL the double arrow unquotes the value and returns text; the single arrow returns a JSON value that still carries its quotes. Comparing a single-arrow result to a string literal is the most common JSON bug there is, because the comparison fails even though the printed values look identical.
Extraction does not coerce types. Every value that comes out of a JSON path is text, so > 100 against an extracted field compares strings in some engines and numbers in others. Cast explicitly, as the examples above do.
Indexing needs help. A GIN index on a jsonb column accelerates containment queries but not an arbitrary path comparison, so PostgreSQL needs an expression index on the extracted field. MySQL 8 can index a functional expression directly while MySQL 5.7 needs a generated column, and T-SQL needs a persisted computed column. Prefer jsonb over json for anything you query: raw json preserves whitespace and duplicate keys, jsonb does not.
14. Transactions, Locking & Permissions
Changing data is half the job; the other half is deciding when the change becomes visible, what it locks while it runs, and who is allowed to run it at all. These are the statements worth knowing before touching anything that matters.
-- Explicit transaction
BEGIN; -- MySQL / PostgreSQL
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK
-- Partial rollback with a savepoint
BEGIN;
UPDATE orders SET status = 'shipped' WHERE id = 42;
SAVEPOINT before_audit;
INSERT INTO audit_log (event) VALUES ('order 42 shipped');
ROLLBACK TO SAVEPOINT before_audit; -- keeps the UPDATE, drops the log row
COMMIT;
-- Lock the rows you are about to update
SELECT * FROM jobs WHERE status = 'pending' FOR UPDATE;
SELECT * FROM jobs WHERE status = 'pending' FOR UPDATE SKIP LOCKED;
-- Isolation level for this transaction only
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
| Task | MySQL | PostgreSQL | T-SQL |
|---|---|---|---|
| Start a transaction | BEGIN / START TRANSACTION | BEGIN | BEGIN TRANSACTION |
| Default isolation | REPEATABLE READ | READ COMMITTED | READ COMMITTED |
| Row lock hint | FOR UPDATE | FOR UPDATE | WITH (UPDLOCK) |
| Grant read access | GRANT SELECT ON shop.* TO 'app' | GRANT SELECT ON orders TO app | GRANT SELECT ON dbo.Orders TO app |
| Revoke | REVOKE SELECT ON shop.* FROM 'app' | REVOKE SELECT ON orders FROM app | REVOKE SELECT ON dbo.Orders FROM app |
-- PostgreSQL: a read-only role for analytics
CREATE ROLE analyst LOGIN;
GRANT USAGE ON SCHEMA public TO analyst;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO analyst;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO analyst;
-- MySQL
CREATE USER 'analyst'@'%' IDENTIFIED BY 'change-me';
GRANT SELECT ON shop.* TO 'analyst'@'%';
-- T-SQL: reuse the built-in role
ALTER ROLE db_datareader ADD MEMBER analyst;
DDL inside a transaction does not behave the same everywhere
PostgreSQL and SQL Server run DDL inside the surrounding transaction, so a migration that creates three tables and fails on the third rolls all of them back. MySQL commits implicitly before and after almost every DDL statement, so a CREATE TABLE survives even when the transaction around it rolls back, and TRUNCATE cannot be undone. If a migration has to be atomic, check the engine's rules before promising that a failed deploy leaves no trace.
Least privilege, in practice
Applications should connect with an account that holds only the privileges they actually need: SELECT, INSERT, UPDATE, and DELETE on the tables they own, and nothing on the schema. Reserve DDL and GRANT for migration accounts that only run during deployment. Two details save time later: FLUSH PRIVILEGES in MySQL is only required when you edit the grant tables directly, because CREATE USER and GRANT take effect immediately; and in PostgreSQL, privileges on existing objects and future objects are separate settings, so ALTER DEFAULT PRIVILEGES is what keeps a role working after the next migration creates a table.
FAQ
What are the basic SQL commands every beginner should know?
Start with SELECT, INSERT, UPDATE, and DELETE — the four fundamental operations. Then learn WHERE (filtering), JOIN (combining tables), GROUP BY (aggregation), and ORDER BY (sorting). These 8 commands cover 90% of daily SQL work.
How do I format SQL queries to make them readable?
Use uppercase for keywords, put each clause on a new line, indent subqueries, and format column lists vertically. Or use SQLFormat.io to auto-format any query in one click — 15+ dialects supported.
What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only rows with matches in both tables. LEFT JOIN returns all rows from the left table plus matching rows from the right — unmatched right columns get NULL. Use LEFT JOIN when you need all rows from the main table regardless of matches.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping, so it cannot reference aggregate functions such as COUNT() or SUM(). HAVING filters groups after GROUP BY and can reference aggregates. If the condition involves a SUM or COUNT it belongs in HAVING; everything else belongs in WHERE, because filtering earlier reduces the rows that reach the aggregation step.