Module 3 · SQL for Data Analysis
SELECT
Choose the columns you need, rename them, calculate new ones and remove duplicates.
About 25 minutes
The problem
The sales team is preparing calls to customers. They don't need every column in the customers table. They need the company name, the city and the industry, and nothing else cluttering the screen.
Later that day, finance asks for each shipment's weight in tonnes, but the database stores it in kilograms.
The concept
SELECT * returns every column. Most of the time you want to be specific, and list only the columns you need, separated by commas.
You can also:
- Rename a column in the result with
AS, which is called an alias. - Calculate a new column from existing ones, using
+,-,*and/. - Remove duplicates with
DISTINCT, so each value appears once.
Being specific makes queries faster, results easier to read, and your intent clear to the next person who reads your SQL.
Example
SELECT
company_name,
city,
industry
FROM customers;And a calculated, renamed column:
SELECT
shipment_id,
weight_kg,
weight_kg / 1000.0 AS weight_tonnes
FROM shipments;Walkthrough
In the first query, the columns come back in the order you list them, not the order they're stored in.
In the second:
weight_kg / 1000.0divides each row's weight by 1,000.AS weight_tonnesgives the calculated column a readable name. Without it, the column heading would be the expression itself.- We divide by
1000.0rather than1000. In SQLite (and SQL Server), dividing one whole number by another throws away the decimals, so1500 / 1000gives1. Adding.0makes it decimal division, so1500 / 1000.0gives1.5.
To see each value only once, use DISTINCT:
SELECT DISTINCT mode FROM routes;Harbourline runs three transport modes, so you get three rows.
Practice
Practice
The sales team wants a call list: show company_name, city and industry for every customer.
Ctrl + Enter to run. Tab indents; press Esc then Tab to leave the editor.
Challenge
Challenge · optional
Finance wants each shipment's charge in millions of naira. Show shipment_id and freight_charge divided by 1,000,000 as charge_millions.
Ctrl + Enter to run. Tab indents; press Esc then Tab to leave the editor.
Challenge · optional
Which industries do Harbourline's customers work in? List each industry once.
Ctrl + Enter to run. Tab indents; press Esc then Tab to leave the editor.
Check your understanding
Answer every question to check.