PostgreSQL IF statement
Mastering Conditional Logic with PostgreSQL IF Statements

Explore the various ways to implement conditional logic in PostgreSQL, from basic IF
statements in PL/pgSQL to SQL-standard CASE
expressions and their practical applications.
Conditional logic is a fundamental aspect of any programming or database system, allowing for different actions or results based on specific conditions. In PostgreSQL, while there isn't a direct IF
statement available in standard SQL queries, it's extensively used within procedural language blocks like PL/pgSQL. This article will guide you through implementing conditional logic using IF
statements in PL/pgSQL functions and procedures, as well as leveraging the SQL-standard CASE
expression for conditional results directly within your queries.
Understanding IF Statements in PL/pgSQL
PostgreSQL's procedural language, PL/pgSQL, provides a robust IF
statement construct similar to those found in other programming languages. This allows you to execute blocks of code conditionally within functions, triggers, and stored procedures. The basic syntax includes IF
, THEN
, ELSEIF
(or ELSIF
), ELSE
, and END IF;
.
CREATE OR REPLACE FUNCTION get_product_category(product_id INT) RETURNS TEXT AS $$
DECLARE
price DECIMAL;
category TEXT;
BEGIN
SELECT unit_price INTO price FROM products WHERE id = product_id;
IF price IS NULL THEN
category := 'Unknown';
ELSIF price < 10.00 THEN
category := 'Budget';
ELSIF price >= 10.00 AND price < 50.00 THEN
category := 'Standard';
ELSE
category := 'Premium';
END IF;
RETURN category;
END;
$$ LANGUAGE plpgsql;
Example of an IF-ELSIF-ELSE statement in a PL/pgSQL function.
flowchart TD A[Start Function] --> B{Fetch Product Price?} B -- Yes --> C{Price IS NULL?} C -- Yes --> D[Category: 'Unknown'] C -- No --> E{Price < 10.00?} E -- Yes --> F[Category: 'Budget'] E -- No --> G{Price >= 10.00 AND Price < 50.00?} G -- Yes --> H[Category: 'Standard'] G -- No --> I[Category: 'Premium'] D --> J[Return Category] F --> J H --> J I --> J J --> K[End Function]
Decision flow for the get_product_category
PL/pgSQL function.
IF
statements are part of PL/pgSQL, not standard SQL. You'll use them within DO
blocks, functions, or procedures, not directly in SELECT
queries.Conditional Expressions with CASE
For conditional logic directly within SQL queries (e.g., in SELECT
, WHERE
, ORDER BY
clauses), PostgreSQL uses the SQL-standard CASE
expression. The CASE
expression allows you to return different values based on specified conditions. There are two main forms: simple CASE
and searched CASE
.
Simple CASE Expression
A simple CASE
expression compares a single expression to several possible values. It's concise when you're checking for equality against a set of discrete values.
SELECT
product_name,
unit_price,
CASE unit_price
WHEN 0 THEN 'Free'
WHEN 10 THEN 'Ten Dollars'
ELSE 'Other Price'
END AS price_description
FROM products;
Using a simple CASE expression to categorize prices.
Searched CASE Expression
The searched CASE
expression is more flexible, allowing you to specify different boolean conditions for each WHEN
clause. This is equivalent to an IF-ELSIF-ELSE
structure and is generally more powerful.
SELECT
order_id,
order_date,
total_amount,
CASE
WHEN total_amount < 50.00 THEN 'Small Order'
WHEN total_amount >= 50.00 AND total_amount < 200.00 THEN 'Medium Order'
WHEN total_amount >= 200.00 THEN 'Large Order'
ELSE 'Invalid Amount'
END AS order_size
FROM orders;
Using a searched CASE expression to classify order sizes.
ELSE
clause is specified in a CASE
expression and none of the WHEN
conditions are met, the CASE
expression will return NULL
. Always consider including an ELSE
clause for clarity and to handle unexpected cases.Practical Applications and Best Practices
Conditional logic is invaluable for data transformation, reporting, and enforcing business rules. When deciding between PL/pgSQL IF
and SQL CASE
, consider the context:
- PL/pgSQL
IF
: Ideal for complex procedural logic, flow control within functions/procedures, and when you need to perform multiple statements based on a condition. - SQL
CASE
: Best for returning conditional values directly within aSELECT
statement, filtering withWHERE
, or ordering results withORDER BY
. It's generally more performant for simple conditional value assignments in queries.
-- Example: Using CASE in an UPDATE statement
UPDATE products
SET status = CASE
WHEN stock_quantity = 0 THEN 'Out of Stock'
WHEN stock_quantity < 10 THEN 'Low Stock'
ELSE 'In Stock'
END
WHERE category = 'Electronics';
Updating product status based on stock quantity using a CASE expression.