SQL Cheat Sheet — Quick Reference Guide for Beginners

Published: July 14, 2026 | Updated: September 29, 2026

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.

Table of Contents
  1. Basic SQL Commands
  2. SELECT — Retrieving Data
  3. WHERE — Filtering Rows
  4. JOIN — Combining Tables
  5. GROUP BY — Aggregating Data
  6. Subqueries & CTEs
  7. Window Functions
  8. DDL — Creating & Modifying Tables
  9. DML — Insert, Update, Delete
  10. Common Data Types
  11. Dialect Differences at a Glance
  12. String Functions
  13. Date & Time Functions
  14. JSON Functions
  15. Transactions, Locking & Permissions
  16. FAQ

1. Basic SQL Commands — Quick Reference

CommandDescriptionExample
SELECTRetrieve data from a tableSELECT * FROM users;
INSERTAdd new rowsINSERT INTO users (name) VALUES ('Alice');
UPDATEModify existing rowsUPDATE users SET name='Bob' WHERE id=1;
DELETERemove rowsDELETE FROM users WHERE id=1;
CREATE TABLECreate a new tableCREATE TABLE users (id INT, name TEXT);
ALTER TABLEModify table structureALTER TABLE users ADD email TEXT;
DROP TABLEDelete a tableDROP TABLE users;
TRUNCATEDelete 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

OperatorDescriptionExample
=EqualWHERE dept = 'Engineering'
!= or <>Not equalWHERE status != 'closed'
>, <, >=, <=Greater/less thanWHERE salary > 50000
BETWEENRange (inclusive)WHERE age BETWEEN 18 AND 65
LIKEPattern matchWHERE email LIKE '%@gmail.com'
INMatch any in listWHERE dept IN ('Sales','HR')
IS NULLNull checkWHERE manager_id IS NULL
AND / ORCombine conditionsWHERE 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

TypeDescription
INNER JOINReturns rows with matches in both tables
LEFT JOINReturns all left-table rows + matches from right
RIGHT JOINReturns all right-table rows + matches from left
FULL OUTER JOINReturns all rows from both tables
CROSS JOINCartesian product (every combination)
SELF JOINJoin 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

TypeMySQLPostgreSQLT-SQL
IntegerINT, BIGINTINTEGER, BIGINTINT, BIGINT
DecimalDECIMAL(10,2)NUMERIC(10,2)DECIMAL(10,2)
StringVARCHAR(255)VARCHAR(255)NVARCHAR(255)
TextTEXTTEXTNVARCHAR(MAX)
BooleanTINYINT(1)BOOLEANBIT
Date/TimeDATETIMETIMESTAMPDATETIME2
Auto-incrementAUTO_INCREMENTSERIALIDENTITY(1,1)
JSONJSONJSONBNVARCHAR(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.

TaskMySQLPostgreSQLT-SQL
Limit rowsLIMIT 10LIMIT 10SELECT TOP 10
Concatenate stringsCONCAT(a, b)a || ba + b or CONCAT
Quote an identifier`name`"name"[name]
Random rowORDER BY RAND()ORDER BY RANDOM()ORDER BY NEWID()
Null-safe comparisona <=> ba IS NOT DISTINCT FROM ba IS NOT DISTINCT FROM b (2022+)
UpsertON DUPLICATE KEY UPDATEON CONFLICT DO UPDATEMERGE
Auto-incrementAUTO_INCREMENTGENERATED ... AS IDENTITYIDENTITY(1,1)
Regex matchREGEXP~no built-in operator
Execution planEXPLAINEXPLAIN ANALYZESET 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.

FunctionWhat it doesExample
UPPER / LOWERChange caseUPPER(email)
LENGTH / LENLength of a stringLENGTH(name)
TRIM, LTRIM, RTRIMStrip surrounding spacesTRIM(raw_input)
SUBSTRINGExtract part of a stringSUBSTRING(phone, 1, 3)
REPLACESwap every occurrenceREPLACE(phone, '-', '')
CONCATJoin strings togetherCONCAT(first_name, ' ', last_name)
LEFT / RIGHTFirst or last n charactersLEFT(code, 2)
COALESCEFirst non-NULL argumentCOALESCE(nickname, first_name)
NULLIFTurn a value into NULLNULLIF(status, 'unknown')
CAST / CONVERTChange the data typeCAST(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.

TaskMySQLPostgreSQLT-SQL
Current timestampNOW()NOW()GETDATE(), SYSDATETIME()
Current dateCURDATE()CURRENT_DATECAST(GETDATE() AS DATE)
Add an intervald + INTERVAL 7 DAYd + INTERVAL '7 days'DATEADD(day, 7, d)
Difference between two datesDATEDIFF(a, b)a - bDATEDIFF(day, a, b)
Extract one partEXTRACT(YEAR FROM d)EXTRACT(YEAR FROM d)DATEPART(year, d)
Truncate to first of monthDATE_FORMAT(d, '%Y-%m-01')DATE_TRUNC('month', d)DATETRUNC(month, d)
Format as textDATE_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.

TaskMySQLPostgreSQLT-SQL
Field as JSON valuedoc->'$.name'doc->'name'JSON_QUERY(doc, '$.name')
Field as textdoc->>'$.name'doc->>'name'JSON_VALUE(doc, '$.name')
Nested path'$.user.city'doc#>>'{user,city}''$.user.city'
Array elements as rowsJSON_TABLE(...)jsonb_array_elements(doc)OPENJSON(doc)
Index for filteringgenerated column + indexGIN index on the jsonb columncomputed 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;
TaskMySQLPostgreSQLT-SQL
Start a transactionBEGIN / START TRANSACTIONBEGINBEGIN TRANSACTION
Default isolationREPEATABLE READREAD COMMITTEDREAD COMMITTED
Row lock hintFOR UPDATEFOR UPDATEWITH (UPDLOCK)
Grant read accessGRANT SELECT ON shop.* TO 'app'GRANT SELECT ON orders TO appGRANT SELECT ON dbo.Orders TO app
RevokeREVOKE SELECT ON shop.* FROM 'app'REVOKE SELECT ON orders FROM appREVOKE 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.