A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/mastering-postgresql-case-statement.php below:

Website Navigation


Comprehensive Guide to PostgreSQL CASE Statement

Comprehensive Guide to PostgreSQL CASE StatementLast update on December 28 2024 13:05:10 (UTC/GMT +8 hours)

Using the CASE Statement in PostgreSQL

The CASE statement in PostgreSQL allows for conditional logic within SQL queries. It operates similarly to IF-THEN-ELSE statements in programming languages, enabling dynamic decision-making in queries. This guide covers the syntax, examples, and practical use cases for the CASE statement.

Syntax of CASE Statement

The CASE statement can be used in two forms:

1. Simple CASE: Compares an expression to a set of values.

CASE expression
    WHEN value1 THEN result1
    WHEN value2 THEN result2
    ...
    ELSE default_result
END

2. Searched CASE: Evaluates boolean expressions.

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
    ELSE default_result
END

Example 1: Simple CASE in a SELECT Query

Scenario: Assign labels to employee salary ranges.

Code:

-- Select employee names and assign salary ranges
SELECT 
    name,
    salary,
    CASE
        WHEN salary < 3000 THEN 'Low'
        WHEN salary BETWEEN 3000 AND 7000 THEN 'Medium'
        ELSE 'High'
    END AS salary_range
FROM employees;

Explanation:

Example 2: Searched CASE in a WHERE Clause

Scenario: Filter employees based on dynamic criteria.

Code:

-- Filter employees based on a dynamic salary range
SELECT *
FROM employees
WHERE 
    CASE
        WHEN department = 'HR' THEN salary > 4000
        ELSE salary > 3000
    END;

Explanation:

Example 3: Using CASE in UPDATE

Scenario: Update employee bonuses based on performance ratings.

Code:

-- Update bonus amounts based on ratings
UPDATE employees
SET bonus = 
    CASE
        WHEN performance_rating = 'Excellent' THEN 1000
        WHEN performance_rating = 'Good' THEN 500
        ELSE 100
    END;

Explanation:

Advanced Example: Nested CASE Statements

Scenario: Determine employee rank based on multiple criteria.

Code:

-- Assign ranks based on salary and experience
SELECT 
    name,
    salary,
    experience,
    CASE
        WHEN salary > 7000 THEN 
            CASE
                WHEN experience > 5 THEN 'Senior'
                ELSE 'Mid-Level'
            END
        ELSE 'Junior'
    END AS rank
FROM employees;

Explanation:

Practical Applications of CASE

Best Practices

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4