

 从补丁 198 开始，Amazon Redshift 将不再支持创建新的 Python UDF。现有的 Python UDF 将继续正常运行至 2026 年 6 月 30 日。有关更多信息，请参阅[博客文章](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/)。

# NULLIF 函数
<a name="r_NULLIF_function"></a>

## 语法
<a name="r_NULLIF_function-synopsis"></a>

NULLIF 表达式比较两个参数并在两个参数相等时返回 null。如果两个参数不相等，则返回第一个参数。此表达式为 NVL 或 COALESCE 表达式的反向表达式。

```
NULLIF ( expression1, expression2 )
```

## 参数
<a name="r_NULLIF_function-arguments"></a>

 *expression1，expression2*   
所比较的目标列或表达式。返回类型与第一个表达式的类型相同。NULLIF 结果的默认列名称为第一个表达式的列名称。

## 示例
<a name="r_NULLIF_function-examples"></a>

在以下示例中，查询返回字符串 `first`，因为参数不相等。

```
SELECT NULLIF('first', 'second');

case
-------
first
```

在以下示例中，查询返回字符串 `NULL`，因为字符串文本参数相等。

```
SELECT NULLIF('first', 'first');

case
-------
NULL
```

在以下示例中，查询返回 `1`，因为整数参数不相等。

```
SELECT NULLIF(1, 2);

case
-------
1
```

在以下示例中，查询返回 `NULL`，因为整数参数相等。

```
SELECT NULLIF(1, 1);

case
-------
NULL
```

在以下示例中，查询在 LISTID 和 SALESID 值匹配时返回 null：

```
select nullif(listid,salesid), salesid
from sales where salesid<10 order by 1, 2 desc;

listid  | salesid
--------+---------
     4  |       2
     5  |       4
     5  |       3
     6  |       5
     10 |       9
     10 |       8
     10 |       7
     10 |       6
        |       1
(9 rows)
```

您可以使用 NULLIF 来确保始终将空字符串返回为 null。在以下示例中，NULLIF 表达式返回一个 null 值或一个包含至少一个字符的字符串。

```
insert into category
values(0,'','Special','Special');

select nullif(catgroup,'') from category
where catdesc='Special';

catgroup
----------
null
(1 row)
```

NULLIF 忽略尾随空格。如果一个字符串不为空但包含空格，则 NULLIF 仍返回 null：

```
create table nulliftest(c1 char(2), c2 char(2));

insert into nulliftest values ('a','a ');

insert into nulliftest values ('b','b');


select nullif(c1,c2) from nulliftest;
c1
------
null
null
(2 rows)
```