Kodewick
Start learning →

SQL Cheat Sheet

47 statements, each with what it does, how it is written, an example and its result. Press Run to run it in the editor, or Step to watch it work out each step. The examples use ready-made databases: nothing to set up.

Select

Some columns

Column names separated by commas, shown in that order.

SELECT col1, col2 FROM table;
Database · School
SELECT name, class FROM student;
Result
nameclass
Maya LinCS-1
Ethan ColeCS-1
Noah ParkCS-2
Ava ReedCS-2
Zoe HartSE-1
Liam ShawSE-1

8 rows · 2 more: press Run to see them all

Rename with AS

The result shows the new name; the table is unchanged.

SELECT col AS new_name FROM table;
Database · School
SELECT name AS student_name, class AS class_name FROM student;
Result
student_nameclass_name
Maya LinCS-1
Ethan ColeCS-1
Noah ParkCS-2
Ava ReedCS-2
Zoe HartSE-1
Liam ShawSE-1

8 rows · 2 more: press Run to see them all

No repeats: DISTINCT

Rows that are the same are shown once.

SELECT DISTINCT col FROM table;
Database · School
SELECT DISTINCT class FROM student;
Result
class
CS-1
CS-2
SE-1

3 rows

A computed column

An expression in SELECT gives a new column.

SELECT col, col * 0.9 AS x FROM table;
Database · Shop
SELECT name, price, price * 0.9 AS sale_price FROM product;
Result
namepricesale_price
Mechanical keyboard299.00269.100
Wireless mouse89.9080.910
Travel mug59.0053.100
Desk lamp129.00116.100
Notebook12.5011.250
Fountain pen45.0040.500

6 rows

Filter

WHERE

Only the rows where the condition is true.

SELECT * FROM table WHERE condition;
Database · School
SELECT * FROM enroll WHERE score >= 90;
Result
sidcidscore
1196
1390
2293
5191
8398

5 rows

AND / OR

AND: both; OR: either. Use brackets when you mix them.

WHERE a AND (b OR c)
Database · Shop
SELECT * FROM product WHERE price < 100 AND (category = 'Tech' OR category = 'Office');
Result
idnamecategoryprice
2Wireless mouseTech89.90
5NotebookOffice12.50
6Fountain penOffice45.00

3 rows

IN a list

Equal to any value in the list.

WHERE col IN (v1, v2)
Database · School
SELECT * FROM enroll WHERE cid IN (1, 3);
Result
sidcidscore
1196
1390
2381
3188
4167
5191

8 rows · 2 more: press Run to see them all

BETWEEN

Both ends included.

WHERE col BETWEEN low AND high
Database · Shop
SELECT name, price FROM product WHERE price BETWEEN 50 AND 150;
Result
nameprice
Wireless mouse89.90
Travel mug59.00
Desk lamp129.00

3 rows

LIKE

% matches any characters, _ exactly one.

WHERE col LIKE 'a%'
Database · School
SELECT * FROM student WHERE class LIKE 'CS%';
Result
idnamegenderclassemail
1Maya LinFCS-1[email protected]
2Ethan ColeMCS-1NULL
3Noah ParkMCS-2[email protected]
4Ava ReedFCS-2NULL
8Ivy ChenFCS-1[email protected]

5 rows

IS NULL

NULL is never = anything: use IS NULL / IS NOT NULL.

WHERE col IS NULL
Database · School
SELECT name FROM student WHERE email IS NULL;
Result
name
Ethan Cole
Ava Reed
Owen Brooks

3 rows

Sort and page

ORDER BY

ASC smallest first (the default), DESC largest first.

ORDER BY col DESC
Database · Shop
SELECT name, price FROM product ORDER BY price DESC;
Result
nameprice
Mechanical keyboard299.00
Desk lamp129.00
Wireless mouse89.90
Travel mug59.00
Fountain pen45.00
Notebook12.50

6 rows

Two sort keys

By the first column, then the second where the first is equal.

ORDER BY col1, col2 DESC
Database · School
SELECT * FROM enroll ORDER BY cid, score DESC;
Result
sidcidscore
1196
5191
3188
4167
2293
5284

15 rows · 9 more: press Run to see them all

LIMIT

With ORDER BY: the top 3.

