{% extends "base.html" %} {% block title %}SQL Learning - Data Science Lab{% endblock %} {% block content %}

📖 Why SQL for Data Science?

SQL (Structured Query Language) is the universal language for working with relational databases. In the data ecosystem, government datasets from housing, Urban Planning, and Transport Authority are often stored in relational databases. SQL lets you query, filter, aggregate, and join these datasets efficiently.

🖥️ Interactive SQL Console

1️⃣ SQL DDL — Data Definition Language

DDL commands define the structure of your database: tables, columns, constraints, and indexes.

🎯 Purpose

Design a normalized schema for housing data with proper relationships and constraints.

SQL
-- CREATE TABLE with constraints
CREATE TABLE dim_location (
    location_id INTEGER PRIMARY KEY AUTOINCREMENT,
    town VARCHAR(100) NOT NULL,
    property_type VARCHAR(50),
    block VARCHAR(20),
    street_name VARCHAR(200),
    planning_area VARCHAR(100),
    UNIQUE(town, block, street_name, property_type)
);

-- CREATE INDEX for query performance
CREATE INDEX idx_location_town ON dim_location(town);

-- ALTER TABLE (in SQLite, limited to adding columns)
-- ALTER TABLE dim_location ADD COLUMN postal_code VARCHAR(10);

-- CREATE VIEW for reusable queries
CREATE VIEW v_hdb_summary AS
SELECT l.town, t.year, AVG(f.price) as avg_price
FROM fact_transactions f
JOIN dim_location l ON f.location_id = l.location_id
JOIN dim_time t ON f.time_id = t.time_id
GROUP BY l.town, t.year;
Expected: Tables created with proper constraints and relationships

2️⃣ SQL DML — Data Manipulation Language

DML commands insert, update, delete, and query data.

INSERT

SQL
-- Single INSERT
INSERT INTO raw_data (month, town, property_type, price)
VALUES ('2024-07', 'DOWNTOWN', 'MEDIUM', 650000);

-- Bulk INSERT
INSERT INTO dim_time (full_date, year, quarter, month, month_name)
VALUES
    ('2024-01-01', 2024, 1, 1, 'January'),
    ('2024-02-01', 2024, 1, 2, 'February'),
    ('2024-03-01', 2024, 1, 3, 'March');

SELECT with Filters

SQL
SELECT town, property_type, price
FROM raw_data
WHERE price > 500000
ORDER BY price DESC;

UPDATE and DELETE

SQL
-- UPDATE (be careful in production!)
UPDATE raw_data
SET price = 660000
WHERE town = 'DOWNTOWN' AND block = '184' AND month = '2024-01';

-- DELETE with condition
DELETE FROM raw_data WHERE price < 0;

-- TRANSACTION for data integrity
BEGIN TRANSACTION;
    INSERT INTO raw_data (month, town, property_type, price)
    VALUES ('2024-07', 'NORTHPARK', 'MEDIUM', 550000);
    UPDATE pipeline_runs SET status = 'completed' WHERE run_id = 1;
COMMIT;

3️⃣ Advanced SQL

JOINs

SQL
-- Multi-table JOIN: Combine facts with dimensions
SELECT l.town, t.year, t.month, p.property_type,
       f.price, f.price_per_sqm
FROM fact_transactions f
JOIN dim_location l ON f.location_id = l.location_id
JOIN dim_time t ON f.time_id = t.time_id
JOIN dim_property_type p ON f.property_type_id = p.property_type_id
ORDER BY f.price DESC LIMIT 15;

GROUP BY, HAVING

SQL
SELECT town, COUNT(*) as transactions,
       ROUND(AVG(price), 0) as avg_price,
       MIN(price) as min_price,
       MAX(price) as max_price
FROM raw_data
GROUP BY town
HAVING COUNT(*) >= 2
ORDER BY avg_price DESC;

Subqueries

SQL
-- Towns with above-average prices
SELECT town, price, property_type
FROM raw_data
WHERE price > (SELECT AVG(price) FROM raw_data)
ORDER BY price DESC;

CTEs (Common Table Expressions)

SQL
WITH town_stats AS (
    SELECT town, AVG(price) as avg_price, COUNT(*) as cnt
    FROM raw_data GROUP BY town
),
overall AS (
    SELECT AVG(price) as overall_avg FROM raw_data
)
SELECT t.town, ROUND(t.avg_price, 0) as avg_price, t.cnt,
       ROUND(o.overall_avg, 0) as overall_avg,
       ROUND(t.avg_price - o.overall_avg, 0) as diff
FROM town_stats t, overall o
ORDER BY diff DESC;

Window Functions

SQL
SELECT town, property_type, price,
    RANK() OVER (PARTITION BY town ORDER BY price DESC) as price_rank,
    ROUND(AVG(price) OVER (PARTITION BY town), 0) as town_avg
FROM raw_data
ORDER BY town, price_rank;
⚠️ Common SQL Mistakes
🧪 Try It Yourself

Use the SQL console above to answer these questions:

  1. Find the top 5 most expensive towns by average resale price
  2. Count transactions per flat type
  3. Write a CTE that ranks each transaction within its town
  4. Find towns where the average price exceeds $500,000
{% endblock %}