Skip to content

Commit a3f4d71

Browse files
committed
Add The nullif Function as a Postgres til
1 parent 673dcbf commit a3f4d71

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1134 TILs and counting..._
13+
_1135 TILs and counting..._
1414

1515
---
1616

@@ -622,6 +622,7 @@ _1134 TILs and counting..._
622622
- [Temporarily Disable Triggers](postgres/temporarily-disable-triggers.md)
623623
- [Temporary Tables](postgres/temporary-tables.md)
624624
- [Terminating A Connection](postgres/terminating-a-connection.md)
625+
- [The nullif Function](postgres/the-nullif-function.md)
625626
- [Timestamp Functions](postgres/timestamp-functions.md)
626627
- [Toggling The Pager In PSQL](postgres/toggling-the-pager-in-psql.md)
627628
- [Track psql History Separately Per Database](postgres/track-psql-history-separately-per-database.md)

postgres/the-nullif-function.md

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# The nullif Function
2+
3+
PostgreSQL, in addition to generalized case statements, includes the
4+
[`nullif`](https://www.postgresql.org/docs/current/functions-conditional.html)
5+
function. The docs describe it as a way "to perform the inversation operation
6+
of a `coalesce`".
7+
8+
Rather than resolving to some fallback value if the primary value is `null`
9+
(like `coalesce` does), it will resolve to `null` if the given values are the
10+
same.
11+
12+
```sql
13+
> select nullif(0, 0);
14+
nullif
15+
--------
16+
ø
17+
(1 row)
18+
```
19+
20+
If the values are not equal, then the first value is the result of the
21+
function.
22+
23+
```sql
24+
> select nullif(1, 0);
25+
nullif
26+
--------
27+
1
28+
(1 row)
29+
```
30+
31+
One way this can be used is in conjunction with the `coalesce` function. For
32+
instance, if I have a table of values that are either 0 or a positive number, I
33+
can coerce all the zeros to be `1` like so.
34+
35+
```sql
36+
> select coalesce(nullif(0, 0), 1);
37+
coalesce
38+
----------
39+
1
40+
(1 row)
41+
```
42+
43+
h/t [Ian Jones](https://twitter.com/_jonesian)

0 commit comments

Comments
 (0)