LIMIT n
Database · School
SELECT * FROM enroll ORDER BY score DESC LIMIT 3;
Result
sidcidscore
8398
1196
2293

3 rows

Pages: LIMIT OFFSET

Skip OFFSET rows, then take LIMIT.

LIMIT n OFFSET m
Database · School
SELECT * FROM student ORDER BY id LIMIT 3 OFFSET 3;
Result
idnamegenderclassemail
4Ava ReedFCS-2NULL
5Zoe HartFSE-1[email protected]
6Liam ShawMSE-1[email protected]

3 rows

Aggregate and group

COUNT

COUNT(*) counts rows, COUNT(col) skips NULLs.

SELECT COUNT(*) FROM table;
Database · School
SELECT COUNT(*) AS students, COUNT(email) AS with_email FROM student;
Result
studentswith_email
85

1 row

SUM, AVG, MAX, MIN

Work over a column, one row out.

SELECT SUM(col), AVG(col), MAX(col), MIN(col) FROM table;
Database · School
SELECT SUM(score), AVG(score), MAX(score), MIN(score) FROM enroll;
Result
SUM(score)AVG(score)MAX(score)MIN(score)
121480.93339855

1 row

GROUP BY

One aggregate per group, one row per group.

SELECT col, COUNT(*) FROM table GROUP BY col;
Database · School
SELECT class, COUNT(*) AS n FROM student GROUP BY class;
Result
classn
CS-13
CS-22
SE-13

3 rows

HAVING

WHERE filters rows, HAVING filters groups (aggregates allowed).

GROUP BY col HAVING COUNT(*) > n
Database · School
SELECT cid, AVG(score) AS avg_score FROM enroll GROUP BY cid HAVING AVG(score) >= 80;
Result
cidavg_score
185.5000
386.5000

2 rows

Group by two columns

A group: the same values in both columns.

GROUP BY col1, col2
Database · School
SELECT class, gender, COUNT(*) AS n FROM student GROUP BY class, gender ORDER BY class;
Result
classgendern
CS-1F2
CS-1M1
CS-2M1
CS-2F1
SE-1F1
SE-1M2

6 rows

Join

INNER JOIN

Rows of two tables paired by a condition; rows with no partner are left out.

FROM a JOIN b ON a.x = b.y
Database · School
SELECT s.name, e.cid, e.score
FROM enroll e
JOIN student s ON s.id = e.sid;
Result
namecidscore
Maya Lin196
Maya Lin390
Maya Lin478
Ethan Cole293
Ethan Cole381
Ethan Cole459

15 rows · 9 more: press Run to see them all

Three tables

One JOIN after another.

FROM a JOIN b ON … JOIN c ON …
Database · School
SELECT s.name, c.title, e.score
FROM enroll e
JOIN student s ON s.id = e.sid
JOIN course c ON c.id = e.cid;
Result
nametitlescore
Maya LinDatabases96
Maya LinPython90
Maya LinCalculus78
Ethan ColeC Programming93
Ethan ColePython81
Ethan ColeCalculus59

15 rows · 9 more: press Run to see them all

LEFT JOIN

Every row of the left table; NULL where the right has no partner.

FROM a LEFT JOIN b ON a.x = b.y
Database · School
SELECT s.name, e.cid, e.score
FROM student s
LEFT JOIN enroll e ON e.sid = s.id;
Result
namecidscore
Maya Lin196
Maya Lin390
Maya Lin478
Ethan Cole293
Ethan Cole381
Ethan Cole459

16 rows · 10 more: press Run to see them all

Rows with no partner

LEFT JOIN, then keep the rows where the right side is NULL.

LEFT JOIN b ON … WHERE b.y IS NULL
Database · School
SELECT s.name
FROM student s
LEFT JOIN enroll e ON e.sid = s.id
WHERE e.sid IS NULL;
Result
name
Owen Brooks

1 row

Self join

One table under two names, joined to itself.

FROM t a JOIN t b ON a.x = b.y
Database · Company
SELECT e.name AS employee, m.name AS manager
FROM emp e
LEFT JOIN emp m ON m.id = e.manager_id;
Result
employeemanager
Sarah (CEO)NULL
DanSarah (CEO)
PriyaDan
TomDan
GraceSarah (CEO)
BenGrace

