SQL Queries Cheatsheet
sqlSQL query reference — SELECT to advanced JOINs and window functions.
Basic SELECT
SELECT column1, column2 FROM table_nameRetrieves specific columns from a table
SELECT name, email FROM usersSELECT * FROM table_nameRetrieves all columns from a table
SELECT * FROM productsSELECT columns FROM table WHERE conditionFilters rows based on a specified condition
SELECT * FROM users WHERE age > 18SELECT columns FROM table ORDER BY column [ASC|DESC]Sorts the result set by specified columns
SELECT * FROM products ORDER BY price DESCSELECT columns FROM table LIMIT numberRestricts the number of rows returned
SELECT * FROM orders LIMIT 10SELECT columns FROM table LIMIT n OFFSET mSkips a specified number of rows before returning results
SELECT * FROM users LIMIT 10 OFFSET 20SELECT DISTINCT column FROM tableReturns only unique values eliminating duplicates
SELECT DISTINCT country FROM customersSELECT column AS alias_name FROM tableRenames a column or table with a temporary alias
SELECT first_name AS name, COUNT(*) AS total FROM usersFiltering
WHERE condition1 AND condition2Combines conditions where all must be true
SELECT * FROM users WHERE age > 18 AND status = 'active'WHERE condition1 OR condition2Combines conditions where at least one must be true
SELECT * FROM products WHERE category = 'books' OR category = 'music'WHERE NOT conditionNegates a condition
SELECT * FROM users WHERE NOT country = 'USA'WHERE column IN (value1, value2, ...)Matches any value in a specified list
SELECT * FROM orders WHERE status IN ('pending', 'processing')WHERE column BETWEEN value1 AND value2Selects values within a given inclusive range
SELECT * FROM products WHERE price BETWEEN 10 AND 100WHERE column LIKE patternSearches for a specified pattern using wildcards % and _
SELECT * FROM users WHERE email LIKE '%@gmail.com'WHERE column IS NULLChecks for NULL values in a column
SELECT * FROM customers WHERE phone IS NULLWHERE column IS NOT NULLChecks for non-NULL values in a column
SELECT * FROM orders WHERE shipped_date IS NOT NULLWHERE EXISTS (subquery)Returns true if the subquery returns any rows
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders WHERE customer_id = c.id)Joins
SELECT cols FROM t1 INNER JOIN t2 ON t1.col = t2.colReturns rows that have matching values in both tables
SELECT orders.id, customers.name FROM orders INNER JOIN customers ON orders.customer_id = customers.idSELECT cols FROM t1 LEFT JOIN t2 ON t1.col = t2.colReturns all rows from left table and matched rows from right table
SELECT users.name, orders.id FROM users LEFT JOIN orders ON users.id = orders.user_idSELECT cols FROM t1 RIGHT JOIN t2 ON t1.col = t2.colReturns all rows from right table and matched rows from left table
SELECT orders.id, customers.name FROM orders RIGHT JOIN customers ON orders.customer_id = customers.idSELECT cols FROM t1 FULL OUTER JOIN t2 ON t1.col = t2.colReturns all rows when there is a match in either table
SELECT a.name, b.order_id FROM customers a FULL OUTER JOIN orders b ON a.id = b.customer_idSELECT cols FROM t1 CROSS JOIN t2Returns Cartesian product of both tables
SELECT colors.name, sizes.name FROM colors CROSS JOIN sizesSELECT cols FROM table t1 JOIN table t2 ON t1.col = t2.colJoins a table to itself to compare rows within the same table
SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.idAggregation
SELECT col, AGG(col2) FROM table GROUP BY colGroups rows sharing a property to apply aggregate functions
SELECT country, COUNT(*) FROM users GROUP BY countrySELECT col, AGG(col2) FROM table GROUP BY col HAVING conditionFilters groups based on aggregate function results
SELECT category, AVG(price) FROM products GROUP BY category HAVING AVG(price) > 50COUNT(column) or COUNT(*)Returns the number of rows or non-NULL values
SELECT COUNT(*) FROM orders WHERE status = 'completed'SUM(column)Returns the total sum of a numeric column
SELECT SUM(amount) AS total_sales FROM ordersAVG(column)Returns the average value of a numeric column
SELECT AVG(rating) FROM reviews WHERE product_id = 1MIN(column)Returns the smallest value in a column
SELECT MIN(price) AS cheapest FROM productsMAX(column)Returns the largest value in a column
SELECT MAX(salary) AS highest_salary FROM employeesSubqueries
SELECT col, (SELECT AGG(col) FROM t2) FROM t1Returns a single value to be used in the outer query
SELECT name, (SELECT AVG(salary) FROM employees) AS avg_sal FROM employeesSELECT cols FROM t1 WHERE col IN (SELECT col FROM t2)Uses subquery result to filter the outer query
SELECT * FROM products WHERE category_id IN (SELECT id FROM categories WHERE active = 1)SELECT cols FROM t1 WHERE col op (SELECT col FROM t2 WHERE t2.col = t1.col)Subquery that references columns from the outer query
SELECT * FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id)WITH cte_name AS (SELECT ...) SELECT ... FROM cte_nameCreates a named temporary result set for the main query
WITH top_sales AS (SELECT * FROM orders WHERE amount > 1000) SELECT customer_id, COUNT(*) FROM top_sales GROUP BY customer_idWITH RECURSIVE cte AS (base UNION ALL recursive) SELECT * FROM cteCTE that references itself to handle hierarchical data
WITH RECURSIVE org AS (SELECT id, name, manager_id FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.id, e.name, e.manager_id FROM employees e JOIN org ON e.manager_id = org.id) SELECT * FROM orgWindow Functions
function() OVER ([PARTITION BY col] [ORDER BY col])Defines a window frame for the window function to operate on
SELECT name, salary, SUM(salary) OVER () AS total FROM employeesfunction() OVER (PARTITION BY column)Divides the result set into partitions for window calculations
SELECT dept, name, AVG(salary) OVER (PARTITION BY dept) FROM employeesROW_NUMBER() OVER (ORDER BY column)Assigns a unique sequential integer to each row
SELECT name, ROW_NUMBER() OVER (ORDER BY created_at) AS rn FROM usersRANK() OVER (ORDER BY column)Assigns rank with gaps for ties
SELECT name, score, RANK() OVER (ORDER BY score DESC) FROM playersDENSE_RANK() OVER (ORDER BY column)Assigns rank without gaps for ties
SELECT name, score, DENSE_RANK() OVER (ORDER BY score DESC) FROM playersLAG(column, offset, default) OVER (ORDER BY column)Accesses data from a previous row in the result set
SELECT date, sales, LAG(sales, 1) OVER (ORDER BY date) AS prev_sales FROM daily_salesLEAD(column, offset, default) OVER (ORDER BY column)Accesses data from a subsequent row in the result set
SELECT date, price, LEAD(price, 1) OVER (ORDER BY date) AS next_price FROM stocksFIRST_VALUE(column) OVER (PARTITION BY col ORDER BY col)Returns the first value in the window frame
SELECT name, FIRST_VALUE(name) OVER (PARTITION BY dept ORDER BY hire_date) AS first_hire FROM employeesLAST_VALUE(column) OVER (... ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)Returns the last value in the window frame
SELECT name, LAST_VALUE(name) OVER (PARTITION BY dept ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM employeesMutations
INSERT INTO table (col1, col2) VALUES (val1, val2)Adds new rows to a table
INSERT INTO users (name, email) VALUES ('John', 'john@example.com')INSERT INTO table (cols) VALUES (vals1), (vals2), (vals3)Inserts multiple rows in a single statement
INSERT INTO products (name, price) VALUES ('A', 10), ('B', 20), ('C', 30)INSERT INTO table1 (cols) SELECT cols FROM table2Inserts rows from another table or query result
INSERT INTO archived_orders SELECT * FROM orders WHERE created_at < '2023-01-01'UPDATE table SET col1 = val1, col2 = val2 WHERE conditionModifies existing rows in a table
UPDATE users SET status = 'inactive' WHERE last_login < '2023-01-01'UPDATE t1 SET t1.col = t2.col FROM t1 JOIN t2 ON conditionUpdates rows based on values from another table
UPDATE orders SET status = 'vip' FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.tier = 'gold'DELETE FROM table WHERE conditionRemoves rows from a table based on a condition
DELETE FROM sessions WHERE expires_at < NOW()INSERT INTO table (cols) VALUES (vals) ON CONFLICT (col) DO UPDATE SET col = valInserts a row or updates it if a conflict occurs
INSERT INTO users (id, name) VALUES (1, 'John') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.nameINSERT INTO table (cols) VALUES (vals) ON DUPLICATE KEY UPDATE col = valInserts a row or updates it if duplicate key exists
INSERT INTO users (id, name) VALUES (1, 'John') ON DUPLICATE KEY UPDATE name = VALUES(name)TRUNCATE TABLE table_nameRemoves all rows from a table quickly without logging individual deletions
TRUNCATE TABLE temp_data