SQL Foundations for Data Science: Complex Queries, Joins & Aggregations

Python is fantastic for modeling, but SQL (Structured Query Language) is where real enterprise data lives. In this class, we master robust relational query techniques, dissect the internal SQL execution pipeline, and review join patterns essential for data science.

The 8-Stage Logical Query Execution Order

Writing performant SQL requires understanding how the database query planner evaluates clauses internally:

1. FROM & JOIN → 2. WHERE → 3. GROUP BY → 4. HAVING → 5. SELECT → 6. DISTINCT → 7. ORDER BY → 8. LIMIT

Notice that column aliases defined in SELECT cannot be referenced in WHERE because WHERE executes before SELECT!

Relational Joins Cheat Sheet

Join Type Output Behavior Data Science Use Case
INNER JOIN Returns records with matching keys in BOTH tables. Analyze users who have made at least one verified transaction.
LEFT JOIN All rows from Left table, matched rows from Right table (NULLs if missing). Audit user churn (find registered users where order_id IS NULL).
FULL OUTER JOIN All rows from both tables, filling NULLs wherever matches do not exist. Reconcile inventory catalogs between two newly merged company databases.
CROSS JOIN Cartesian product (every row in Table A paired with every row in Table B). Generate grid search combinations or complete date/store matrices.

Practical SQL Example: High-Value Customer Segmentation

-- Identify high-value customers with 5+ orders who spent over $1,000 in 2025
SELECT 
    u.user_id,
    u.first_name,
    u.country,
    COUNT(o.order_id) AS total_orders,
    ROUND(SUM(o.total_amount), 2) AS total_revenue,
    ROUND(AVG(o.total_amount), 2) AS avg_order_value,
    CASE 
        WHEN SUM(o.total_amount) >= 5000 THEN 'VIP Platinum'
        WHEN SUM(o.total_amount) >= 2500 THEN 'Gold Tier'
        ELSE 'Silver Tier'
    END AS customer_tier
FROM users u
INNER JOIN orders o ON u.user_id = o.user_id
WHERE o.order_status = 'COMPLETED'
  AND o.created_at >= '2025-01-01'
GROUP BY u.user_id, u.first_name, u.country
HAVING COUNT(o.order_id) >= 5 
   AND SUM(o.total_amount) >= 1000.00
ORDER BY total_revenue DESC
LIMIT 50;

University Viva & Exam Checklist

What is the output difference between COUNT(*) and COUNT(column_name)? (Answer: COUNT(*) counts all rows including those with NULLs; COUNT(column_name) counts only rows where the specified column is non-NULL).

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the true logical order of SQL query execution?

SQL is not executed in the written syntax order. The true logical execution order is: 1. FROM & JOINs, 2. WHERE (row filtering), 3. GROUP BY (bucketing), 4. HAVING (aggregate filtering), 5. SELECT (column evaluation), 6. DISTINCT, 7. ORDER BY, and 8. LIMIT / OFFSET.

Q2. What is the critical difference between WHERE and HAVING?

WHERE filters raw individual table rows BEFORE grouping occurs and cannot evaluate aggregate functions. HAVING filters grouped rows AFTER GROUP BY has aggregated results (e.g., HAVING COUNT(*) > 5).

Q3. When should I use a LEFT JOIN vs. an INNER JOIN?

Use INNER JOIN when you only want rows that have matching keys in BOTH tables. Use LEFT JOIN when you want to retain ALL rows from the primary (left) table, even if there is no matching record in the secondary table (filling missing columns with NULLs).

Q4. Why is SQL still the most sought-after data science skill?

Over 90% of enterprise business data resides in relational databases and cloud warehouses. SQL is the native tongue of data extraction. Extracting precisely aggregated data via SQL drastically reduces memory overhead in Python and R.

Q5. What causes unintended Cartesian products (row explosion) in joins?

If the joining column contains non-unique (one-to-many or many-to-many) duplicates in both tables, every matching row in Table A pairs with every matching row in Table B, exponentially multiplying output row counts and corrupting aggregate sums.

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

Advanced SQL: Window Functions & CTEs

Elevate your SQL skills with ROW_NUMBER, RANK, LAG, and CTEs.

SQL Cohort Analysis & Funnels

Build retention curves, rolling metrics, and conversion funnels in SQL.

Pandas GroupBy & Transformations

Translate SQL queries into high-performance Python DataFrame code.

DuckDB-Wasm Client-Side SQL Engine

Execute full ANSI SQL queries directly inside modern web applications.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!