skip to content
Alvin Lucillo

Case statement in PostgreSQL

/ 1 min read

💻 Tech

In PostgreSQL, or even in SQL in general, a case statement can be used to create an inline conditional statement. For example,

select SUM(amount) total_amount,
SUM(CASE WHEN type IN ('penalties', 'deductions') THEN amount ELSE 0 END) as total_credit_amount,
from transactions

In the example above, the total_amount applies for all types; however, total_credit_amount only applies if the record type is ‘penalties’ or ‘deductions’.