Module 2, Session 12. Defensive fallback cascades, zero-division shields, horizontal row bounds with GREATEST & LEAST, three-valued logic truth matrices, and NULL-safe equality in PostgreSQL 18.
Open in Present mode · 400 practice questions · Live class schedule · Try the playground
Jo class mein bola, yahan nukte mein likha hai.
What I said in class, written here as key points.
Defensive fallback cascades, zero-division shields, horizontal row bounds with GREATEST & LEAST, three-valued logic truth matrices, and NULL-safe equality in PostgreSQL 18 on RetailMart.
Four pillars: three-valued logic, COALESCE fallbacks, zero-division guards, and NULL-safe equality
TRUE, FALSE, UNKNOWN
IS NULL & IS NOT NULL
COALESCE(val, fallback)
NULLIF(val, sentinel)
x / NULLIF(y, 0)
NULLIF(TRIM(str), '')
IS DISTINCT FROM
COUNT(col) vs COUNT(*)
Bridging declarative conditional logic and the subtleties of three-valued truth
IS NULL, COALESCE, or IS DISTINCT FROM.-- Blacklist: suppliers 1, 2 + one blank row -- NOT IN (1, 2, NULL) returns 0 rows SELECT shipment_id, supplier_id, status FROM supply_chain.shipments WHERE supplier_id NOT IN (1, 2) ORDER BY shipment_id LIMIT 10; -- NULL kept out: 1,949 dispatches released
NOT IN list evaluates every comparison to UNKNOWN, returning zero rows. Always filter out NULLs with WHERE col IS NOT NULL or use NOT EXISTS.Every crisis in the story translates directly into an essential defensive SQL function.
COALESCE(phone, alt_phone, 'Not Provided').COALESCE(val / NULLIF(denom, 0), 0.0).col IS DISTINCT FROM 'Gold'.Click contact scenarios to watch PostgreSQL evaluate arguments from left to right.
Evaluating arbitrary argument cascades to guarantee reliable, report-ready non-null values.
COALESCE(val1, val2, ..., default)'₹ ' || price) propagates NULL: if price is NULL, the result is NULL. COALESCE ensures a clean default string before concatenation.SELECT view_id, page_url, customer_id, COALESCE( customer_id::TEXT, 'Guest' ) AS visitor FROM web_events.page_views ORDER BY view_id LIMIT 10;
Compare naive division crashes against NULLIF defensive engineering.
100 / 0 → FATAL: division by zero! Entire query aborted.
Why dividing by NULL is safe, elegant, and standard in analytical engineering.
100 / 0 raises a fatal runtime exception: division by zero. A single free promotional item (price = 0) crashes an entire enterprise report.100 / NULL evaluates to NULL without raising an exception! NULLIF(denom, 0) converts dangerous 0s to benign NULLs.COALESCE(val / NULLIF(denom, 0), 0.0). Computes the metric, shields from crashes, and supplies a business default.SELECT product_id, product_name, price, cost_price, ROUND(((price - cost_price) / NULLIF(price, 0)) * 100.0, 1) AS margin_pct, COALESCE(ROUND(((price - cost_price) / NULLIF(price, 0)) * 100.0, 1), 0.0) AS safe_margin_pct FROM products.products ORDER BY price DESC LIMIT 10;
Click boolean operators to inspect how UNKNOWN behaves under SQL logic.
Why NULL = NULL is never TRUE, and how IS DISTINCT FROM fixes change detection.
=, !=, >, <) involving NULL evaluates to UNKNOWN!WHERE clause only accepts rows where the expression evaluates strictly to TRUE. If a condition evaluates to UNKNOWN, the row is discarded silently!NULL IS NOT DISTINCT FROM NULL is TRUE, and 'Gold' IS DISTINCT FROM NULL is TRUE.SELECT (NULL = NULL) AS null_eq_null, (NULL != NULL) AS null_neq_null, (NULL IS NOT DISTINCT FROM NULL) AS distinct_null_equality, ('Active' IS DISTINCT FROM NULL) AS val_distinct_from_null LIMIT 1;
Avoid the catastrophic NOT IN (NULL) trap and inequality filter omissions.
WHERE id NOT IN (SELECT bonus_id FROM ...) when bonus_id contains even ONE NULL!id != 1 AND id != NULL. Since id != NULL is UNKNOWN, the whole expression is UNKNOWN, returning 0 rows!NOT EXISTS or filter: WHERE bonus_id IS NOT NULL.
WHERE tier != 'Gold' assuming it returns Silver, Bronze, AND NULL.NULL != 'Gold' is UNKNOWN, so PostgreSQL drops them!WHERE tier IS DISTINCT FROM 'Gold'.
col IS NULL and col IS NOT DISTINCT FROM NULL produce the exact same boolean result. Use IS NULL for clarity when testing a single literal, and IS NOT DISTINCT FROM when comparing two dynamic columns.
ORDER BY price DESC NULLS LAST.
Click evaluation scope to inspect horizontal row bounds versus vertical column aggregations.
Distinguishing row-level multi-column functions from column-level multi-row aggregations.
GREATEST(10, NULL) returns 10! NULL is skipped unless all arguments are NULL.COUNT(col), SUM, AVG, MAX, MIN. Only COUNT(*) counts every row.' ') are NOT NULL! Use NULLIF(TRIM(col), '') to convert empty text and blank spaces into clean SQL NULLs before processing.SELECT product_id, product_name, price, cost_price, GREATEST(price, cost_price) AS max_valuation, LEAST(price, cost_price) AS min_valuation, (price IS DISTINCT FROM cost_price) AS has_price_variance FROM products.products WHERE cost_price IS NOT NULL ORDER BY product_id LIMIT 10;
Five core missing data questions interviewers ask, with production-grade answers.
COALESCE is the ANSI SQL standard function supported by all major database engines (PostgreSQL, MySQL, Oracle, SQL Server, BigQuery). It accepts an arbitrary number of arguments (cascade chaining) and evaluates lazily with short-circuiting. NVL(a, b) is Oracle-specific and takes exactly 2 arguments. IFNULL(a, b) is MySQL/SQLite-specific and takes exactly 2 arguments. In modern engineering, always prefer ANSI COALESCE for portable, expressive code.Click any flashcard to flip and test your understanding of PostgreSQL 3VL rules.
Universal principles for writing resilient SQL queries and bulletproof missing data pipelines.
NULLIF(val, 0) so zero-division cleanly produces NULL instead of aborting the query.COALESCE(val / NULLIF(denom, 0), 0.0). Shields against crashes and guarantees clean, default-ready numeric metrics.NOT EXISTS (Session 26).!= drops NULL rows.= and != fail in 3VL when operands are NULL. Use IS DISTINCT FROM for safe change-data-capture and audit discrepancy checks.Complete PostgreSQL defensive function index with interactive ▶ Run links.
SELECT COALESCE(NULL, NULL, 'Fallback Value');
SELECT COALESCE('Work Phone', 'Not Provided');
SELECT NULLIF(100, 100);
SELECT NULLIF(100, 0);
SELECT 1000.0 / NULLIF(0, 0);
SELECT COALESCE(1000.0 / NULLIF(0, 0), 0.0);
SELECT (NULL = NULL) AS eq_test;
SELECT (NULL IS NOT DISTINCT FROM NULL) AS safe_eq LIMIT 1;
SELECT ('Gold' IS DISTINCT FROM NULL) AS safe_neq LIMIT 1;
SELECT GREATEST(120, 450, 85), LEAST(120, 450, 85);
SELECT GREATEST(100, NULL, 50);
SELECT NULLIF(TRIM(' '), '') AS clean_str;
Apply today's COALESCE, NULLIF, and IS DISTINCT FROM techniques in the playground, then check your counts against the ones given.
web_events.page_views, show view_id, page_url and the visitor with COALESCE(customer_id::TEXT, 'Guest'): 1,50,316 of the 5,00,000 views are guests.products.products, calculate profit margin percentage shielding against zero price: ROUND(((price - cost_price) / NULLIF(price, 0)) * 100, 2).sales.shipments, resolve the latest event date with COALESCE(delivered_date, shipped_date): 14,982 parcels fall back to shipped_date.products.products, detect products where price differs from cost_price with price IS DISTINCT FROM cost_price.products.products, compute GREATEST(price, cost_price) and LEAST(price, cost_price) for catalog valuation bounds.sales.orders, calculate discount percentage: COALESCE(ROUND((discount_amount / NULLIF(gross_total, 0)) * 100, 2), 0.00).customers.customers, convert whitespace-only strings to genuine NULLs: NULLIF(TRIM(phone), '') (RetailMart has 0 blank phones; real form data has many).Track your progress across the 59-session SQL course.
Coming next in Module 2: Compressing Lakhs of Rows into Executive Business Metrics.