SQL Data Transformation: Creating New Columns

SQL Tutorial: Creating new columns with data transformations 👇 So far in this series we've covered querying, aggregating, and grouping data. But what if the column you need doesn't exist yet? That's where data transformation comes in — creating new columns from existing ones using formulas, applied row by row. 🔹 Basic arithmetic transformation Keep all existing columns with SELECT *, then add your formula: SELECT *,   ad_spend_usd * 0.92 AS ad_spend_eur FROM campaign_spend; Every row gets its own calculated value. One formula, applied consistently across the entire dataset. 🔹 Calculating ratios Ratios divide one value by another to reveal efficiency and performance — the kind of insight raw numbers hide. SELECT *,   100 * paid_orders / paid_sessions AS pcvr,   ad_spend / paid_orders      AS cpo FROM campaign_performance ORDER BY campaign_day; 🔹 Always handle division by zero If any row has a zero denominator, your query breaks. Use NULLIF to convert zeros to NULL before dividing — NULL divided by anything returns NULL, not an error: SELECT *,   100 * paid_orders / NULLIF(paid_sessions, 0) AS pcvr,   ad_spend     / NULLIF(paid_orders, 0)  AS cpo FROM campaign_performance; NOTE: BigQuery has SAFE_DIVIDE() which does the same thing more cleanly. PostgreSQL users stick with NULLIF. 🔹 One thing most tutorials skip Ratios become unreliable with small sample sizes. A conversion rate of 50% sounds impressive — until you realise it's based on 1 order from 2 visits. One fewer order and it's 0%. The math is correct, but the insight is misleading. Always check your denominator size before drawing conclusions from a ratio. Next up: more advanced transformation techniques. #SQL #PostgreSQL #DataAnalysis #LearningInPublic

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