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';
namephone
Emily CarterNULL
Westbrook Dental Clinic312-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;
namecity
Emily CarterChicago
Olivia BrooksAustin
Daniel KimSeattle

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;
namecategoryprice
Cross-cut shredderElectronics129
Comfort office chairFurniture189
Mono laser printer L30Electronics219
27-inch monitorElectronics279

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_idorder_datestatus
10072026-03-04delivered
10082026-03-17delivered
10092026-03-30delivered

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%';
nameprice
Black ink cartridge24.9
Black toner XL89.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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

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;
countrycustomers
USA8
UK3
Canada1

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;
monthrevenue
2026-011304.7
2026-021557.6
2026-033249.25
2026-04229.85
2026-05378.8
2026-062333.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;
nameunitsrevenue
Comfort office chair111945
Copy paper, 500 sheets3301576.7
27-inch monitor51365
Black toner XL121048.8
Standing desk2878

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_idorder_total
10041344
10091284.4
10141236
10081067.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_bandproducts
under 105
10 to 99.992
100 and up5

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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

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_idorder_datename
10162026-06-12Daniel Kim
10172026-06-13Raj Patel
10182026-06-14Northline 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;
namecity
Emily CarterChicago
Lakeview Hotel LtdManchester
Maple Grove High SchoolAustin

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_namelast_namemanager
TomBradleyMitchell
JuliaReyesBradley
MarcusAllenBradley

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;
citycustomers
Austin2
Boston2
Chicago2

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_namelast_namesalary
KarenMitchell93600
TomBradley62400
NinaCooper52800

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');
departmentlast_namesalarysalary_rank
AccountingCooper528001
AccountingWard432002
SalesBradley624001
SalesAllen492002
SalesReyes468003

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:

nameprice
Copy paper, 500 sheets5.24
Notebook A5, ruled5.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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

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.

From reading examples to writing your own

Ready-made queries are great to look things up. Real confidence comes from writing them yourself. The SQL course gets you there in small steps, with exercises on the same data you have seen here.

Go to the SQL course

Write to us

Choose language

Select your preferred language