Postgres Conditionals: How to Use Nullif
How to use the "nullif" statement in PostgreSQL. This episode is brought to you by Hashrocket, expert consultants in PostgreSQL - learn more at https://hashrocket.com and www.pgcasts.com
Transcript:
Hey everyone, today we're going to explore the "nullif" statement in Postgres.
The nullif statement in Postgres accepts two arguments, and returns null if the two arguments are equal, otherwise returns the first argument.
Let's take a look at how this works.
For this example, I have a table called posts with a few entries.
```sql
select * from posts;
```
If we want to remove blank values from our short_description column when reading from the table, we can use the nullif statement, passing as our first argument short_description, followed by an empty string as our second argument.
```sql
select nullif(short_description, '') as short_description from posts;
```
As you can see from the output, our row where short_description wasn't blank returned the short_description. However, our row with the blank short_description now returns null instead of the empty string.
The nullif statement can be very helpful when used in conjunction with coalesce statements. For example, if we wanted to read from our table and return short_description if present, otherwise description:
```sql
select coalesce(short_description, description) as display_description from posts;
```
We can see that the empty string short_description does not evaluate to null in the coalesce statement, and so we have blank values in our output.
To resolve this, we can use the nullif statement in conjunction with the coalesce, using it as the first argument to the coalesce, and passing it our short description, followed by an empty string.
```sql
select coalesce(nullif(short_description, ''), description) as display_description from posts;
```
From the output, we can see now that both of our rows have a display description.
Thanks for watching!
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Postgres Conditionals: How to Use Nullif», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.