SQL Tutorial: Complex Transformations & WITH Clause

SQL Tutorial: Complex transformations & the WITH clause 👇 Last post covered basic arithmetic transformations. This one tackles a limitation you'll hit almost immediately when you start building real calculations. 🔹 The alias-in-same-SELECT problem SQL cannot reference a column alias in the same SELECT where it's defined. This fails: SELECT *,   revenue - ad_spend - (paid_orders * avg_cost) AS ad_contribution,   100 * ad_contribution / revenue AS contribution_rate -- ERROR FROM campaign_performance; The database hasn't finished creating ad_contribution yet when it tries to use it on the next line. 🔹 The fix: WITH clause (CTEs) A Common Table Expression (CTE) breaks the calculation into named steps. The final SELECT queries from the temporary result, where the intermediate column already exists: WITH extended AS (   SELECT *,     revenue - ad_spend - (paid_orders * avg_cost) AS ad_contribution   FROM campaign_performance ) SELECT *,   100 * ad_contribution / NULLIF(revenue, 0) AS contribution_rate FROM extended; Clean, readable, no repeated formulas. 🔹 Percent of total with scalar subqueries To express each row as a % of the total, you need the SUM of the entire column — but aggregate functions collapse rows. The solution is a scalar subquery: a nested query that returns one value every row can use: SELECT *,   ROUND(     100 * revenue / NULLIF((SELECT SUM(revenue) FROM category_sales), 0),   2) AS revenue_pot FROM category_sales; 🔹 One thing that trips people up Percentages can exceed 100% when negative values exist in the data. If some rows have negative margins, they shrink the total — making profitable rows represent a larger share than expected. Always check for negatives before interpreting % metrics. Next up: filtering data with WHERE and HAVING. #SQL #PostgreSQL #DataAnalysis #LearningInPublic #TechTips

All SQL code from these posts is saved to my GitHub as I go: 🔗 https://github.com/aucampr/sql And if you want to know more about my work and experience: 🌐 https://ruanaucamp.me/

Like
Reply

To view or add a comment, sign in

Explore content categories