SQL in Action: A Curated Gallery of Practical Query Examples
SQL remains the backbone of data work, and the fastest way to learn is through practical sql query examples. This curated gallery walks through real patterns you can adapt: filtering, joining, aggregating, and troubleshooting. Each example focuses on clarity, so you can copy the logic and adjust table or column names for your own database.
SQL in Action: A Curated Gallery of Practical Query Examples
Below, the examples assume a simple sales database with customers, orders, and products. Use them as a starting point, then explore deeper references such as codecodex.com for more patterns.
Filtering and Sorting
Start with focused retrieval. These sql query examples show how to narrow rows and order results without scanning everything.
SELECT customer_id, order_date FROM orders WHERE order_date >= '2024-01-01' ORDER BY order_date DESC;SELECT * FROM products WHERE price BETWEEN 10 AND 50 AND stock > 0 ORDER BY price ASC;
Joining Related Tables
Joins unlock context. The next sql query examples combine customer names with order totals and product details.
SELECT c.name, o.order_date FROM customers c JOIN orders o ON c.id = o.customer_id;SELECT p.name, SUM(oi.quantity) AS units FROM products p JOIN order_items oi ON p.id = oi.product_id GROUP BY p.name;
Aggregating and Grouping
Aggregation turns rows into insight. Use these sql query examples to summarize revenue, count activity, and spot trends.
SELECT customer_id, COUNT(*) AS order_count, SUM(total) AS revenue FROM orders GROUP BY customer_id HAVING SUM(total) > 500;SELECT DATE_TRUNC('month', order_date) AS month, AVG(total) FROM orders GROUP BY month ORDER BY month;
Updating and Cleaning Data
Read queries dominate dashboards, but maintenance matters too. These sql query examples keep data accurate with targeted updates and safe deletes.
UPDATE customers SET status = 'active' WHERE last_login >= CURRENT_DATE - INTERVAL '90 days';DELETE FROM orders WHERE status = 'cancelled' AND order_date < '2023-01-01';
Common Table Expressions
CTEs make complex logic readable. The following sql query examples break a multi-step calculation into named parts.
WITH monthly AS (SELECT customer_id, SUM(total) AS spent FROM orders GROUP BY customer_id) SELECT * FROM monthly WHERE spent > 1000;
Window Functions
Window functions add ranking without losing row detail. Try these sql query examples for leaderboards and running totals.
SELECT name, total, RANK() OVER (ORDER BY total DESC) AS rank FROM customers;SELECT order_date, SUM(total) OVER (ORDER BY order_date) AS running_total FROM orders;
FAQs About sql query examples
How do I choose between JOIN and subquery?
Use JOINs when you need columns from multiple tables and want readable, set-based logic. Subqueries work well for isolated filters or scalar checks; test performance on your data.
Why include ORDER BY when grouping?
ORDER BY controls output order, while GROUP BY defines aggregation buckets. Without ORDER BY, the database may return groups in any order, which can confuse dashboards.
How can I practice these patterns safely?
Use a sandbox database or sample dataset. Run each query with LIMIT first, inspect execution plans, and compare results against a manual check. Revisit curated sql query examples until the patterns feel natural.
Working with Strings and Dates
Text and date logic appear in nearly every report. These sql query examples show trimming, concatenating, and bucketing dates without extra application code.
SELECT CONCAT(first_name, ' ', last_name) AS full_name, LOWER(email) FROM customers;SELECT id, created_at, EXTRACT(YEAR FROM created_at) AS year FROM accounts WHERE created_at >= '2024-01-01';
Subqueries and EXISTS
Sometimes a nested question is clearer than a join. The next sql query examples use subqueries to filter by related rows and avoid duplicate output.
SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE total > 500);SELECT name FROM products p WHERE EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.id AND oi.quantity > 10);
Pagination and Ranking
Large result sets require limits. Use these sql query examples to page through data predictably and return top performers.
SELECT * FROM orders ORDER BY order_date DESC LIMIT 20 OFFSET 40;SELECT name, total FROM customers ORDER BY total DESC FETCH FIRST 5 ROWS ONLY;
Combining Results with UNION
UNION merges compatible result sets. These sql query examples combine current and archived records while removing duplicates.
SELECT id, email FROM customers_2024 UNION SELECT id, email FROM customers_2023;SELECT 'active' AS source, COUNT(*) FROM customers WHERE status = 'active' UNION ALL SELECT 'inactive', COUNT(*) FROM customers WHERE status = 'inactive';
Transaction and Error Handling
Production queries need safety. Wrap multi-step changes in transactions and test rollbacks; these sql query examples emphasize predictable outcomes.
What is the safest way to test a DELETE?
Run the same WHERE clause as a SELECT first. Confirm row counts, wrap the DELETE in a transaction, and commit only after verification. This habit matters more than memorizing sql query examples.
Can these sql query examples run on every database?
Most patterns are portable, but date functions, LIMIT, and FETCH syntax vary by engine. Check your database manual and adapt identifiers.