SQL query examples for everyday tasks
A collection of sample SQL queries for the jobs that actually come up at work: filtering lists, summing up sales, joining tables, finding problems in the data. Every query is shown with the exact result it returns on our practice database.
The short version: every statement on this page runs against the database of a small online office supplies store, with the tables customers, products, orders, order_items (one row per product in an order) and employees. The results below are real output, not made-up numbers. Each example links to a lesson with exercises.
Finding and filtering rows
All customers in one city
The classic: a list with a condition. Text goes in single quotes and has to match the table exactly.
SELECT name, phone
FROM customers
WHERE city = 'Chicago';
| name | phone |
|---|---|
| Emily Carter | NULL |
| Westbrook Dental Clinic | 312-555-0164 |
More on this in the lesson WHERE: filter rows.
Customers with no phone number
An empty field in SQL is NULL. Comparing with = NULL finds nothing, which is why there is IS NULL.
SELECT name, city
FROM customers
WHERE phone IS NULL;
| name | city |
|---|---|
| Emily Carter | Chicago |
| Olivia Brooks | Austin |
| Daniel Kim | Seattle |
More on this in the lesson NULL and COALESCE.
Products from certain categories in a price range
IN checks against a list, BETWEEN against a range with both ends included. Combined with AND and sorted by price:
SELECT name, category, price
FROM products
WHERE category IN ('Furniture', 'Electronics')
AND price BETWEEN 100 AND 300
ORDER BY price;
| name | category | price |
|---|---|---|
| Cross-cut shredder | Electronics | 129 |
| Comfort office chair | Furniture | 189 |
| Mono laser printer L30 | Electronics | 219 |
| 27-inch monitor | Electronics | 279 |
More on this in the lesson IN and BETWEEN.
Orders from one month
Dates in the practice database are stored as text in the form YYYY-MM-DD. That way they sort and compare correctly, and BETWEEN with the first and last day of March gets the whole month:
SELECT order_id, order_date, status
FROM orders
WHERE order_date BETWEEN '2026-03-01' AND '2026-03-31';
| order_id | order_date | status |
|---|---|---|
| 1007 | 2026-03-04 | delivered |
| 1008 | 2026-03-17 | delivered |
| 1009 | 2026-03-30 | delivered |
Watch out with columns that include a time: there, anything after midnight on the 31st falls out. The safer pattern is order_date >= '2026-03-01' AND order_date < '2026-04-01'.
Products whose name contains a word
LIKE with % searches for part of a text. The % stands for any number of characters before and after.
SELECT name, price
FROM products
WHERE name LIKE '%black%';
| name | price |
|---|---|
| Black ink cartridge | 24.9 |
| Black toner XL | 89.9 |
Both names start with a capital B and still match the lowercase pattern: in SQLite, LIKE ignores case for the letters A to Z.
More on this in the lesson LIKE: pattern matching.
Try it yourself: products from several categories
Task The warehouse is counting small items: everything in the categories Paper, Writing and Filing. Show name, category and price of these products from the products table. Use IN with a list.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
Counting, summing, grouping
Number of customers per country
GROUP BY puts all rows with the same country into one group, and COUNT(*) counts the rows in each group.
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC;
| country | customers |
|---|---|
| USA | 8 |
| UK | 3 |
| Canada | 1 |
More on this in the lesson GROUP BY: summarize groups.
Revenue by month
Quantities and prices live in order_items, the date and status in orders. A JOIN on the order number brings them together. Cancelled orders are left out, and substr(o.order_date, 1, 7) cuts the year and month out of the date.
SELECT substr(o.order_date, 1, 7) AS month,
ROUND(SUM(i.quantity * i.unit_price), 2) AS revenue
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;
| month | revenue |
|---|---|
| 2026-01 | 1304.7 |
| 2026-02 | 1557.6 |
| 2026-03 | 3249.25 |
| 2026-04 | 229.85 |
| 2026-05 | 378.8 |
| 2026-06 | 2333.91 |
More on this in the lesson Dates and times.
Top 5 products by revenue
Sum per product first, then sort from highest to lowest and cut the list off after five rows. Three tables are joined here: order_items for quantity and price, products for the name, orders for the status.
SELECT p.name,
SUM(i.quantity) AS units,
ROUND(SUM(i.quantity * i.unit_price), 2) AS revenue
FROM order_items AS i
JOIN products AS p ON p.product_id = i.product_id
JOIN orders AS o ON o.order_id = i.order_id
WHERE o.status <> 'cancelled'
GROUP BY p.product_id, p.name
ORDER BY revenue DESC
LIMIT 5;
| name | units | revenue |
|---|---|---|
| Comfort office chair | 11 | 1945 |
| Copy paper, 500 sheets | 330 | 1576.7 |
| 27-inch monitor | 5 | 1365 |
| Black toner XL | 12 | 1048.8 |
| Standing desk | 2 | 878 |
By units, copy paper would win by a mile. Decide what “top” means before you write the query.
More on this in the lesson ORDER BY and LIMIT.
Orders worth more than 1,000
A condition on a group's total belongs in HAVING, not WHERE. WHERE checks single rows before anything is grouped.
SELECT order_id, ROUND(SUM(quantity * unit_price), 2) AS order_total
FROM order_items
GROUP BY order_id
HAVING SUM(quantity * unit_price) > 1000
ORDER BY order_total DESC;
| order_id | order_total |
|---|---|
| 1004 | 1344 |
| 1009 | 1284.4 |
| 1014 | 1236 |
| 1008 | 1067.45 |
More on this in the lesson HAVING: filter groups.
Counting products by price band
CASE WHEN assigns each row to a band, then GROUP BY counts per band. The conditions are checked from top to bottom, and the first match wins.
SELECT CASE
WHEN price < 10 THEN 'under 10'
WHEN price < 100 THEN '10 to 99.99'
ELSE '100 and up'
END AS price_band,
COUNT(*) AS products
FROM products
GROUP BY price_band
ORDER BY MIN(price);
| price_band | products |
|---|---|
| under 10 | 5 |
| 10 to 99.99 | 2 |
| 100 and up | 5 |
More on this in the lesson CASE WHEN: conditional logic.
Try it yourself: calculating with columns
Task For the stock count, accounting needs the stock value of every product. From the products table, show the columns name, price and stock, plus a fourth column with the stock value: price times stock.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
Joining tables
Open orders with customer names
The orders table only holds the customer number. A JOIN fetches the name from customers through the shared customer_id column.
SELECT o.order_id, o.order_date, c.name
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
WHERE o.status = 'open';
| order_id | order_date | name |
|---|---|---|
| 1016 | 2026-06-12 | Daniel Kim |
| 1017 | 2026-06-13 | Raj Patel |
| 1018 | 2026-06-14 | Northline Printing Co |
More on this in the lesson INNER JOIN: joining tables.
Customers with no orders since April
Sales wants to call customers who haven't ordered in a while. LEFT JOIN keeps every customer, including those without a matching order. For them the columns from orders are empty, and that is exactly what WHERE filters on. The date condition sits in ON, because in WHERE it would throw the empty rows straight back out.
SELECT c.name, c.city
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.order_date >= '2026-04-01'
WHERE o.order_id IS NULL;
| name | city |
|---|---|
| Emily Carter | Chicago |
| Lakeview Hotel Ltd | Manchester |
| Maple Grove High School | Austin |
Without the date condition the list is empty: every customer in the practice database has ordered at least once. WHERE NOT EXISTS (SELECT 1 FROM orders ...) gets the same result.
More on this in the lesson LEFT JOIN.
More on this in the lesson EXISTS and NOT EXISTS.
Employees and their managers
Who reports to whom is stored in the same table: manager_id points to another row of employees. So you join the table to itself, with two different aliases.
SELECT e.first_name, e.last_name, m.last_name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
WHERE e.department = 'Sales';
| first_name | last_name | manager |
|---|---|---|
| Tom | Bradley | Mitchell |
| Julia | Reyes | Bradley |
| Marcus | Allen | Bradley |
More on this in the lesson Self join.
Checking and comparing
Finding duplicate values
Which values show up more than once? GROUP BY with HAVING COUNT(*) > 1 lists them. Here it's cities with several customers. The same query finds duplicate customer numbers, email addresses or invoices after an import.
SELECT city, COUNT(*) AS customers
FROM customers
GROUP BY city
HAVING COUNT(*) > 1;
| city | customers |
|---|---|
| Austin | 2 |
| Boston | 2 |
| Chicago | 2 |
More on this in the lesson Finding duplicates.
Salaries above average
A subquery in parentheses works out the average, and the outer query compares each row with it. AVG skips Laura Hughes, whose salary is empty.
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC;
| first_name | last_name | salary |
|---|---|---|
| Karen | Mitchell | 93600 |
| Tom | Bradley | 62400 |
| Nina | Cooper | 52800 |
More on this in the lesson Subqueries.
Ranking within each department
A window function hands out ranks without collapsing rows. PARTITION BY starts again at 1 in every department.
SELECT department, last_name, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
FROM employees
WHERE department IN ('Sales', 'Accounting');
| department | last_name | salary | salary_rank |
|---|---|---|---|
| Accounting | Cooper | 52800 | 1 |
| Accounting | Ward | 43200 | 2 |
| Sales | Bradley | 62400 | 1 |
| Sales | Allen | 49200 | 2 |
| Sales | Reyes | 46800 | 3 |
More on this in the lesson Window functions: ROW_NUMBER, RANK.
Changing data
Raising prices in one category by 5 percent
UPDATE changes every row that WHERE matches. Without WHERE, that would be every product. So run a SELECT with the same condition first to see which rows you are about to touch.
UPDATE products
SET price = ROUND(price * 1.05, 2)
WHERE category = 'Paper';
The database reports 2 changed rows. Afterwards, SELECT name, price FROM products WHERE category = 'Paper' shows:
| name | price |
|---|---|
| Copy paper, 500 sheets | 5.24 |
| Notebook A5, ruled | 5.76 |
More on this in the lesson UPDATE: changing rows.
Your turn: the reorder list
Reading queries is one thing, writing them is another. This task from the level 1 project combines a filter, a calculation and sorting. As with every exercise, it is also checked against different, hidden data.
Task The warehouse keeps at least 20 units of every product in stock. Build the reorder list: all products with fewer than 20 units, except the Furniture category (the manufacturer ships those directly). Columns: product (the name), stock, reorder_qty (how many units are missing to reach 20) and reorder_cost (that quantity times the price). Sorted by reorder_cost, highest first.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
Do these examples work in MySQL, PostgreSQL and SQL Server?
Most of them do: SELECT, WHERE, IN, BETWEEN, LIKE, IS NULL, GROUP BY, HAVING, CASE, JOIN, subqueries and UPDATE are all part of standard SQL. The results above come from SQLite, the database behind our exercises. Things to watch for when you move a query elsewhere:
- The first few rows: MySQL and PostgreSQL use LIMIT like SQLite, SQL Server writes
SELECT TOP (5) .... - Aliases in GROUP BY: the examples group by month and price_band, the names from the SELECT list. MySQL and PostgreSQL allow that. SQL Server doesn't, so there you repeat the full expression in GROUP BY.
- Aliases in HAVING: MySQL allows them, PostgreSQL doesn't. That's why the “orders worth more than 1,000” example spells out the sum in HAVING, so it runs everywhere.
- Dates and text: date and string functions have different names from system to system. The dates here are text, so substr is enough.
- Upper and lower case: whether
LIKE '%black%'also finds “Black” depends on the system and its settings. The lessons on WHERE and LIKE cover the details.
Sources: MySQL Reference Manual (Problems with Column Aliases), PostgreSQL documentation (SELECT), Microsoft Learn (GROUP BY, TOP).
FAQ
Can I run these examples myself?
Yes. Every exercise has a Run button, and all the tables on this page are available there. Type in a query from here and change it: another city, another month, one more column. That's the fastest way to learn what each part does.
In what order do the parts of a query go?
SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Any other order is a syntax error. The database evaluates them in a different order, FROM and WHERE first and SELECT later. That's why standard SQL doesn't let you use a SELECT alias in WHERE. More on this in SQL order of execution.
Why are prices written with a dot and without a currency?
SQL writes decimals with a dot, and a comma separates columns and values. The practice data stores amounts without a currency symbol, so the same examples fit dollars and pounds alike. How a number looks in the final report is up to the program that displays it.
Where can I learn this step by step?
In the SQL course. It starts with your first SELECT and builds up topic by topic, all the way to window functions and changing data. All practice problems at a glance are on SQL practice.