Skip to main content
Documents
Basic SyntaxMath FunctionsDate FunctionsJSON FunctionsDatabasesTables & Schema ManagementString FunctionsTriggersIndexes

PostgreSQL FILTER

The `FILTER` clause in PostgreSQL is used to apply conditions to aggregate functions, allowing for more granular control over which rows are included in the aggregation. It is particularly useful for performing conditional aggregation directly within the aggregate function call.

Usage

The `FILTER` clause is utilized with aggregate functions to specify a condition that determines which rows are included in the calculation. It is written immediately after the aggregate function, enclosed in parentheses.

sql
SELECT aggregate_function(column) FILTER (WHERE condition)
FROM table_name;

In this syntax, `FILTER (WHERE condition)` ensures that only rows meeting the specified condition are considered by the aggregate function. Common aggregate functions used with `FILTER` include `SUM`, `COUNT`, `AVG`, `MIN`, and `MAX`. Additionally, the `FILTER` clause can be combined with window functions for analytical queries.

Examples

1. Basic Usage with COUNT

sql
SELECT COUNT(*) FILTER (WHERE status = 'active') AS active_count
FROM users;

This example counts only the rows in the `users` table where the `status` is 'active'.

2. Using FILTER with SUM

sql
SELECT SUM(salary) FILTER (WHERE department = 'IT') AS total_it_salary
FROM employees;

Here, the `SUM` function calculates the total salaries only for employees in the 'IT' department.

3. Combining Multiple Aggregates

sql
SELECT 
    COUNT(*) AS total_orders,
    COUNT(order_id) FILTER (WHERE status = 'completed') AS completed_orders,
    AVG(amount) FILTER (WHERE status = 'completed') AS average_completed_amount
FROM orders;

This example calculates the total number of orders, the number of completed orders, and the average amount of completed orders, all in a single query.

Tips and Best Practices

  • Use for conditional logic. Employ `FILTER` to apply conditions directly to aggregate functions, simplifying complex queries.
  • Improve readability. By using `FILTER`, you can avoid nested subqueries and maintain a cleaner query structure.
  • Combine with GROUP BY. `FILTER` can be effectively combined with `GROUP BY` for grouped conditional aggregations. For example:
sql
SELECT department, COUNT(employee_id) FILTER (WHERE status = 'active') AS active_employees
FROM employees
GROUP BY department;
  • Test conditions separately. Ensure the logic in your `FILTER` clause is correct by testing conditions independently when possible.
  • Watch performance on large datasets. While `FILTER` can simplify queries, ensure performance is optimal, especially with large datasets and complex conditions.
  • SQL standard compliance. The `FILTER` clause is part of the SQL standard, offering compatibility benefits for cross-database queries.

Common Pitfalls and Errors

  • Condition Logic Misunderstanding: Ensure that the condition in the `FILTER` clause is correctly specified to avoid unexpected results.
  • Performance Considerations: Be mindful of the potential performance impact on large datasets, and optimize where necessary.

Comparing FILTER with CASE

The `FILTER` clause differs from using `CASE` statements within aggregate functions. While `FILTER` provides a more concise and readable syntax for conditional aggregation, `CASE` offers flexibility for more complex logic. Choose `FILTER` for simpler conditions and `CASE` when more detailed logic is required.