9 rows · 3 more: press Run to see them all

Join, then group

Join first, then count per group.

FROM a JOIN b … GROUP BY …
Database · Shop
SELECT c.name, COUNT(o.id) AS orders
FROM customer c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;
Result
nameorders
Emma Stone2
Lucas Gray2
Mia Ross1
Jack Hill1
Ella Ward0

5 rows

Subqueries and sets

A subquery in WHERE

Work one value out first, then compare with it.

WHERE col > (SELECT AVG(col) FROM table)
Database · Shop
SELECT name, price FROM product
WHERE price > (SELECT AVG(price) FROM product);
Result
nameprice
Mechanical keyboard299.00
Desk lamp129.00

2 rows

IN (subquery)

In what another query returns.

WHERE col IN (SELECT …)
Database · School
SELECT name FROM student
WHERE id IN (SELECT sid FROM enroll WHERE score >= 90);
Result
name
Maya Lin
Ethan Cole
Zoe Hart
Ivy Chen

4 rows

EXISTS

True when the subquery returns any row.

WHERE EXISTS (SELECT 1 FROM … WHERE …)
Database · Shop
SELECT name FROM customer c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
Result
name
Emma Stone
Lucas Gray
Mia Ross
Jack Hill

4 rows

A subquery in FROM

A query's result used as a table: it needs a name.

FROM (SELECT …) AS t
Database · School
SELECT AVG(n) AS avg_courses
FROM (SELECT sid, COUNT(*) AS n FROM enroll GROUP BY sid) AS t;
Result
avg_courses
2.1429

1 row

WITH (CTE)

Name a query first, then use it like a table.

WITH t AS (SELECT …) SELECT … FROM t;
Database · School
WITH top AS (
  SELECT sid, MAX(score) AS best FROM enroll GROUP BY sid
)
SELECT s.name, top.best
FROM top JOIN student s ON s.id = top.sid
ORDER BY top.best DESC;
Result
namebest
Ivy Chen98
Maya Lin96
Ethan Cole93
Zoe Hart91
Noah Park88
Ava Reed85

7 rows · 1 more: press Run to see them all

UNION

One result under the other; UNION drops repeats, UNION ALL keeps them.

SELECT … UNION SELECT …
Database · Shop
SELECT city FROM customer WHERE city IS NOT NULL
UNION
SELECT category FROM product;
Result
city
Boston
Chicago
Austin
Tech
Home
Office

6 rows

Functions and expressions

CASE

A value by condition, like if / else.

CASE WHEN cond THEN a ELSE b END
Database · School
SELECT sid, score,
  CASE WHEN score >= 90 THEN 'A'
       WHEN score >= 60 THEN 'pass'
       ELSE 'fail' END AS grade
FROM enroll;
Result
sidscoregrade
196A
190A
178pass
293A
281pass
259fail

15 rows · 9 more: press Run to see them all

IFNULL / COALESCE

The second value where the first is NULL.

IFNULL(col, value)
Database · School
SELECT name, IFNULL(email, 'no email') AS email FROM student;
Result
nameemail
Maya Lin[email protected]
Ethan Coleno email
Noah Park[email protected]
Ava Reedno email
Zoe Hart[email protected]
Liam Shaw[email protected]

8 rows · 2 more: press Run to see them all

CONCAT

Join pieces of text into one.

CONCAT(a, b, …)
Database · School
SELECT CONCAT(name, ' (', class, ')') AS who FROM student;
Result
who
Maya Lin (CS-1)
Ethan Cole (CS-1)
Noah Park (CS-2)
Ava Reed (CS-2)
Zoe Hart (SE-1)
Liam Shaw (SE-1)

8 rows · 2 more: press Run to see them all

Text functions

LENGTH in bytes, CHAR_LENGTH in characters, UPPER / LOWER, SUBSTRING.

CHAR_LENGTH(s), UPPER(s), SUBSTRING(s, start, n)
Database · School
SELECT email, CHAR_LENGTH(email) AS len, UPPER(email) AS up, SUBSTRING(email, 1, 4) AS first4
FROM student WHERE email IS NOT NULL;

ROUND and friends

ROUND rounds, FLOOR / CEIL to whole numbers, MOD the remainder.

