SQL is the language every database understands, and writing SQL queries is a daily task for developers, data analysts and anyone preparing for a tech interview. About a dozen keywords cover most of the queries you will ever write.
This page teaches SQL queries with examples on one realistic dataset, an online store with 10,000 orders. Every one of the 62 example queries shows its real output, and you can edit and run it right here in your browser. After the lessons there are 50 SQL queries for practice that check your answer automatically. Prefer to study offline? Download all the queries as a free PDF.
What you will find on this page
- An online SQL editor with a sample database of 10,000 orders, 2,000 customers and 300 products. Nothing to install.
- 62 SQL query examples from basic SELECT to joins, subqueries, window functions and CTEs, each with its real output and a “Run this query” button.
- A JOIN visualiser that shows which rows INNER, LEFT, RIGHT and FULL joins keep.
- 50 SQL practice questions (20 easy, 20 medium, 10 hard) that check your query and tell you what is wrong.
- Notes on MySQL, PostgreSQL and SQL Server wherever their syntax differs.
- A cheat sheet, the sample database as a .sql file and a free 44-page PDF.
Related guides (each opens our own post):
Run SQL queries online
Type any SQL query below and press Run (or Ctrl + Enter). It runs in your browser on SQLite, a real database engine, so you can practise without installing MySQL or anything else. Click a table name on the left to see its first rows. You can also insert, update and delete rows; “Reset database” brings back the original data.
Online SQL playground
Sample database: an online store with 7 tables. The database (about 505 KB) loads the first time you run a query.
The sample database: an online store
All the SQL queries on this page use the same seven tables. They model a small Indian online store, with orders from January 2023 to December 2025. The data is made up, but it behaves like the real thing: some customers never ordered, some products never sold, one category is still empty, and a few phone numbers and ratings are missing, so you get to practise with NULLs too.
7 tables, 41,585 rows
People who signed up. Some have no phone number.
customer_id, first_name, last_name, email, phone, gender, city, state, signup_date
One row per order. Status is Delivered, Shipped, Pending, Cancelled or Returned.
order_id, customer_id, order_date, status, total_amount
The products inside each order, with the price actually paid.
item_id, order_id, product_id, quantity, unit_price
The catalogue. Some products have no rating yet.
product_id, product_name, category_id, brand, price, stock, rating, launch_date
Mobiles, Laptops, Audio and more. Toys has no products yet.
category_id, category_name
UPI, Card, COD and others. Unpaid orders have no row here.
payment_id, order_id, method, amount, paid_on
Store staff. manager_id points to another employee.
emp_id, name, department, job_title, manager_id, salary, city, hire_date
How the tables connect: orders.customer_id → customers, order_items.order_id → orders, order_items.product_id → products, products.category_id → categories, payments.order_id → orders, employees.manager_id → employees.
Basic SQL queries: SELECT
Every SQL query that reads data starts with SELECT. You list the columns you want, then say which table they come from with FROM. You will write these basic SQL queries every day.
Select every column from a table
* means “all columns”. It is handy for a quick look at a small table, but in real code list the columns you need, so the query does not break or slow down when someone adds a column.
SELECT *
FROM categories;Output:
category_id | category_name
------------+---------------
1 | Mobiles
2 | Laptops
3 | Audio
4 | Wearables
5 | Fashion
6 | Home & Kitchen
7 | Books
8 | Beauty
9 | Sports
10 | Groceries
11 | Toys
(11 rows)Select only the columns you need
Name the columns, separated by commas. LIMIT 5 keeps the result short while you explore a table with thousands of rows.
SELECT first_name, last_name, city
FROM customers
LIMIT 5;Output:
first_name | last_name | city
-----------+-----------+----------
Anjali | Singh | Ahmedabad
Gaurav | Joshi | Surat
Meera | Thakur | Delhi
Siddharth | Shaikh | Pune
Amit | Sinha | Pune
(5 rows)Calculated columns and aliases
You can calculate new values in the SELECT list. AS gives the result column a readable name, called an alias. Here we add 18% GST to each price.
SELECT product_name,
price,
ROUND(price * 0.18, 2) AS gst,
ROUND(price * 1.18, 2) AS price_with_gst
FROM products
LIMIT 5;Output:
product_name | price | gst | price_with_gst
--------------------------+-------+----------+---------------
Lenovo Laptop 14" Classic | 74799 | 13463.82 | 88262.82
Noise Smartwatch Pro 30 | 6099 | 1097.82 | 7196.82
Apple Fitness Band Air | 49999 | 8999.82 | 58998.82
Biba Sneakers X | 3699 | 665.82 | 4364.82
Lakme Moisturiser Classic | 269 | 48.42 | 317.42
(5 rows)Join text columns together
The || operator joins strings. This builds a full name from two columns.
SELECT first_name || ' ' || last_name AS full_name,
city
FROM customers
LIMIT 5;Output:
full_name | city
-----------------+----------
Anjali Singh | Ahmedabad
Gaurav Joshi | Surat
Meera Thakur | Delhi
Siddharth Shaikh | Pune
Amit Sinha | Pune
(5 rows)Other databases: MySQL uses CONCAT(first_name, ' ', last_name). SQL Server accepts + or CONCAT(). PostgreSQL supports both || and CONCAT().
SQL WHERE clause: filter rows
WHERE keeps only the rows that match a condition. It runs before grouping and sorting, so it is also the cheapest place to cut down your data.
Compare values with =, >, <, >= and <>
Find every product that costs more than one lakh rupees.
SELECT product_name, brand, price
FROM products
WHERE price > 100000
ORDER BY price DESC;Output:
product_name | brand | price
---------------------------+--------+-------
Acer Gaming Laptop X | Acer | 188299
Lenovo Laptop 15.6" X | Lenovo | 185799
Apple Ultrabook Plus | Apple | 182699
Acer Gaming Laptop 30 | Acer | 175499
Lenovo Laptop 15.6" 2.0 | Lenovo | 167199
Apple Laptop 15.6" Classic | Apple | 165399
HP Gaming Laptop Neo | HP | 158999
Dell Gaming Laptop X | Dell | 148799
Acer Laptop 15.6" Air | Acer | 148399
Lenovo Gaming Laptop 60 | Lenovo | 147599
Dell Ultrabook 2.0 | Dell | 138699
Asus Laptop 15.6" Air | Asus | 137699
... 20 rows in totalCombine conditions with AND and OR
AND needs both conditions to be true, OR needs at least one. When you mix them, use brackets: without them, AND is evaluated first and you can get rows you did not want.
SELECT product_name, category_id, rating
FROM products
WHERE (category_id = 1 OR category_id = 2)
AND rating >= 4.7;Output:
product_name | category_id | rating
-----------------------+-------------+-------
Vivo Smartphone 5G 2.0 | 1 | 4.7
Vivo Phone Pro X | 1 | 4.7
Asus Gaming Laptop 70 | 2 | 4.7
Samsung Phone Pro 70 | 1 | 4.7
Lenovo Laptop 15.6" X | 2 | 4.7
Samsung Phone Max 2.0 | 1 | 4.8
Samsung Phone Lite X | 1 | 4.7
(7 rows)Match a list of values with IN
IN is a shorter way to write several OR conditions on the same column.
SELECT order_id, order_date, status, total_amount
FROM orders
WHERE status IN ('Cancelled', 'Returned')
LIMIT 5;Output:
order_id | order_date | status | total_amount
---------+------------+-----------+-------------
27 | 2023-01-05 | Returned | 277597
30 | 2023-01-06 | Cancelled | 10755
43 | 2023-01-07 | Returned | 80926
47 | 2023-01-08 | Returned | 25550
54 | 2023-01-08 | Returned | 4718
(5 rows)Filter a range with BETWEEN
BETWEEN includes both ends. This counts the orders placed in November 2025, the festive month.
SELECT COUNT(*) AS november_orders
FROM orders
WHERE order_date BETWEEN '2025-11-01' AND '2025-11-30';Output:
november_orders
---------------
408
(1 row)Other databases: In this database dates are stored as text in the YYYY-MM-DD format, so comparing them as text works. In MySQL, PostgreSQL and SQL Server, a DATETIME or TIMESTAMP column with a time part needs order_date < '2025-12-01' as the upper bound, or you miss orders placed on 30 November after midnight.
Search text patterns with LIKE
% matches any number of characters and _ matches exactly one. This finds every pair of earbuds.
SELECT product_name, price
FROM products
WHERE product_name LIKE '%Earbuds%'
ORDER BY price
LIMIT 5;Output:
product_name | price
-----------------------------+------
Noise Wireless Earbuds Plus | 769
OnePlus Wireless Earbuds Air | 1099
Sony Wireless Earbuds X | 1599
OnePlus Wireless Earbuds 2.0 | 3299
boAt Wireless Earbuds Plus | 4299
(5 rows)Other databases: SQLite and MySQL (with its default collation) ignore case in LIKE. PostgreSQL is case-sensitive, so use ILIKE there for a case-insensitive search.
Find missing values with IS NULL
NULL means "no value". You cannot test it with = NULL, because any comparison with NULL is unknown, never true. Use IS NULL or IS NOT NULL.
SELECT COUNT(*) AS customers_without_phone
FROM customers
WHERE phone IS NULL;Output:
customers_without_phone
-----------------------
271
(1 row)Exclude values with NOT IN and NOT LIKE
Put NOT in front of IN, LIKE or BETWEEN to flip the condition.
SELECT first_name, last_name, email
FROM customers
WHERE city NOT IN ('Mumbai', 'Delhi', 'Bengaluru')
AND first_name NOT LIKE 'A%'
LIMIT 5;Output:
first_name | last_name | email
-----------+-----------+------------------------------
Gaurav | Joshi | ga**********@*****le.net
Siddharth | Shaikh | si**************@*****le.com
Janvi | Mukherjee | ja*************@*****le.net
Muskan | Yadav | mu**********@**********le.com
Khushi | Reddy | kh**********@*****le.com
(5 rows)ORDER BY and LIMIT: sort and pick the top rows
Rows in a table have no guaranteed order. If the order matters, say so with ORDER BY. ASC (the default) sorts from small to large, DESC from large to small.
Top 5 most expensive products
Sort by price from high to low, then keep the first five rows.
SELECT product_name, brand, price
FROM products
ORDER BY price DESC
LIMIT 5;Output:
product_name | brand | price
------------------------+--------+-------
Acer Gaming Laptop X | Acer | 188299
Lenovo Laptop 15.6" X | Lenovo | 185799
Apple Ultrabook Plus | Apple | 182699
Acer Gaming Laptop 30 | Acer | 175499
Lenovo Laptop 15.6" 2.0 | Lenovo | 167199
(5 rows)Other databases: SQL Server writes this as SELECT TOP 5 .... Oracle and standard SQL use FETCH FIRST 5 ROWS ONLY at the end. MySQL and PostgreSQL use LIMIT like SQLite.
Sort by more than one column
Rows are sorted by the first column, and ties are broken by the next one. Here, customers are grouped by city, newest sign-ups first within each city.
SELECT first_name, city, signup_date
FROM customers
ORDER BY city ASC, signup_date DESC
LIMIT 6;Output:
first_name | city | signup_date
-----------+-----------+------------
Karan | Ahmedabad | 2025-11-26
Simran | Ahmedabad | 2025-11-17
Janvi | Ahmedabad | 2025-11-09
Varun | Ahmedabad | 2025-10-18
Maria | Ahmedabad | 2025-10-04
Trisha | Ahmedabad | 2025-10-01
(6 rows)Pagination with LIMIT and OFFSET
OFFSET skips rows. With 10 rows per page, page 3 skips the first 20 rows. This is how most websites show "page 3 of 200".
SELECT order_id, order_date, total_amount
FROM orders
ORDER BY order_id
LIMIT 10 OFFSET 20;Output:
order_id | order_date | total_amount
---------+------------+-------------
21 | 2023-01-04 | 2398
22 | 2023-01-05 | 1999
23 | 2023-01-05 | 79853
24 | 2023-01-05 | 7599
25 | 2023-01-05 | 98937
26 | 2023-01-05 | 4399
27 | 2023-01-05 | 277597
28 | 2023-01-05 | 279
29 | 2023-01-05 | 12064
30 | 2023-01-06 | 10755
(10 rows)Other databases: SQL Server: ORDER BY order_id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY. MySQL also accepts the short form LIMIT 20, 10.
DISTINCT: remove duplicate rows
List each value only once
DISTINCT removes duplicate rows from the result. Two thousand customers live in only 13 cities.
SELECT DISTINCT city
FROM customers
ORDER BY city;Output:
city
---------
Ahmedabad
Bengaluru
Chennai
Delhi
Hyderabad
Indore
Jaipur
Kochi
Kolkata
Lucknow
Mumbai
Pune
... 13 rows in totalCount distinct values
Ten thousand orders, but how many different customers placed them? COUNT(DISTINCT ...) answers that.
SELECT COUNT(*) AS total_orders,
COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;Output:
total_orders | unique_customers
-------------+-----------------
10000 | 1583
(1 row)SQL aggregate functions: COUNT, SUM, AVG, MIN, MAX
Aggregate functions turn many rows into one value. On their own they summarise the whole table; with GROUP BY (next section) they summarise each group.
COUNT(*) vs COUNT(column)
COUNT(*) counts rows. COUNT(phone) counts only rows where phone is not NULL. The difference is the number of missing phone numbers.
SELECT COUNT(*) AS all_customers,
COUNT(phone) AS with_phone
FROM customers;Output:
all_customers | with_phone
--------------+-----------
2000 | 1729
(1 row)SUM, AVG, MIN and MAX together
Revenue figures for delivered orders only. ROUND keeps the average readable.
SELECT COUNT(*) AS orders,
SUM(total_amount) AS revenue,
ROUND(AVG(total_amount), 2) AS avg_order_value,
MIN(total_amount) AS smallest,
MAX(total_amount) AS largest
FROM orders
WHERE status = 'Delivered';Output:
orders | revenue | avg_order_value | smallest | largest
-------+-----------+-----------------+----------+--------
8607 | 366811067 | 42617.76 | 39 | 636365
(1 row)GROUP BY and HAVING
GROUP BY puts rows with the same value into one group, and the aggregate functions then run once per group. HAVING filters those groups, the way WHERE filters rows.
Count orders by status
One row per status, with the number of orders in each.
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC;Output:
status | orders
----------+-------
Delivered | 8607
Cancelled | 754
Returned | 584
Shipped | 42
Pending | 13
(5 rows)Group by two columns
Customers by state and gender. Every column in the SELECT list must either be in GROUP BY or be inside an aggregate function.
SELECT state, gender, COUNT(*) AS customers
FROM customers
GROUP BY state, gender
ORDER BY state, gender
LIMIT 6;Output:
state | gender | customers
----------+--------+----------
Delhi | F | 142
Delhi | M | 123
Gujarat | F | 118
Gujarat | M | 132
Karnataka | F | 119
Karnataka | M | 133
(6 rows)Other databases: SQLite and older MySQL versions let you select a column that is not grouped and quietly pick a value from the group. PostgreSQL, SQL Server and MySQL 8 (with its default mode) reject that with an error, so always follow the rule above.
HAVING: keep only the groups you want
Customers who placed more than 40 orders. You cannot use WHERE COUNT(*) > 40, because WHERE runs before the groups exist.
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 40
ORDER BY orders DESC;Output:
customer_id | orders
------------+-------
1157 | 56
292 | 55
1401 | 53
444 | 51
630 | 48
1168 | 47
636 | 43
(7 rows)WHERE and HAVING in the same query
WHERE first removes rows that are not delivered, then GROUP BY forms one group per product, and HAVING keeps products that sold at least 250 units.
SELECT oi.product_id, SUM(oi.quantity) AS units_sold
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
WHERE o.status = 'Delivered'
GROUP BY oi.product_id
HAVING SUM(oi.quantity) >= 250
ORDER BY units_sold DESC;Output:
product_id | units_sold
-----------+-----------
81 | 552
298 | 431
168 | 389
95 | 310
78 | 294
184 | 287
297 | 278
100 | 274
(8 rows)SQL queries on joins
A join combines rows from two tables using a column they share, usually a primary key on one side and a foreign key on the other. In our store, orders.customer_id points to customers.customer_id. The visualiser below shows exactly which rows each join type keeps.
SQL JOIN visualiser
Two tiny tables: four customers and four orders. Order 104 belongs to customer 5, who is not in the customers table. Pick a join to see which rows it keeps.
INNER JOIN: only matching rows
Each order with the name of the customer who placed it. Table aliases (o and c) keep the query short.
SELECT o.order_id, o.order_date, c.first_name, c.city, o.total_amount
FROM orders o
INNER JOIN customers c ON c.customer_id = o.customer_id
ORDER BY o.order_id DESC
LIMIT 5;Output:
order_id | order_date | first_name | city | total_amount
---------+------------+------------+-----------+-------------
10000 | 2025-12-31 | Komal | Surat | 400697
9999 | 2025-12-31 | Divya | Chennai | 864
9998 | 2025-12-31 | Aditi | Lucknow | 69643
9997 | 2025-12-31 | Meera | Pune | 134486
9996 | 2025-12-31 | Neel | Hyderabad | 1399
(5 rows)Join three tables
Revenue by category needs three tables: order_items for the money, products to find the category, and categories for its name.
SELECT cat.category_name,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
GROUP BY cat.category_name
ORDER BY revenue DESC;Output:
category_name | revenue
---------------+----------
Laptops | 227871196
Mobiles | 103910125
Audio | 30651925
Wearables | 30080045
Home & Kitchen | 12309722
Sports | 9866883
Fashion | 7996042
Books | 2207691
Beauty | 2136289
Groceries | 912852
(10 rows)LEFT JOIN: keep every row from the left table
A LEFT JOIN keeps all categories, even one with no products. For that category the product columns are NULL, so COUNT(p.product_id) gives 0.
SELECT cat.category_name, COUNT(p.product_id) AS products
FROM categories cat
LEFT JOIN products p ON p.category_id = cat.category_id
GROUP BY cat.category_name
ORDER BY products;Output:
category_name | products
---------------+---------
Toys | 0
Beauty | 20
Wearables | 21
Home & Kitchen | 24
Groceries | 29
Mobiles | 30
Laptops | 32
Books | 33
Sports | 35
Audio | 37
Fashion | 39
(11 rows)LEFT JOIN with IS NULL: find rows with no match
Customers who signed up but never ordered. This pattern is called an anti-join, and you will use it often.
SELECT c.customer_id, c.first_name, c.signup_date
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL
ORDER BY c.signup_date
LIMIT 5;Output:
customer_id | first_name | signup_date
------------+------------+------------
1259 | Payal | 2022-01-06
326 | Bhavna | 2022-01-07
1781 | Dhruv | 2022-02-11
816 | Rakesh | 2022-02-14
694 | Manish | 2022-02-20
(5 rows)RIGHT JOIN
A RIGHT JOIN keeps every row from the right table instead. It is the same as a LEFT JOIN with the tables swapped, which is why most people just write the left join. Here, every order with its payment method, including orders with no payment yet.
SELECT o.order_id, o.status, p.method
FROM payments p
RIGHT JOIN orders o ON o.order_id = p.order_id
WHERE o.status = 'Pending'
ORDER BY o.order_id
LIMIT 6;Output:
order_id | status | method
---------+---------+-------
9972 | Pending | NULL
9976 | Pending | NULL
9977 | Pending | NULL
9978 | Pending | NULL
9980 | Pending | NULL
9984 | Pending | Card
(6 rows)Other databases: SQLite added RIGHT JOIN and FULL OUTER JOIN in version 3.39. MySQL has RIGHT JOIN but no FULL OUTER JOIN; there you combine a left join and a right join with UNION.
SELF JOIN: join a table to itself
Each employee row stores its manager's emp_id. Joining employees to itself under two aliases gives each person next to their manager. The CEO has no manager, so a LEFT JOIN keeps that row.
SELECT e.name AS employee, e.job_title, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.emp_id = e.manager_id
ORDER BY e.emp_id
LIMIT 6;Output:
employee | job_title | manager
---------------+--------------------------+--------------
Anirudh Mehra | CEO | NULL
Rakesh Naidu | Head of Operations | Anirudh Mehra
Dhruv Ghosh | Head of Technology | Anirudh Mehra
Kavya Gupta | Head of Marketing | Anirudh Mehra
Arjun Kulkarni | Head of Customer Support | Anirudh Mehra
Rahul Shaikh | Head of Finance | Anirudh Mehra
(6 rows)CROSS JOIN: every combination
A CROSS JOIN pairs every row of one table with every row of the other. 11 categories times 5 payment methods gives 55 rows. Useful for building a grid you will fill in later, dangerous on two big tables.
SELECT COUNT(*) AS combinations
FROM categories
CROSS JOIN (SELECT DISTINCT method FROM payments) AS m;Output:
combinations
------------
55
(1 row)SQL subqueries
A subquery is a query inside another query, written in brackets. It can return one value, a list of values or a whole table.
Subquery that returns one value
Products priced above the average price. The inner query runs first and returns a single number.
SELECT product_name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price
LIMIT 5;Output:
product_name | price
---------------------------+------
Noise Wireless Earbuds Air | 22699
Samsung Phone Pro 50 | 22799
JBL Neckband 2.0 | 23499
JBL Neckband 90 | 24499
boAt Headphones Plus | 24899
(5 rows)Subquery with IN
Customers from Surat who placed at least one order worth more than three lakh rupees.
SELECT first_name, last_name
FROM customers
WHERE city = 'Surat'
AND customer_id IN (SELECT customer_id
FROM orders
WHERE total_amount > 300000);Output:
first_name | last_name
-----------+-----------
Anjali | Jain
Tanvi | Malhotra
Chirag | Jain
Komal | Jain
Nikhil | Chatterjee
Sanjay | Tiwari
(6 rows)Correlated subquery
The most expensive product in each category. The inner query refers to p.category_id from the outer query, so it runs once for each outer row.
SELECT p.category_id, p.product_name, p.price
FROM products p
WHERE p.price = (SELECT MAX(p2.price)
FROM products p2
WHERE p2.category_id = p.category_id)
ORDER BY p.category_id;Output:
category_id | product_name | price
------------+----------------------------------+-------
1 | Vivo Smartphone 5G | 124799
2 | Acer Gaming Laptop X | 188299
3 | boAt Neckband Air | 28099
4 | Apple Fitness Band Air | 49999
5 | Biba Kurta 80 | 4999
6 | Philips Pressure Cooker | 14799
7 | Penguin Programming Book Classic | 1399
8 | Himalaya Face Wash Classic | 2499
9 | Nivia Football 60 | 9899
10 | Aashirvaad Tea 500g Neo | 959
(10 rows)NOT EXISTS: products that never sold
EXISTS is true when the subquery returns at least one row. NOT EXISTS finds products with no row in order_items, and unlike NOT IN, it is not confused by NULLs.
SELECT p.product_id, p.product_name, p.stock
FROM products p
WHERE NOT EXISTS (SELECT 1
FROM order_items oi
WHERE oi.product_id = p.product_id)
ORDER BY p.product_id;Output:
product_id | product_name | stock
-----------+-------------------------------+------
9 | Fire-Boltt Smartwatch Pro 2.0 | 288
26 | Puma Kurta | 0
55 | Cosco Dumbbell Set X | 350
64 | OnePlus Neckband 2.0 | 0
88 | Samsung Smartwatch Pro Air | 0
135 | Nivia Football 60 | 351
147 | Cosco Dumbbell Set 60 | 293
160 | Biba Jeans 2.0 | 200
171 | boAt Wireless Earbuds Air | 0
215 | Rupa Novel X | 427
248 | boAt Headphones X | 14
262 | Puma Jeans Air | 59
(12 rows)Subquery in FROM (a derived table)
First count orders per customer, then average those counts. The inner query must have an alias.
SELECT ROUND(AVG(order_count), 2) AS avg_orders_per_customer,
MAX(order_count) AS most_orders
FROM (SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id) AS per_customer;Output:
avg_orders_per_customer | most_orders
------------------------+------------
6.32 | 56
(1 row)CASE WHEN: if-else in SQL
Label rows with CASE
CASE checks conditions from top to bottom and returns the value of the first one that is true. ELSE catches the rest.
SELECT product_name, price,
CASE
WHEN price < 1000 THEN 'Budget'
WHEN price < 20000 THEN 'Mid-range'
ELSE 'Premium'
END AS price_band
FROM products
LIMIT 6;Output:
product_name | price | price_band
---------------------------+-------+-----------
Lenovo Laptop 14" Classic | 74799 | Premium
Noise Smartwatch Pro 30 | 6099 | Mid-range
Apple Fitness Band Air | 49999 | Premium
Biba Sneakers X | 3699 | Mid-range
Lakme Moisturiser Classic | 269 | Budget
Aashirvaad Basmati Rice 20 | 199 | Budget
(6 rows)Group by a CASE expression
The same bands, now counted.
SELECT CASE
WHEN price < 1000 THEN 'Budget'
WHEN price < 20000 THEN 'Mid-range'
ELSE 'Premium'
END AS price_band,
COUNT(*) AS products
FROM products
GROUP BY price_band
ORDER BY products DESC;Output:
price_band | products
-----------+---------
Mid-range | 141
Budget | 87
Premium | 72
(3 rows)Other databases: Grouping by an alias works in SQLite, MySQL and PostgreSQL. SQL Server needs you to repeat the whole CASE expression in GROUP BY.
Conditional aggregation: a pivot table
Put CASE inside SUM to count different things in one pass. This gives delivered, cancelled and returned orders per year as columns.
SELECT SUBSTR(order_date, 1, 4) AS year,
SUM(CASE WHEN status = 'Delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'Cancelled' THEN 1 ELSE 0 END) AS cancelled,
SUM(CASE WHEN status = 'Returned' THEN 1 ELSE 0 END) AS returned
FROM orders
GROUP BY year
ORDER BY year;Output:
year | delivered | cancelled | returned
-----+-----------+-----------+---------
2023 | 2584 | 225 | 199
2024 | 2977 | 269 | 180
2025 | 3046 | 260 | 205
(3 rows)Handling NULL: COALESCE and NULLIF
Replace NULL with a default
COALESCE returns its first argument that is not NULL.
SELECT first_name, COALESCE(phone, 'Not given') AS phone
FROM customers
WHERE customer_id BETWEEN 1 AND 6;Output:
first_name | phone
-----------+-----------
Anjali | 6412943214
Gaurav | 7328377485
Meera | 8980730465
Siddharth | 8547908454
Amit | Not given
Janvi | 8132076536
(6 rows)Other databases: MySQL also has IFNULL(phone, ...), SQL Server has ISNULL(phone, ...) and Oracle has NVL. COALESCE works in all of them.
Avoid division by zero with NULLIF
NULLIF(a, b) returns NULL when a equals b, and dividing by NULL gives NULL instead of an error. The Toys category has sold nothing, so its item count is 0.
SELECT cat.category_name,
COUNT(oi.item_id) AS items_sold,
ROUND(SUM(oi.quantity * oi.unit_price) / NULLIF(COUNT(oi.item_id), 0), 2) AS avg_item_value
FROM categories cat
LEFT JOIN products p ON p.category_id = cat.category_id
LEFT JOIN order_items oi ON oi.product_id = p.product_id
GROUP BY cat.category_name
ORDER BY items_sold
LIMIT 3;Output:
category_name | items_sold | avg_item_value
--------------+------------+---------------
Toys | 0 | NULL
Wearables | 1100 | 27345.5
Beauty | 1422 | 1502.31
(3 rows)Other databases: SQLite and MySQL return NULL when you divide by zero, but PostgreSQL and SQL Server stop with an error. NULLIF makes the query safe in all of them.
SQL string functions
UPPER, LOWER, LENGTH and SUBSTR
Common text functions in one query.
SELECT first_name,
UPPER(first_name) AS upper_name,
LENGTH(first_name) AS letters,
SUBSTR(first_name, 1, 3) AS first_three
FROM customers
LIMIT 5;Output:
first_name | upper_name | letters | first_three
-----------+------------+---------+------------
Anjali | ANJALI | 6 | Anj
Gaurav | GAURAV | 6 | Gau
Meera | MEERA | 5 | Mee
Siddharth | SIDDHARTH | 9 | Sid
Amit | AMIT | 4 | Ami
(5 rows)Other databases: SQL Server uses LEN() and SUBSTRING(). In MySQL, LENGTH() counts bytes; use CHAR_LENGTH() for letters.
Extract part of a string
Everything after the @ in an email address is the domain. INSTR finds the position of the @.
SELECT email,
SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM customers
LIMIT 3;Output:
email | domain
---------------------------------+-----------------
aa**********@*****le.com | example.com
aa*******@**********le.com | mail.example.com
aa*************@**********le.com | mail.example.com
(3 rows)Other databases: MySQL: SUBSTRING_INDEX(email, '@', -1). PostgreSQL: SPLIT_PART(email, '@', 2). SQL Server: SUBSTRING(email, CHARINDEX('@', email) + 1, 100).
REPLACE and TRIM
REPLACE swaps text, TRIM removes spaces from both ends.
SELECT product_name,
REPLACE(product_name, 'Smartwatch', 'Watch') AS short_name,
TRIM(' Code and Debug ') AS trimmed
FROM products
WHERE product_name LIKE '%Smartwatch%'
LIMIT 3;Output:
product_name | short_name | trimmed
------------------------------+--------------------------+---------------
Noise Smartwatch Pro 30 | Noise Watch Pro 30 | Code and Debug
Fire-Boltt Smartwatch Pro 2.0 | Fire-Boltt Watch Pro 2.0 | Code and Debug
Apple Smartwatch 60 | Apple Watch 60 | Code and Debug
(3 rows)SQL date queries
Date functions differ more between databases than anything else in SQL. The examples use SQLite's strftime and julianday; the notes show the MySQL, PostgreSQL and SQL Server versions.
Orders and revenue per year
strftime('%Y', order_date) pulls the year out of a date.
SELECT strftime('%Y', order_date) AS year,
COUNT(*) AS orders,
ROUND(SUM(total_amount)) AS revenue
FROM orders
GROUP BY year
ORDER BY year;Output:
year | orders | revenue
-----+--------+----------
2023 | 3008 | 126341559
2024 | 3426 | 150010691
2025 | 3566 | 151590520
(3 rows)Other databases: MySQL and SQL Server: YEAR(order_date). PostgreSQL: EXTRACT(YEAR FROM order_date).
Monthly revenue for one year
'%Y-%m' gives year and month, which sorts correctly as text.
SELECT strftime('%Y-%m', order_date) AS month,
COUNT(*) AS orders,
ROUND(SUM(total_amount)) AS revenue
FROM orders
WHERE order_date >= '2025-01-01' AND status = 'Delivered'
GROUP BY month
ORDER BY month;Output:
month | orders | revenue
--------+--------+---------
2025-01 | 246 | 8799760
2025-02 | 198 | 7248543
2025-03 | 236 | 10939282
2025-04 | 197 | 8455654
2025-05 | 250 | 9182802
2025-06 | 233 | 10257922
2025-07 | 249 | 11060519
2025-08 | 255 | 11204911
2025-09 | 232 | 10656113
2025-10 | 395 | 16074697
2025-11 | 355 | 14927710
2025-12 | 200 | 9129452
(12 rows)Other databases: MySQL: DATE_FORMAT(order_date, '%Y-%m'). PostgreSQL: TO_CHAR(order_date, 'YYYY-MM'). SQL Server: FORMAT(order_date, 'yyyy-MM').
Difference between two dates
How many days after the order did cash-on-delivery customers pay?
SELECT julianday(p.paid_on) - julianday(o.order_date) AS days_to_pay,
COUNT(*) AS payments
FROM payments p
JOIN orders o ON o.order_id = p.order_id
WHERE p.method = 'COD'
GROUP BY days_to_pay
ORDER BY days_to_pay;Output:
days_to_pay | payments
------------+---------
2 | 227
3 | 221
4 | 238
5 | 239
6 | 227
7 | 244
(6 rows)Other databases: MySQL: DATEDIFF(p.paid_on, o.order_date). PostgreSQL: p.paid_on - o.order_date for DATE columns. SQL Server: DATEDIFF(day, o.order_date, p.paid_on).
Add days to a date
The expected delivery date, five days after the order.
SELECT order_id, order_date,
date(order_date, '+5 days') AS expected_delivery
FROM orders
WHERE status = 'Shipped'
LIMIT 3;Output:
order_id | order_date | expected_delivery
---------+------------+------------------
9917 | 2025-12-22 | 2025-12-27
9918 | 2025-12-22 | 2025-12-27
9919 | 2025-12-22 | 2025-12-27
(3 rows)Other databases: MySQL: DATE_ADD(order_date, INTERVAL 5 DAY). PostgreSQL: order_date + INTERVAL '5 days'. SQL Server: DATEADD(day, 5, order_date).
Window functions: ROW_NUMBER, RANK, running totals
A window function calculates a value across a set of related rows but, unlike GROUP BY, keeps every row. The OVER() part defines the window: PARTITION BY splits rows into groups and ORDER BY sets the order inside each group.
ROW_NUMBER: top 2 products in each category
Number the products in each category from most to least expensive, then keep numbers 1 and 2. This "top N per group" query comes up often in SQL interviews.
SELECT category_id, product_name, price
FROM (SELECT category_id, product_name, price,
ROW_NUMBER() OVER (PARTITION BY category_id
ORDER BY price DESC) AS rn
FROM products) AS ranked
WHERE rn <= 2
ORDER BY category_id, rn
LIMIT 6;Output:
category_id | product_name | price
------------+--------------------------+-------
1 | Vivo Smartphone 5G | 124799
1 | Realme Phone Max Air | 119299
2 | Acer Gaming Laptop X | 188299
2 | Lenovo Laptop 15.6" X | 185799
3 | boAt Neckband Air | 28099
3 | OnePlus Wireless Earbuds | 27499
(6 rows)RANK vs DENSE_RANK vs ROW_NUMBER
With a tie, ROW_NUMBER still gives different numbers, RANK gives the same number and then skips, and DENSE_RANK gives the same number without a gap.
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
WHERE department = 'Technology';Output:
name | salary | row_num | rnk | dense_rnk
---------------+--------+---------+-----+----------
Deepak Dubey | 330000 | 1 | 1 | 1
Dhruv Ghosh | 315000 | 2 | 2 | 2
Arjun Malhotra | 100000 | 3 | 3 | 3
Bhavna Thakur | 80000 | 4 | 4 | 4
Pranav Thakur | 75000 | 5 | 5 | 5
Fatima Sharma | 70000 | 6 | 6 | 6
Arnav Reddy | 45000 | 7 | 7 | 7
Trisha Desai | 45000 | 8 | 7 | 7
Bhavna Rao | 45000 | 9 | 7 | 7
(9 rows)Running total with SUM() OVER
Revenue for each month of 2025 and the total so far. The inner query makes one row per month; the window adds them up in date order.
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS running_total
FROM (SELECT strftime('%Y-%m', order_date) AS month,
ROUND(SUM(total_amount)) AS revenue
FROM orders
WHERE order_date LIKE '2025%' AND status = 'Delivered'
GROUP BY month) AS m
ORDER BY month
LIMIT 6;Output:
month | revenue | running_total
--------+----------+--------------
2025-01 | 8799760 | 8799760
2025-02 | 7248543 | 16048303
2025-03 | 10939282 | 26987585
2025-04 | 8455654 | 35443239
2025-05 | 9182802 | 44626041
2025-06 | 10257922 | 54883963
(6 rows)LAG: compare with the previous row
LAG(revenue) returns the value from the previous row in the window, so you can work out growth month over month.
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS previous,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ LAG(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM (SELECT strftime('%Y-%m', order_date) AS month,
ROUND(SUM(total_amount)) AS revenue
FROM orders
WHERE order_date LIKE '2025%' AND status = 'Delivered'
GROUP BY month) AS m
ORDER BY month
LIMIT 6;Output:
month | revenue | previous | growth_pct
--------+----------+----------+-----------
2025-01 | 8799760 | NULL | NULL
2025-02 | 7248543 | 8799760 | -17.6
2025-03 | 10939282 | 7248543 | 50.9
2025-04 | 8455654 | 10939282 | -22.7
2025-05 | 9182802 | 8455654 | 8.6
2025-06 | 10257922 | 9182802 | 11.7
(6 rows)Common table expressions (WITH)
A CTE makes a long query readable
WITH name AS (...) defines a temporary named result you can use like a table in the main query. Here: each customer's total spend, then the top five spenders with their city.
WITH spend AS (
SELECT customer_id, SUM(total_amount) AS total_spent, COUNT(*) AS orders
FROM orders
WHERE status = 'Delivered'
GROUP BY customer_id
)
SELECT c.first_name, c.last_name, c.city, s.orders, s.total_spent
FROM spend s
JOIN customers c ON c.customer_id = s.customer_id
ORDER BY s.total_spent DESC
LIMIT 5;Output:
first_name | last_name | city | orders | total_spent
-----------+-----------+-----------+--------+------------
Arnav | Dubey | Bengaluru | 45 | 2523668
Aditi | Bansal | Chennai | 33 | 2270017
Aditi | Rao | Delhi | 27 | 2226186
Hetal | Yadav | Chennai | 35 | 1937163
Ritesh | Dubey | Jaipur | 34 | 1783487
(5 rows)Recursive CTE: walk an org chart
A recursive CTE has a starting query and a part that refers to the CTE itself. This one starts at the CEO and goes down one reporting level at a time.
WITH RECURSIVE chain AS (
SELECT emp_id, name, job_title, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.emp_id, e.name, e.job_title, chain.level + 1
FROM employees e
JOIN chain ON e.manager_id = chain.emp_id
)
SELECT level, COUNT(*) AS people
FROM chain
GROUP BY level
ORDER BY level;Output:
level | people
------+-------
1 | 1
2 | 5
3 | 5
4 | 28
(4 rows)Other databases: SQL Server and Oracle write WITH without the word RECURSIVE.
UNION, INTERSECT and EXCEPT
Set operators stack the results of two queries on top of each other. Both queries must return the same number of columns with compatible types.
UNION vs UNION ALL
UNION removes duplicates, UNION ALL keeps them and is faster. Every city where we have either customers or staff:
SELECT city FROM customers
UNION
SELECT city FROM employees
ORDER BY city;Output:
city
---------
Ahmedabad
Bengaluru
Chennai
Delhi
Hyderabad
Indore
Jaipur
Kochi
Kolkata
Lucknow
Mumbai
Pune
... 13 rows in totalINTERSECT and EXCEPT
INTERSECT keeps rows found in both results, EXCEPT keeps rows from the first that are not in the second. Customer IDs that ordered in 2023 but not in 2025:
SELECT COUNT(*) AS lapsed_customers
FROM (SELECT customer_id FROM orders WHERE order_date LIKE '2023%'
EXCEPT
SELECT customer_id FROM orders WHERE order_date LIKE '2025%') AS x;Output:
lapsed_customers
----------------
126
(1 row)Other databases: Oracle calls EXCEPT MINUS. MySQL supports INTERSECT and EXCEPT from version 8.0.31.
INSERT, UPDATE and DELETE queries
These queries change data. When you press Run in the boxes below, the change happens on a fresh copy of the database, so you can try them as often as you like. In the main playground, use "Reset database" to undo your changes.
INSERT a new row
List the columns, then the values in the same order. A SELECT after it shows the result.
INSERT INTO categories (category_id, category_name)
VALUES (12, 'Stationery');
SELECT * FROM categories WHERE category_id >= 10;Output:
category_id | category_name
------------+--------------
10 | Groceries
11 | Toys
12 | Stationery
(3 rows)INSERT several rows at once
One INSERT with several value lists is much faster than many single inserts.
INSERT INTO products (product_id, product_name, category_id, brand, price, stock, rating, launch_date)
VALUES (301, 'Funskool Building Blocks', 11, 'Funskool', 899, 120, 4.4, '2025-06-01'),
(302, 'Funskool Jigsaw Puzzle 500', 11, 'Funskool', 499, 300, 4.6, '2025-06-01');
SELECT product_id, product_name, price FROM products WHERE product_id > 300;Output:
product_id | product_name | price
-----------+----------------------------+------
301 | Funskool Building Blocks | 899
302 | Funskool Jigsaw Puzzle 500 | 499
(2 rows)UPDATE rows that match a condition
A 10% discount on every Audio product. Always write the WHERE first: an UPDATE without it changes every row in the table.
UPDATE products
SET price = ROUND(price * 0.9)
WHERE category_id = 3;
SELECT product_name, price FROM products WHERE category_id = 3 LIMIT 3;Output:
product_name | price
--------------------+------
JBL Neckband 2.0 | 21149
boAt Headphones Air | 8189
boAt Headphones 60 | 8819
(3 rows)DELETE rows
Remove cancelled orders from 2023, together with their items, so nothing is left pointing at a missing order. The child rows go first.
DELETE FROM order_items
WHERE order_id IN (SELECT order_id FROM orders
WHERE status = 'Cancelled' AND order_date < '2024-01-01');
DELETE FROM payments
WHERE order_id IN (SELECT order_id FROM orders
WHERE status = 'Cancelled' AND order_date < '2024-01-01');
DELETE FROM orders
WHERE status = 'Cancelled' AND order_date < '2024-01-01';
SELECT COUNT(*) AS orders_left FROM orders;Output:
orders_left
-----------
9775
(1 row)Other databases: In production, wrap changes like this in a transaction (BEGIN ... COMMIT) so you can ROLLBACK if something looks wrong.
CREATE TABLE, ALTER, INDEX and VIEW
CREATE TABLE with constraints
Constraints let the database reject bad data: PRIMARY KEY, NOT NULL, UNIQUE, CHECK and REFERENCES (a foreign key).
CREATE TABLE reviews (
review_id INTEGER PRIMARY KEY,
product_id INTEGER NOT NULL REFERENCES products(product_id),
customer_id INTEGER NOT NULL REFERENCES customers(customer_id),
stars INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5),
comment TEXT,
created_on TEXT NOT NULL DEFAULT '2025-12-31',
UNIQUE (product_id, customer_id)
);
INSERT INTO reviews (product_id, customer_id, stars, comment)
VALUES (1, 1, 5, 'Fast delivery, great laptop');
SELECT * FROM reviews;Output:
review_id | product_id | customer_id | stars | comment | created_on
----------+------------+-------------+-------+-----------------------------+-----------
1 | 1 | 1 | 5 | Fast delivery, great laptop | 2025-12-31
(1 row)Other databases: MySQL uses AUTO_INCREMENT and PostgreSQL uses GENERATED ALWAYS AS IDENTITY (or SERIAL) for an ID that fills itself in. In SQLite, an INTEGER PRIMARY KEY does that on its own.
ALTER TABLE: add a column
Add a column to an existing table. Old rows get the default value.
ALTER TABLE customers ADD COLUMN is_prime INTEGER DEFAULT 0;
UPDATE customers SET is_prime = 1 WHERE customer_id IN (SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) >= 15);
SELECT is_prime, COUNT(*) AS customers FROM customers GROUP BY is_prime;Output:
is_prime | customers
---------+----------
0 | 1882
1 | 118
(2 rows)CREATE INDEX: make lookups fast
An index works like the index at the back of a book. Without one, finding all orders of one customer means reading all 10,000 rows. EXPLAIN QUERY PLAN shows whether SQLite uses the index: "SEARCH ... USING INDEX" means yes, "SCAN orders" would mean it reads the whole table.
CREATE INDEX idx_orders_customer ON orders(customer_id);
EXPLAIN QUERY PLAN
SELECT * FROM orders WHERE customer_id = 42;Output:
QUERY PLAN
`--SEARCH orders USING INDEX idx_orders_customer (customer_id=?)Other databases: MySQL and PostgreSQL use EXPLAIN (or EXPLAIN ANALYZE) for the same purpose.
CREATE VIEW: save a query under a name
A view is a stored query you can select from like a table. It does not copy data.
CREATE VIEW delivered_revenue AS
SELECT customer_id, SUM(total_amount) AS revenue
FROM orders
WHERE status = 'Delivered'
GROUP BY customer_id;
SELECT COUNT(*) AS customers, ROUND(AVG(revenue)) AS avg_revenue
FROM delivered_revenue;Output:
customers | avg_revenue
----------+------------
1544 | 237572
(1 row)In what order does SQL run a query?
You write SELECT first, but the database runs it almost last. Knowing the real order explains most beginner errors, for example why WHERE cannot use a column alias or an aggregate, while ORDER BY can.
| Step | Clause | What happens |
|---|---|---|
| 1 | FROM and JOIN | Pick the tables and combine them |
| 2 | WHERE | Remove rows that fail the condition |
| 3 | GROUP BY | Put the remaining rows into groups |
| 4 | HAVING | Remove groups that fail the condition |
| 5 | SELECT | Work out the columns, including window functions and aliases |
| 6 | DISTINCT | Remove duplicate rows |
| 7 | ORDER BY | Sort the result (aliases can be used here) |
| 8 | LIMIT / OFFSET | Keep only the rows you asked for |
SQL queries for practice: 50 questions with answers
Each question below has an editor: type your query and press Run and check. The page runs it on a fresh copy of the store database and compares your result with the correct answer. Column names and column order do not matter, only the data. If something is off, it tells you what: the wrong number of rows, a column with wrong values, or the wrong sort order. Your queries and your "Done" progress are saved in this browser.
Start with the easy ones. Every question can be answered with what this page teaches, and the "Show answer" link under each one has a model solution.
Your progress
Easy SQL practice questions
Basic SQL queries on one table: filtering, sorting, counting and simple grouping.
1. List the name and price of every product made by the brand 'Apple'.
Show answer
SELECT product_name, price
FROM products
WHERE brand = 'Apple';2. Show the first and last name of every customer who lives in Surat.
Show answer
SELECT first_name, last_name
FROM customers
WHERE city = 'Surat';3. Which products are out of stock? Show their product names.
Show answer
SELECT product_name
FROM products
WHERE stock = 0;4. How many orders have the status 'Returned'?
Show answer
SELECT COUNT(*)
FROM orders
WHERE status = 'Returned';5. Show the 5 cheapest products with their name and price, cheapest first.
Show answer
SELECT product_name, price
FROM products
ORDER BY price
LIMIT 5;6. Show each city with its number of customers, the city with the most customers first.
Show answer
SELECT city, COUNT(*) AS customers
FROM customers
GROUP BY city
ORDER BY customers DESC;7. List the name and rating of products in the Books category (category_id = 7) rated 4.5 or higher.
Show answer
SELECT product_name, rating
FROM products
WHERE category_id = 7 AND rating >= 4.5;8. How many customers have a first name that starts with the letter S?
Show answer
SELECT COUNT(*)
FROM customers
WHERE first_name LIKE 'S%';9. Show the order ID and total amount of every order placed on 25 December 2025.
Show answer
SELECT order_id, total_amount
FROM orders
WHERE order_date = '2025-12-25';10. List every brand that sells laptops (category_id = 2), once each, in alphabetical order.
Show answer
SELECT DISTINCT brand
FROM products
WHERE category_id = 2
ORDER BY brand;11. What is the total number of units in stock across all products?
Show answer
SELECT SUM(stock)
FROM products;12. What is the average product rating, rounded to 2 decimal places?
Show answer
SELECT ROUND(AVG(rating), 2)
FROM products;13. List the names of products that have no rating yet.
Show answer
SELECT product_name
FROM products
WHERE rating IS NULL;14. How many customers signed up in 2025?
Show answer
SELECT COUNT(*)
FROM customers
WHERE signup_date BETWEEN '2025-01-01' AND '2025-12-31';15. List the name and salary of everyone in the Marketing department, highest salary first.
Show answer
SELECT name, salary
FROM employees
WHERE department = 'Marketing'
ORDER BY salary DESC;16. How many orders have a total amount between 50,000 and 60,000 (both included)?
Show answer
SELECT COUNT(*)
FROM orders
WHERE total_amount BETWEEN 50000 AND 60000;17. Show each payment method and how many payments used it.
Show answer
SELECT method, COUNT(*)
FROM payments
GROUP BY method;18. How many products have the word "Pro" in their name?
Show answer
SELECT COUNT(*)
FROM products
WHERE product_name LIKE '%Pro%';19. List the first name, last name and city of customers in the state of Maharashtra who did not give a phone number.
Show answer
SELECT first_name, last_name, city
FROM customers
WHERE state = 'Maharashtra' AND phone IS NULL;20. What are the highest and the lowest salary in the employees table? Return both in one row.
Show answer
SELECT MAX(salary), MIN(salary)
FROM employees;Medium SQL practice questions
Joins, GROUP BY with HAVING, subqueries and dates.
21. For every order above 4,00,000 rupees, show the order ID, the customer's full name (first name, a space, last name) and the total amount.
Show answer
SELECT o.order_id, c.first_name || ' ' || c.last_name, o.total_amount
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.total_amount > 400000;22. Show every category name with its number of products. Include categories that have no products.
Show answer
SELECT cat.category_name, COUNT(p.product_id)
FROM categories cat
LEFT JOIN products p ON p.category_id = cat.category_id
GROUP BY cat.category_name;23. Which 5 customer cities bring in the most revenue from delivered orders? Show the city and the revenue, highest first.
Show answer
SELECT c.city, SUM(o.total_amount) AS revenue
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Delivered'
GROUP BY c.city
ORDER BY revenue DESC
LIMIT 5;24. How many customers have never placed an order?
Show answer
SELECT COUNT(*)
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;25. Show the 3 best-selling products by units sold (sum of quantity across all orders), with the product name and units, highest first.
Show answer
SELECT p.product_name, SUM(oi.quantity) AS units
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
GROUP BY p.product_id, p.product_name
ORDER BY units DESC
LIMIT 3;26. For each payment method, show the average payment amount rounded to 2 decimals.
Show answer
SELECT method, ROUND(AVG(amount), 2)
FROM payments
GROUP BY method;27. Which customers placed more than 30 orders? Show the customer ID and their number of orders.
Show answer
SELECT customer_id, COUNT(*)
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 30;28. How many products cost more than the average price of their own category?
Show answer
SELECT COUNT(*)
FROM products p
WHERE p.price > (SELECT AVG(p2.price)
FROM products p2
WHERE p2.category_id = p.category_id);29. Show the number of orders in each month of 2024 as year-month (for example 2024-01) and the count, in month order.
Show answer
SELECT strftime('%Y-%m', order_date) AS month, COUNT(*)
FROM orders
WHERE order_date LIKE '2024%'
GROUP BY month
ORDER BY month;30. How many employees work in a different city from their manager?
Show answer
SELECT COUNT(*)
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
WHERE e.city <> m.city;31. Orders with no row in the payments table: show each order status and how many such orders it has.
Show answer
SELECT o.status, COUNT(*)
FROM orders o
LEFT JOIN payments p ON p.order_id = o.order_id
WHERE p.payment_id IS NULL
GROUP BY o.status;32. For the Mobiles category (category_id = 1), show each brand and its revenue from order items (quantity times unit price), highest first.
Show answer
SELECT p.brand, SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
WHERE p.category_id = 1
GROUP BY p.brand
ORDER BY revenue DESC;33. How many customers have spent more than 10,00,000 rupees in total on delivered orders?
Show answer
SELECT COUNT(*)
FROM (SELECT customer_id
FROM orders
WHERE status = 'Delivered'
GROUP BY customer_id
HAVING SUM(total_amount) > 1000000) AS big;34. For each year, show the percentage of orders that were cancelled, rounded to 1 decimal place.
Show answer
SELECT strftime('%Y', order_date) AS year,
ROUND(100.0 * SUM(CASE WHEN status = 'Cancelled' THEN 1 ELSE 0 END) / COUNT(*), 1)
FROM orders
GROUP BY year;35. List the names of products that have never been ordered but still have stock.
Show answer
SELECT product_name
FROM products p
WHERE stock > 0
AND NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.product_id);36. What is the second highest product price? (If two products share the top price, the answer is the next lower price.)
Show answer
SELECT MAX(price)
FROM products
WHERE price < (SELECT MAX(price) FROM products);37. How many customers placed at least one order in 2023 and at least one in 2025?
Show answer
SELECT COUNT(*)
FROM (SELECT customer_id FROM orders WHERE order_date LIKE '2023%'
INTERSECT
SELECT customer_id FROM orders WHERE order_date LIKE '2025%') AS both_years;38. Leaving out the Management department (it has only the CEO), which department has the highest average salary? Show the department and the average salary rounded to 0 decimals.
Show answer
SELECT department, ROUND(AVG(salary))
FROM employees
WHERE department <> 'Management'
GROUP BY department
ORDER BY AVG(salary) DESC
LIMIT 1;39. Which categories earned more than 1 crore (1,00,00,000) rupees from order items in delivered orders? Show the category name and the revenue.
Show answer
SELECT cat.category_name, SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
WHERE o.status = 'Delivered'
GROUP BY cat.category_name
HAVING SUM(oi.quantity * oi.unit_price) > 10000000;40. For each customer city, how many different customers placed an order in 2025?
Show answer
SELECT c.city, COUNT(DISTINCT o.customer_id)
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_date LIKE '2025%'
GROUP BY c.city;Hard SQL practice questions
Window functions, CTEs and multi-step logic, the kind asked in data analyst interviews.
41. Show the top 3 products by revenue (quantity times unit price) in each category, with the category name, product name and revenue.
Show answer
SELECT category_name, product_name, revenue
FROM (SELECT cat.category_name, p.product_name,
SUM(oi.quantity * oi.unit_price) AS revenue,
ROW_NUMBER() OVER (PARTITION BY cat.category_id
ORDER BY SUM(oi.quantity * oi.unit_price) DESC) AS rn
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
GROUP BY cat.category_id, cat.category_name, p.product_id, p.product_name) AS ranked
WHERE rn <= 3;42. For delivered orders in 2025, show each month (YYYY-MM), its revenue (sum of total amount) and the growth in percent over the previous month, rounded to 1 decimal. January has no growth value.
Show answer
WITH m AS (
SELECT strftime('%Y-%m', order_date) AS month, SUM(total_amount) AS revenue
FROM orders
WHERE order_date LIKE '2025%' AND status = 'Delivered'
GROUP BY month
)
SELECT month, revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ LAG(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM m;43. For delivered orders in 2024, show each month (YYYY-MM), its revenue and the running total of revenue up to that month.
Show answer
WITH m AS (
SELECT strftime('%Y-%m', order_date) AS month, SUM(total_amount) AS revenue
FROM orders
WHERE order_date LIKE '2024%' AND status = 'Delivered'
GROUP BY month
)
SELECT month, revenue, SUM(revenue) OVER (ORDER BY month) AS running_total
FROM m;44. How many customers placed their first and their latest order more than 730 days apart?
Show answer
SELECT COUNT(*)
FROM (SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING julianday(MAX(order_date)) - julianday(MIN(order_date)) > 730) AS loyal;45. How many customers have at least 5 orders, all of them delivered?
Show answer
SELECT COUNT(*)
FROM (SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 5
AND SUM(CASE WHEN status <> 'Delivered' THEN 1 ELSE 0 END) = 0) AS perfect;46. Which employees earn more than their own manager? Show the employee name, their salary and the manager's salary.
Show answer
SELECT e.name, e.salary, m.salary
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
WHERE e.salary > m.salary;47. What percentage of customers who ordered at least once came back and ordered again? Round to 1 decimal place.
Show answer
SELECT ROUND(100.0 * SUM(CASE WHEN n > 1 THEN 1 ELSE 0 END) / COUNT(*), 1)
FROM (SELECT customer_id, COUNT(*) AS n
FROM orders
GROUP BY customer_id) AS per_customer;48. Show each category name with its share of total order-item revenue in percent, rounded to 1 decimal, largest share first. Only include categories that sold something.
Show answer
SELECT cat.category_name,
ROUND(100.0 * SUM(oi.quantity * oi.unit_price)
/ (SELECT SUM(quantity * unit_price) FROM order_items), 1) AS share_pct
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
JOIN categories cat ON cat.category_id = p.category_id
GROUP BY cat.category_name
ORDER BY share_pct DESC;49. Rank the customer cities by revenue from delivered orders in 2025 using DENSE_RANK. Show the city, the revenue and the rank, with rank 1 for the highest revenue.
Show answer
SELECT c.city, SUM(o.total_amount) AS revenue,
DENSE_RANK() OVER (ORDER BY SUM(o.total_amount) DESC) AS city_rank
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'Delivered' AND o.order_date LIKE '2025%'
GROUP BY c.city;50. For each year, find the month with the most orders. Show the year, the month (YYYY-MM) and its number of orders.
Show answer
WITH m AS (
SELECT strftime('%Y', order_date) AS year,
strftime('%Y-%m', order_date) AS month,
COUNT(*) AS orders
FROM orders
GROUP BY year, month
)
SELECT year, month, orders
FROM (SELECT m.*, RANK() OVER (PARTITION BY year ORDER BY orders DESC) AS r FROM m) AS x
WHERE r = 1;SQL queries cheat sheet
The syntax from this page on one screen. Screenshot it, or get the printable version in the PDF.
Read
SELECT col1, col2 FROM t;Pick columnsSELECT DISTINCT col FROM t;Unique valuesSELECT * FROM t WHERE cond;Filter rows... ORDER BY col DESC LIMIT 10;Sort and keep the top 10... LIMIT 10 OFFSET 20;Page 3 of 10 rows eachFilter
WHERE a = 1 AND (b = 2 OR c = 3)Combine conditionsWHERE col IN ('x', 'y')Match a listWHERE col BETWEEN 10 AND 20Inclusive rangeWHERE col LIKE 'Ab%'Starts with AbWHERE col IS NULLMissing valuesSummarise
COUNT(*), COUNT(col), COUNT(DISTINCT col)CountingSUM(col), AVG(col), MIN(col), MAX(col)Totals and extremesGROUP BY colOne row per valueHAVING COUNT(*) > 5Filter groupsJoin
a JOIN b ON a.id = b.a_idOnly matchesa LEFT JOIN b ON ...All of a, matches of b... WHERE b.id IS NULLRows of a with no matcht x JOIN t y ON x.mgr = y.idSelf joina CROSS JOIN bEvery combinationAdvanced
WHERE col > (SELECT AVG(col) FROM t)SubqueryWHERE NOT EXISTS (SELECT 1 FROM ...)Anti-joinCASE WHEN c THEN 'a' ELSE 'b' ENDIf-elseWITH x AS (SELECT ...) SELECT ...CTEROW_NUMBER() OVER (PARTITION BY g ORDER BY v)Top N per groupSUM(v) OVER (ORDER BY d)Running totalChange
INSERT INTO t (a, b) VALUES (1, 'x');Add a rowUPDATE t SET a = 2 WHERE id = 5;Change rowsDELETE FROM t WHERE id = 5;Remove rowsCREATE TABLE t (id INTEGER PRIMARY KEY, ...);New tableCREATE INDEX idx ON t(col);Faster lookupsSQL queries notes PDF
The PDF has every SQL query from this page with its output, the dialect notes, the cheat sheet and all 50 practice questions with answers, in 45 printable pages with a clickable table of contents. Pair it with the .sql file of the sample database and you can practise anywhere, even offline in MySQL Workbench or pgAdmin. It is free, with no sign-up.
SQL Queries with Examples
44 pages · 62 examples with output · cheat sheet · 50 practice questions
Frequently asked questions
What are the basic SQL queries every beginner should know?
Start with SELECT and FROM to read columns, WHERE to filter rows, ORDER BY and LIMIT to sort and pick the top rows, the aggregate functions COUNT, SUM and AVG with GROUP BY, and INNER and LEFT JOIN to combine tables. Then learn INSERT, UPDATE and DELETE to change data. These cover most everyday SQL queries.
How can I practise SQL queries online for free?
Use the online SQL editor and the 50 practice questions on this page. They run in your browser on a sample online store database with 10,000 orders, so there is nothing to install, and the practice questions check your answer automatically. You can also download the database as a .sql file and run it in MySQL or PostgreSQL.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before they are grouped, so it cannot use aggregate functions. HAVING filters the groups made by GROUP BY, so it is where conditions like COUNT(*) > 5 or SUM(amount) > 1000 go. A query can use both.
Which SQL join is used most often?
INNER JOIN and LEFT JOIN cover almost all real queries. Use INNER JOIN when you only want rows that have a match in both tables, and LEFT JOIN when you want every row from the first table, with NULLs where the second table has no match. LEFT JOIN with WHERE ... IS NULL finds rows with no match at all.
Are SQL queries the same in MySQL, PostgreSQL and SQL Server?
The core is the same in all of them: SELECT, WHERE, GROUP BY, joins, subqueries and window functions work almost identically. The differences are mainly in limiting rows (LIMIT vs TOP), string and date functions, and auto-increment columns. This page notes the differences next to each example.
How long does it take to learn SQL queries?
Most people can write basic SQL queries in a week of regular practice, and joins, GROUP BY and subqueries in two to four weeks. Window functions and CTEs take a little longer. The fastest way is to write queries on a real dataset every day, which is what the practice questions here are for.
Can I download these SQL queries as a PDF?
Yes. Every query on this page with its output, the cheat sheet and all 50 practice questions with answers are in a free 44-page PDF. Use the Download PDF button at the top of the page; no sign-up is needed.
Next steps
Work through the practice questions one level at a time and press "Mark as done" when you can solve each one without looking at the answer. When the hard ones feel comfortable, move on to our 100 SQL interview questions, which go deeper into theory and tricky query questions, and the DBMS interview questions for keys, transactions and indexing. Analysing data in Python next? The pandas roadmap shows how the same GROUP BY and JOIN ideas work in pandas. All the best!
