PostgreSQL ANY,ALL & CASE


Using ANY in PostgreSQL

The ANY keyword lets you compare a value against a list or a result from a subquery. The condition is true if the value matches at least one item from the set.

Think of it like this:

"Is this value equal to any one in the group?"

Example:

SELECT * FROM products   
WHERE price = ANY (SELECT price FROM discounted_items); 

This retrieves products where the price is found in the discounted list


Using ALL in PostgreSQL

ALL is the opposite of ANY. The condition is true only if it matches every single value in the list.

In simple terms:

"Is this value valid compared to all others?"

Example:

SELECT * FROM suppliers   
WHERE rating >= ALL (SELECT rating FROM suppliers WHERE country = 'India'); 

This returns suppliers with the highest rating, equal to or above everyone from India.


Using CASE in PostgreSQL

The CASE expression works like a flexible "if-then" block inside SQL. It helps you add logic and return different outputs based on certain conditions.

Imagine it like a decision-making chain.

Example:

SELECT name,     
   CASE       
      WHEN age < 18 THEN 'Minor'       
      WHEN age >= 18 AND age < 60 THEN 'Adult'       
      ELSE 'Senior'     
    END AS category   
FROM people; 

This shows each person’s name and labels them based on their age group.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand POSTGRESQL Tutorial visually:

What You'll Learn:
  • 📌 How to use CASE - Postgresql
  • 📌 Postgres Conditionals: How to Use Case
Previous Next