ROUND(x, digits)
Database · School
SELECT cid, ROUND(AVG(score), 1) AS avg_score FROM enroll GROUP BY cid;
Result
cidavg_score
185.5
386.5
474.0
276.0

4 rows

Dates

YEAR / MONTH, DATEDIFF in days, DATE_FORMAT.

YEAR(d), DATEDIFF(d1, d2), DATE_FORMAT(d, fmt)
Database · Shop
SELECT id, order_date, MONTH(order_date) AS m, DATEDIFF('2026-11-01', order_date) AS days_ago
FROM orders;
Result
idorder_datemdays_ago
1012026-09-01961
1022026-09-03959
1032026-09-15947
1042026-10-021030
1052026-10-081024
1062026-10-201012

6 rows

Ranking: window functions

OVER says how to group and order; every row stays.

RANK() OVER (PARTITION BY a ORDER BY b DESC)
Database · School
SELECT cid, sid, score,
  RANK() OVER (PARTITION BY cid ORDER BY score DESC) AS rk
FROM enroll;
Result
cidsidscorerk
11961
15912
13883
14674
22931
25842

15 rows · 9 more: press Run to see them all

A running total

Added up row by row, in order.

SUM(col) OVER (ORDER BY col2)
Database · Shop
SELECT o.id, o.order_date, SUM(i.qty) OVER (ORDER BY o.order_date) AS items_so_far
FROM orders o JOIN order_item i ON i.order_id = o.id
ORDER BY o.order_date;
Result
idorder_dateitems_so_far
1012026-09-015
1012026-09-015
1022026-09-038
1022026-09-038
1032026-09-1511
1032026-09-1511

12 rows · 6 more: press Run to see them all

Insert, update, delete

INSERT

Columns and values in the same order; many rows at once.

INSERT INTO table (c1, c2) VALUES (v1, v2), (…);
Database · School
INSERT INTO course (id, title, credit) VALUES (5, 'Linear algebra', 4);
SELECT * FROM course;
Result
idtitlecredit
1Databases3
2C Programming4
3Python3
4Calculus5
5Linear algebra4

5 rows

UPDATE

Don’t forget WHERE, or every row changes.

UPDATE table SET col = value WHERE condition;
Database · Shop
UPDATE product SET price = price * 0.8 WHERE id = 1;
SELECT id, name, price FROM product;
Result
idnameprice
1Mechanical keyboard239.20
2Wireless mouse89.90
3Travel mug59.00
4Desk lamp129.00
5Notebook12.50
6Fountain pen45.00

6 rows

DELETE

WHERE again.

DELETE FROM table WHERE condition;
Database · School
DELETE FROM enroll WHERE score < 60;
SELECT * FROM enroll;
Result
sidcidscore
1196
1390
1478
2293
2381
3188

13 rows · 7 more: press Run to see them all

A transaction

After BEGIN, ROLLBACK undoes every change.

BEGIN; … ROLLBACK; / COMMIT;
Database · School
BEGIN;
DELETE FROM enroll;
SELECT COUNT(*) FROM enroll;
ROLLBACK;
SELECT COUNT(*) FROM enroll;
Result
COUNT(*)
15

1 row

Tables

CREATE TABLE

A name and a type for each column; the PRIMARY KEY never repeats.

CREATE TABLE t (id INT PRIMARY KEY, name VARCHAR(20) NOT NULL);
Database · School
CREATE TABLE club (
  id INT PRIMARY KEY,
  name VARCHAR(20) NOT NULL,
  members INT DEFAULT 0
);
INSERT INTO club (id, name) VALUES (1, 'chess');
SELECT * FROM club;
Result
idnamemembers
1chess0

1 row

ALTER TABLE

ADD a column, DROP COLUMN to remove one.

ALTER TABLE t ADD col TYPE;
Database · School
ALTER TABLE course ADD hours INT;
SELECT * FROM course;
Result
idtitlecredithours
1Databases3NULL
2C Programming4NULL
3Python3NULL
4Calculus5NULL

4 rows

DROP TABLE

The table and its rows are gone; IF EXISTS: no error when it isn’t there.

DROP TABLE IF EXISTS t;
Database · School
DROP TABLE IF EXISTS enroll;
SHOW TABLES;
Result
Tables_in_town
course
student

2 rows

Learn SQL from the start: 23 free lessons →