File tree 2 files changed +45
-1
lines changed
2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://tinyletter.com/jbranchaud ) .
12
12
13
- _ 1134 TILs and counting..._
13
+ _ 1135 TILs and counting..._
14
14
15
15
---
16
16
@@ -622,6 +622,7 @@ _1134 TILs and counting..._
622
622
- [ Temporarily Disable Triggers] ( postgres/temporarily-disable-triggers.md )
623
623
- [ Temporary Tables] ( postgres/temporary-tables.md )
624
624
- [ Terminating A Connection] ( postgres/terminating-a-connection.md )
625
+ - [ The nullif Function] ( postgres/the-nullif-function.md )
625
626
- [ Timestamp Functions] ( postgres/timestamp-functions.md )
626
627
- [ Toggling The Pager In PSQL] ( postgres/toggling-the-pager-in-psql.md )
627
628
- [ Track psql History Separately Per Database] ( postgres/track-psql-history-separately-per-database.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments