SQL:SQL Dynamic Transactional CASE WHEN Metrics Query Logic
SQL•Conditionals

SQL Dynamic Transactional CASE WHEN Metrics Query Logic

The SQL CASE expression provides powerful conditional logic inside queries. It evaluates boolean conditions sequentially and returns a matching expression arm, enabling dynamic transactional status classification, tier mapping, and pivot aggregations without procedural stored procedures.

Syntax

CASE WHEN amount >= 1000 THEN 'ENTERPRISE' WHEN amount >= 250 THEN 'BUSINESS' ELSE 'STARTER' END AS customer_tier

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
CASE WHEN condition THEN resultExpressionEvaluates boolean predicate sequentially; returns first matching result.
ELSE default_resultFallbackDefault fallback value when no WHEN conditions evaluate to true.
ENDKeywordTerminates the conditional CASE expression.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

-- 1. Transactional ledger schema
CREATE TABLE transactions (
    tx_id INTEGER PRIMARY KEY,
    account_id TEXT,
    amount REAL,
    risk_score INTEGER
);

INSERT INTO transactions VALUES
    (101, 'acc-alpha', 1450.00, 12),
    (102, 'acc-beta',  320.50,  68),
    (103, 'acc-gamma', 45.00,   5),
    (104, 'acc-delta', 5200.00, 92);

-- 2. Multi-tier dynamic CASE WHEN transactional metrics classification
SELECT 
    tx_id,
    account_id,
    amount,
    risk_score,
    CASE 
        WHEN amount >= 1000.0 THEN 'HIGH-VALUE'
        WHEN amount >= 200.0  THEN 'STANDARD'
        ELSE 'MICRO-TX'
    END AS transaction_tier,
    CASE
        WHEN risk_score >= 80 THEN 'FLAGGED_FRAUD_REVIEW'
        WHEN risk_score >= 50 THEN 'ELEVATED_MONITOR'
        ELSE 'AUTO_CLEARED'
    END AS compliance_status
FROM transactions;
Expected Output:
tx_id  account_id  amount  risk_score  transaction_tier  compliance_status   
-----  ----------  ------  ----------  ----------------  --------------------
101    acc-alpha   1450.0  12          HIGH-VALUE        AUTO_CLEARED        
102    acc-beta    320.5   68          STANDARD          ELEVATED_MONITOR    
103    acc-gamma   45.0    5           MICRO-TX          AUTO_CLEARED        
104    acc-delta   5200.0  92          HIGH-VALUE        FLAGGED_FRAUD_REVIEW

How It Works: Step-by-Step

  • Lines 2-13: Creates transactions schema and inserts rows with varying amounts and risk scores.
  • Lines 21-25: Classifies transaction volume tiers into HIGH-VALUE, STANDARD, and MICRO-TX.
  • Lines 26-30: Applies fraud compliance decision logic based on risk_score thresholds.

Key Concepts

  • CASE expressions evaluate sequentially from top to bottom; the first truthy condition short-circuits.
  • Always supply an explicit ELSE branch, otherwise unmatched rows evaluate to NULL.
  • CASE expressions can be nested or combined inside aggregate functions (e.g. SUM(CASE WHEN status = "APPROVED" THEN 1 ELSE 0 END)) for pivot metrics.
  • Both simple CASE (CASE col WHEN val THEN ...) and searched CASE (CASE WHEN cond THEN ...) are standard ANSI SQL.

Common Mistake: Omitting the ELSE clause in a CASE expression

Without ELSE, any row that does not meet the specified WHEN criteria implicitly resolves to NULL, causing unexpected blank entries.

❌ Incorrect
SELECT CASE WHEN score > 50 THEN 'Pass' END; // Resolves to NULL for <= 50!
✅ Correct
SELECT CASE WHEN score > 50 THEN 'Pass' ELSE 'Fail' END; // Explicit fallback

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler