TRAINING | SQL REFRESHER
SQL for Excel Users: Filter, Sort, Group and Aggregate
Creating and loading tables, SELECT, TOP, ORDER BY, WHERE operators, NULL, GROUP BY, HAVING and DISTINCT on an orders dataset.
1. The Crux in 60 Seconds
1Excel actions have SQL equivalents. Filter is
WHERE, sort is ORDER BY, drop-down list of values is DISTINCT, pivot table is GROUP BY with an aggregate.2Do not run SELECT * on big tables. Use
TOP n and pick only the columns you need: fewer rows and columns is better for performance.3WHERE filters rows, HAVING filters groups. WHERE checks each row on its own; HAVING filters the aggregated result after GROUP BY.
4NULL is unknown.
= NULL never works; use IS NULL / IS NOT NULL.2. Foundational Concepts & Comparisons
The dataset: Superstore-style orders (1,000 rows in class)
Like Amazon-style e-commerce orders: order ID, order date, ship date, ship mode (first, second, standard class), customer ID and name, segment (consumer, corporate, home office), country, city, state, product ID, category (furniture, office supplies, technology), subcategory, product name, sales, quantity, discount, profit. One order ID can have several rows (one per product). The SQL is the same with millions of rows; only 1,000 are used so queries run fast.| In Excel | In SQL |
|---|---|
| Open the sheet and see all data | SELECT * FROM orders |
| Hide columns, copy to another sheet | Name the columns: SELECT order_id, order_date FROM orders |
| Sort A to Z or Z to A | ORDER BY col (ascending by default) or DESC |
| Filter on a value, a list or a range | WHERE with =, IN, BETWEEN, LIKE |
| Filter drop-down of unique values | SELECT DISTINCT segment (or GROUP BY) |
| Filter blanks | IS NULL |
| Pivot table: category and sum of sales | GROUP BY category with SUM(sales) |
| Filter pivot results (sum above 20,000) | HAVING SUM(sales) > 20000 |