Tutorials  /  Databases

PostgreSQL CASE Statement Tutorial with Examples

Ccentron Redaktion · August 2025 ·5 min read ·Databases, Tutorial

The CASE expression in PostgreSQL helps apply logic within SQL queries by returning values based on conditional evaluation. It’s particularly valuable when classifying data dynamically—such as assigning grades or setting labels according to thresholds.

This guide shows how to leverage the CASE statement in PostgreSQL to categorize data from a database. You'll create a test setup with student and score tables and apply CASE logic to compute grades based on score intervals.

Requirements

Before proceeding, ensure the following setup:

  • A running PostgreSQL instance with connection credentials.
  • A Linux machine to act as your client.
  • SSH access to the server.
  • A sudo-enabled user (non-root).
  • The psql client installed.
DB

Matching infrastructure at centron

Databases need care in production: centron can take over updates, backups and monitoring – from a single instance to a full cluster. Explore managed clusters →

How PostgreSQL CASE Works

The CASE keyword in PostgreSQL is a logical operator used inside SQL statements. It checks multiple conditions in sequence and yields a result based on the first matching condition. This allows flexible data manipulation directly within your queries.

A CASE expression typically contains the following parts:

  • CASE: Initiates the logic block.
  • WHEN: Declares a condition to check.
  • THEN: Defines the output for a true condition.
  • END: Closes the expression.

Example CASE syntax within a SELECT statement:

SQL
SELECT 
    column1,
    column2,
    CASE 
        WHEN condition1 THEN 'Value A'
        WHEN condition2 THEN 'Value B'
        ELSE 'Default Value'
    END AS result_column
FROM your_table;

Valid conditional operators include:

  • =: Equals
  • <: Less than
  • <=: Less than or equal to
  • >: Greater than
  • >=: Greater than or equal to

Setting Up the Example Database

To illustrate the CASE feature, begin by creating a simple schema with two tables: students and marks.

Log Into the PostgreSQL Server

Connect via the psql client using your credentials:

Console
$ psql -h <host> -p <port> -U <username> defaultdb

Create the school Database

JavaScript
defaultdb=> CREATE DATABASE school;

Connect to the New Database

JavaScript
defaultdb=> \c school;

Define the students Table

Set up a table to store basic student info:

JavaScript
school=> CREATE TABLE students (
            student_id SERIAL PRIMARY KEY,
            first_name VARCHAR(50),
            last_name VARCHAR(50)
        );

Add Sample Student Data

JavaScript
school=> INSERT INTO students (first_name, last_name) VALUES
          ('JOHN', 'DOE'),
          ('JANE', 'SMITH'),
          ('PETER', 'HENRY'),
          ('MARY', 'ANN'),
          ('JESSICA', 'WILLIAMS'),
          ('BOB', 'JAMES'),
          ('ESTHER', 'CHLOE');

Verify Student Records

JavaScript
school=> SELECT student_id, first_name, last_name FROM students;

Expected output:

 student_id | first_name | last_name
------------+------------+-----------
        1   | JOHN       | DOE
        2   | JANE       | SMITH
        3   | PETER      | HENRY
        4   | MARY       | ANN
        5   | JESSICA    | WILLIAMS
        6   | BOB        | JAMES
        7   | ESTHER     | CHLOE
(7 rows)

Create the marks Table

Define a table to hold test scores linked to students.

JavaScript
school=> CREATE TABLE marks (
            score_id SERIAL PRIMARY KEY,
            student_id INT,
            score INT
        );

Insert Sample Score Data

JavaScript
school=> INSERT INTO marks (student_id, score) VALUES
          (1, 85),
          (2, 39),
          (3, 70),
          (4, 55),
          (5, 0),
          (6, 41),
          (7, 32);

Check Score Records

JavaScript
school=> SELECT score_id, student_id, score FROM marks;

Expected output:

 score_id | student_id | score
----------+------------+-------
        1 |          1 |    85
        2 |          2 |    39
        3 |          3 |    70
        4 |          4 |    55
        5 |          5 |     0
        6 |          6 |    41
        7 |          7 |    32
(7 rows)

Apply the CASE Expression to Assign Grades

The CASE expression can dynamically determine each student's grade based on their score. By joining the students and marks tables, you can produce a report that includes the student's name, their score, and a calculated grade.

Execute the following SQL command to achieve this:

JavaScript
school=> SELECT
             students.student_id,
             students.first_name,
             students.last_name,
             marks.score,
             CASE
                 WHEN marks.score >= 75 THEN 'Distinction'
                 WHEN marks.score >= 70 THEN 'Credit'
                 WHEN marks.score >= 40 THEN 'Pass'
                 ELSE 'Fail'
             END AS grade
         FROM marks
         LEFT JOIN students ON marks.student_id = students.student_id;

This SQL query uses a LEFT JOIN to connect each record in the marks table with its matching entry in the students table. The CASE logic reviews the score field and assigns grades based on these rules:

  • Distinction for scores of 75 or more
  • Credit for scores ranging from 70 to 74
  • Pass for scores between 40 and 69
  • Fail for scores below 40

Expected result:

 student_id | first_name | last_name | score |    grade
------------+------------+-----------+-------+-------------
          1 | JOHN       | DOE       |    85 | Distinction
          2 | JANE       | SMITH     |    39 | Fail
          3 | PETER      | HENRY     |    70 | Credit
          4 | MARY       | ANN       |    55 | Pass
          5 | JESSICA    | WILLIAMS  |     0 | Fail
          6 | BOB        | JAMES     |    41 | Pass
          7 | ESTHER     | CHLOE     |    32 | Fail
(7 rows)

This use case highlights how CASE brings clear and structured conditional behavior to SQL queries. It improves both readability and maintainability when applying rules directly within your SELECT logic.

Final Thoughts

In this walkthrough, you set up a sample PostgreSQL environment and implemented the CASE statement to categorize student scores. This technique simplifies SQL for tasks such as grading and decision-based transformations. For even more complex requirements, consider alternatives like mapping tables, procedural logic using IF, or intelligent solutions using technologies like pgvector for semantic filtering. To go deeper, refer to PostgreSQL’s official documentation on conditional expressions.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Databases
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren