Skip to content

Commit

Permalink
Publish post about the FILTER clause
Browse files Browse the repository at this point in the history
  • Loading branch information
yen223 committed Nov 10, 2024
1 parent 700a44e commit 8d15dc1
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions articles/til-filter-clause.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
title: "TIL: The FILTER clause in SQL"
slug: "til-filter-clause"
date: "2024-11-10"
published: true
tags:
- TIL
- Postgres
- SQL
description: "A useful SQL keyword that I didn't know about until recently."
---

_( H/T [@winand.at](https://bsky.app/profile/winand.at/post/3lagizjuo4e2y) )_

In SQL, if you wanted to perform two or more aggregations with different filters, you might be able to use the `FILTER` clause.

```sql
SELECT
count(*) as user_count,
count(*) filter (where verified = true) as verified_user_count
FROM users;
```

is the equivalent of:

```sql
SELECT
count(*) as user_count,
sum(case when verified = true then 1 else 0 end) as verified_user_count
FROM users;
```

except that a) it reads more naturally, and b) you don't need to write a complicated `case` expression.

`FILTER` is supported in Postgres 9.4 and above, and in sqlite. It is unfortunately not widely supported in other databases.

0 comments on commit 8d15dc1

Please sign in to comment.