SQL for Business Analysts: The 5 Queries You Actually Need
Five SQL queries cover most of what a business analyst needs: SELECT, WHERE, ORDER BY, GROUP BY and JOIN. Watch each one typed and run on a sample online shop database, with plain-English explanations.
Step by step
Five queries
- Five queries. Most business analysts only need five SQL queries to answer real questions from data. Let me show you all five, one by one, on a sample database for an online shop.
- The sample database. On the left are the tables. Customers, products and orders, just like real business data. Every row in a table has the same columns.
SELECT
- SELECT. Query one is select. Say which columns you want, then which table they come from. Here, the first name and city of every customer. Press run. Forty customers, and only the two columns we asked for.
SELECT first_name, city FROM customers;
WHERE
- WHERE. Query two is where. It keeps only the rows you care about. Let's find the cancelled orders. Text goes in single quotes. Eleven cancelled orders. A real question, answered in three lines.
SELECT order_id, order_date, status FROM orders WHERE status = 'Cancelled';
ORDER BY
- ORDER BY. Query three is order by. It sorts the result. Descending puts the biggest orders first, and limit five keeps only the top five. And here's your top five list, biggest first.
SELECT order_id, order_date, order_total FROM orders ORDER BY order_total DESC LIMIT 5; - The biggest order. The biggest order was five hundred and thirteen. Top lists like this show up in almost every report.
GROUP BY
- GROUP BY. Query four is group by. It turns many rows into one row per group. Count star counts the rows in each group, and as gives that column a name. One row per status. Most orders were delivered, and a few are still processing.
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status;
JOIN
- JOIN. Query five is join. Orders don't store the region, customers do. Join links the two tables where the customer ID matches. The letters o and c are short names for each table. Then group by region, and sort by sales. See how the five queries work together?
SELECT c.region, SUM(o.order_total) AS sales FROM orders AS o JOIN customers AS c ON c.customer_id = o.customer_idGROUP BY c.region ORDER BY sales DESC; - Sales per region. Run it. Total sales for each region, biggest first.
- The top region. North sold the most, by a long way. That's the kind of answer a manager asks a business analyst for every week.
Recap
- The five queries. So, select picks columns, where picks rows, order by sorts, group by makes totals, and join links tables. Practice these five, and you can answer most data questions yourself.