Skip to content
Laviyx Learn

Try

SQL Cheat Sheet

The essential SQL statements on one page, from SELECT and WHERE to GROUP BY, JOINs and table changes.

Updated

Read data#

SQL
SELECT col1, col2           -- choose columns
FROM table_name;

SELECT *                    -- every column
FROM table_name;

SELECT DISTINCT city        -- unique values only
FROM customers;

SELECT price * qty AS total -- calculated column with an alias
FROM order_items;

Filter rows#

SQLRun
SELECT * FROM employees
WHERE salary > 50000
  AND (department = 'Sales' OR city IN ('Mumbai', 'Pune'));
-- AND runs before OR: use parentheses when mixing them
OperatorExample
Compare=, <>, >, <, >=, <=
Range (inclusive)salary BETWEEN 40000 AND 60000
Listcity IN ('Mumbai', 'Pune')
Patternname LIKE 'A%' (% any text, _ one char)
Missing valuesmanager_id IS NULL, IS NOT NULL

Sort and limit#

SQLRun
SELECT name, salary
FROM employees
ORDER BY salary DESC, name ASC
LIMIT 10;                 -- MySQL, PostgreSQL, SQLite
-- SQL Server: SELECT TOP 10 ...
-- Standard / Oracle: FETCH FIRST 10 ROWS ONLY

Summarise#

SQL
SELECT department,
       COUNT(*)    AS people,
       AVG(salary) AS avg_salary
FROM employees
WHERE active = 1          -- filter rows (before grouping)
GROUP BY department
HAVING COUNT(*) > 5       -- filter groups (after grouping)
ORDER BY avg_salary DESC;

Aggregates: COUNT(*), COUNT(col), COUNT(DISTINCT col), SUM, AVG, MIN, MAX.

Combine tables#

SQLRun
-- only matching rows
SELECT c.name, o.amount
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;

-- every customer, orders if any (NULL if none)
SELECT c.name, o.amount
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;

-- customers with no orders
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
INNER JOIN of A and B: Only rows that match in both tables.AB
INNER JOIN
LEFT JOIN of A and B: Every row from the left table, plus matches from the right.AB
LEFT JOIN
RIGHT JOIN of A and B: Every row from the right table, plus matches from the left.AB
RIGHT JOIN
FULL OUTER JOIN of A and B: Every row from both tables, matched where possible.AB
FULL OUTER JOIN

Change data#

SQLRun
INSERT INTO customers (name, city)
VALUES ('Asha', 'Mumbai');

UPDATE customers
SET city = 'Pune'
WHERE customer_id = 3;    -- without WHERE, every row changes!

DELETE FROM customers
WHERE customer_id = 3;    -- without WHERE, every row is deleted!

Create and change tables#

SQL
CREATE TABLE customers (
  customer_id INT PRIMARY KEY,
  name        VARCHAR(100) NOT NULL,
  email       VARCHAR(255) UNIQUE,
  city        VARCHAR(50) DEFAULT 'Unknown'
);

ALTER TABLE customers ADD phone VARCHAR(20);
DROP TABLE customers;     -- removes the table and its data

Logical order of a query#

FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT

Want the full explanations? Go to the Learn SQL course →