SQL for Data Analysis
2026-04-01
sales_analysis)WHERE using key operatorsHAVINGCASE WHEN to create analytical categoriesOpen Docker Desktop, Run and open Pgadmin:
sales_analysisDROP TABLE IF EXISTS sales_analysis;
CREATE TABLE sales_analysis AS
SELECT
s.transaction_id,
o.order_date,
DATE(o.order_date) AS order_date_date,
o.year,
o.quarter,
o.month,
c.customer_name,
c.city,
c.zip_code,
p.product_name,
p.category,
p.price,
e.first_name AS employee_first_name,
e.last_name AS employee_last_name,
e.salary AS employee_salary,
s.quantity,
s.discount,
s.total_sales
FROM sales AS s
JOIN orders AS o
ON s.order_id = o.order_id
JOIN customers AS c
ON s.customer_id = c.customer_id
JOIN products AS p
ON s.product_id = p.product_id
LEFT JOIN employees AS e
ON s.employee_id = e.employee_id;| Pattern Example | Meaning |
|---|---|
WHERE product_name LIKE 'Elec%' |
Starts with “Elec” |
WHERE product_name LIKE '%Phone' |
Ends with “Phone” |
WHERE product_name LIKE '%Pro%' |
Contains “Pro” anywhere |
WHERE city LIKE '_ast%' |
“ast” begins at the second character |
WHERE city LIKE 'N%_%' |
Starts with “N” and has at least 3 characters |
WHERE category LIKE 'B%ks' |
Starts with “B” and ends with “ks” |
Tip
Use IS NULL and IS NOT NULL
Do not use = NULL or <> NULL
Warning
Filtering raw columns belongs in WHERE.
HAVING is for aggregated conditions.