IF

Conditional execution based on boolean expressions.

Category: conditional

Syntax

IF <condition> THEN
  <statements>
[ELSIF <condition> THEN
  <statements>]
[ELSE
  <statements>]
END IF;

Description

## Overview The IF statement provides conditional branching in PL/pgSQL. It evaluates conditions in order (IF, then each ELSIF) and executes the first branch whose condition is true. The optional ELSE branch executes when no prior condition matched. ## Behavior - Each condition is evaluated as a DataFusion expression that must return a boolean ScalarValue. Only `Boolean(Some(true))` triggers the branch; `Boolean(Some(false))`, `Boolean(None)` (NULL), and any non-boolean value do not. - Conditions are evaluated lazily: once a branch matches, no subsequent ELSIF or ELSE conditions are evaluated. - Any number of ELSIF clauses is supported. They are stored internally as a vector of (Expression, Vec<Statement>) pairs and tested in order. - Each branch can contain any statements, including nested IF blocks, loops, SQL statements, and sub-blocks. ## Differences from PostgreSQL - Behavior is consistent with PostgreSQL PL/pgSQL. NULL conditions are treated as false (the branch is skipped), matching standard three-valued logic.

Parameters

NameTypeDescription
conditionProvide a boolean expression. Only the branch whose condition evaluates to true executes.

Examples

DO $$
DECLARE
  x INT := 75;
BEGIN
  IF x > 100 THEN
    PRINT 'high';
  ELSIF x > 50 THEN
    PRINT 'medium';
  ELSE
    PRINT 'low';
  END IF;
END;
$$;
DO $$
DECLARE
  row_count INT;
BEGIN
  SELECT count(*) INTO row_count FROM orders WHERE status = 'pending';
  IF row_count = 0 THEN
    PRINT 'No pending orders';
  ELSIF row_count < 10 THEN
    PRINT 'Few pending orders:', row_count;
  ELSE
    RAISE WARNING 'High backlog: % pending orders', row_count;
  END IF;
END;
$$;
DO $$
DECLARE
  table_exists BOOLEAN;
BEGIN
  SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'audit_log') INTO table_exists;
  IF NOT table_exists THEN
    EXECUTE 'CREATE TABLE audit_log (id BIGINT, event TEXT, ts TIMESTAMP)';
    PRINT 'audit_log created';
  END IF;
END;
$$;
DO $$
DECLARE
  val TEXT;
BEGIN
  val := NULL;
  IF val IS NULL THEN
    PRINT 'Value is NULL';
  ELSIF val = '' THEN
    PRINT 'Value is empty string';
  ELSE
    PRINT 'Value:', val;
  END IF;
END;
$$;

Pitfalls

See Also

Open in interactive docs →   DeltaForge home →