

 从补丁 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/)。

# 条件
<a name="r_conditions"></a>

**Topics**
+ [语法](#r_conditions-synopsis)
+ [比较条件](r_comparison_condition.md)
+ [逻辑条件](r_logical_condition.md)
+ [模式匹配条件](pattern-matching-conditions.md)
+ [BETWEEN 范围条件](r_range_condition.md)
+ [Null 条件](r_null_condition.md)
+ [EXISTS 条件](r_exists_condition.md)
+ [IN 条件](r_in_condition.md)

 条件是包含一个或多个表达式和逻辑运算符的语句，计算结果为 true、false 或 unknown。条件有时也称为“谓词”。

**注意**  
所有字符串比较和 LIKE 模式匹配项均区分大小写。例如，“A”和“a”不匹配。但是，您可通过使用 ILIKE 谓词执行不区分大小写的模式匹配。

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

```
comparison_condition
| logical_condition
| range_condition
| pattern_matching_condition
| null_condition
| EXISTS_condition
| IN_condition
```

# 比较条件
<a name="r_comparison_condition"></a>

比较条件阐明两个值之间的逻辑关系。所有比较条件都是具有布尔值返回类型的二进制运算符。Amazon Redshift 支持下表中描述的比较运算符：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/r_comparison_condition.html)

## 使用说明
<a name="r_comparison_condition_usage_notes"></a>

= ANY \$1 SOME   
ANY 和 SOME 关键字与 *IN* 条件同义，当比较操作相对于可返回一个或多个值的子查询所返回的至少一个值为 true 时，将返回 true。对于 ANY 和 SOME，Amazon Redshift 仅支持 =（等于）条件。不支持不相等条件。  
不支持 ALL 谓词。

<> ALL  
ALL 关键字与 NOT IN（请参阅 [IN 条件](r_in_condition.md) 条件）同义并在表达式未包含在子查询的结果中时返回 true。对于 ALL，Amazon Redshift 仅支持 <> 或 \$1=（不等于）条件。不支持其他比较条件。

IS TRUE/FALSE/UNKNOWN  
非零值等于 TRUE，0 等于 FALSE，null 等于 UNKNOWN。请参阅[布尔值类型HLLSKETCH 类型](r_Boolean_type.md)数据类型。

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

下面是比较条件的一些简单示例：

```
a = 5
a < b
min(x) >= 5
qtysold = any (select qtysold from sales where dateid = 1882
```

以下查询返回 VENUE 表中座位数超过 10000 的场地：

```
select venueid, venuename, venueseats from venue
where venueseats > 10000
order by venueseats desc;

venueid |           venuename            | venueseats
---------+--------------------------------+------------
83 | FedExField                     |      91704
 6 | New York Giants Stadium        |      80242
79 | Arrowhead Stadium              |      79451
78 | INVESCO Field                  |      76125
69 | Dolphin Stadium                |      74916
67 | Ralph Wilson Stadium           |      73967
76 | Jacksonville Municipal Stadium |      73800
89 | Bank of America Stadium        |      73298
72 | Cleveland Browns Stadium       |      73200
86 | Lambeau Field                  |      72922
...
(57 rows)
```

此示例从 USERS 表中选择喜欢摇滚音乐的用户 (USERID)：

```
select userid from users where likerock = 't' order by 1 limit 5;

userid
--------
3
5
6
13
16
(5 rows)
```

此示例从 USERS 表中选择不清楚是否喜欢摇滚音乐的用户 (USERID)：

```
select firstname, lastname, likerock
from users
where likerock is unknown
order by userid limit 10;

firstname | lastname | likerock
----------+----------+----------
Rafael    | Taylor   |
Vladimir  | Humphrey |
Barry     | Roy      |
Tamekah   | Juarez   |
Mufutau   | Watkins  |
Naida     | Calderon |
Anika     | Huff     |
Bruce     | Beck     |
Mallory   | Farrell  |
Scarlett  | Mayer    |
(10 rows
```

## 具有 TIME 列的示例
<a name="r_comparison_condition-examples-time"></a>

下面的示例表 TIME\$1TEST 具有一个列 TIME\$1VAL（类型 TIME），其中插入了三个值。

```
select time_val from time_test;
            
time_val
---------------------
20:00:00
00:00:00.5550
00:58:00
```

以下示例从每个 timetz\$1val 中提取小时数。

```
select time_val from time_test where time_val < '3:00';
   time_val
---------------
 00:00:00.5550
 00:58:00
```

以下示例比较两种时间文本。

```
select time '18:25:33.123456' = time '18:25:33.123456';
 ?column?
----------
 t
```

## 具有 TIMETZ 列的示例
<a name="r_comparison_condition-examples-timetz"></a>

下面的示例表 TIMETZ\$1TEST 具有一个列 TIMETZ\$1VAL（类型 TIMETZ），其中插入了三个值。

```
select timetz_val from timetz_test;
            
timetz_val
------------------
04:00:00+00
00:00:00.5550+00
05:58:00+00
```

下面的示例仅选择小于 `3:00:00 UTC` 的 TIMETZ 值。将值转换为 UTC 后进行比较。

```
select timetz_val from timetz_test where timetz_val < '3:00:00 UTC';
                  
   timetz_val
---------------
 00:00:00.5550+00
```

以下示例比较两种 TIMETZ 文本。比较时忽略时区。

```
select time '18:25:33.123456 PST' < time '19:25:33.123456 EST';
                  
 ?column?
----------
 t
```

# 逻辑条件
<a name="r_logical_condition"></a>

逻辑条件组合两个条件的结果以生成一个结果。所有逻辑条件都是具有布尔值返回类型的二进制运算符。

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

```
expression
{ AND | OR }
expression
NOT expression
```

逻辑条件使用具有三个值的布尔逻辑，其中 null 值表示未知关系。下表描述逻辑条件的结果，其中 `E1` 和 `E2` 表示表达式：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/r_logical_condition.html)

NOT 运算符先于 AND 计算，而 AND 运算符先于 OR 运算符计算。使用的任何圆括号可优先于此默认计算顺序。

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

以下示例将返回 USERS 表中用户同时喜欢拉斯维加斯和运动的 USERID 和 USERNAME：

```
select userid, username from users
where likevegas = 1 and likesports = 1
order by userid;

userid | username
--------+----------
1 | JSG99FHE
67 | TWU10MZT
87 | DUF19VXU
92 | HYP36WEQ
109 | FPL38HZK
120 | DMJ24GUZ
123 | QZR22XGQ
130 | ZQC82ALK
133 | LBN45WCH
144 | UCX04JKN
165 | TEY68OEB
169 | AYQ83HGO
184 | TVX65AZX
...
(2128 rows)
```

下一个示例将返回 USERS 表中用户喜欢拉斯维加斯或运动或同时喜欢这二者的 USERID 和 USERNAME。此查询将返回上例中的所有输出以及只喜欢拉斯维加斯或运动的用户。

```
select userid, username from users
where likevegas = 1 or likesports = 1
order by userid;

userid | username
--------+----------
1 | JSG99FHE
2 | PGL08LJI
3 | IFT66TXU
5 | AEB55QTM
6 | NDQ15VBM
9 | MSD36KVR
10 | WKW41AIW
13 | QTF33MCG
15 | OWU78MTR
16 | ZMG93CDD
22 | RHT62AGI
27 | KOY02CVE
29 | HUH27PKK
...
(18968 rows)
```

以下查询使用圆括号将 `OR` 条件括起来以查找纽约或加利福尼亚演出过 Macbeth 的场地：

```
select distinct venuename, venuecity
from venue join event on venue.venueid=event.venueid
where (venuestate = 'NY' or venuestate = 'CA') and eventname='Macbeth'
order by 2,1;

venuename                |   venuecity
----------------------------------------+---------------
Geffen Playhouse                       | Los Angeles
Greek Theatre                          | Los Angeles
Royce Hall                             | Los Angeles
American Airlines Theatre              | New York City
August Wilson Theatre                  | New York City
Belasco Theatre                        | New York City
Bernard B. Jacobs Theatre              | New York City
...
```

删除此示例中的圆括号将更改逻辑和查询的结果。

以下示例使用 `NOT` 运算符：

```
select * from category
where not catid=1
order by 1;

catid | catgroup |  catname  |                  catdesc
-------+----------+-----------+--------------------------------------------
2 | Sports   | NHL       | National Hockey League
3 | Sports   | NFL       | National Football League
4 | Sports   | NBA       | National Basketball Association
5 | Sports   | MLS       | Major League Soccer
...
```

以下示例使用一个 `NOT` 条件并后跟一个 `AND` 条件：

```
select * from category
where (not catid=1) and catgroup='Sports'
order by catid;

catid | catgroup | catname |             catdesc
-------+----------+---------+---------------------------------
2 | Sports   | NHL     | National Hockey League
3 | Sports   | NFL     | National Football League
4 | Sports   | NBA     | National Basketball Association
5 | Sports   | MLS     | Major League Soccer
(4 rows)
```

# 模式匹配条件
<a name="pattern-matching-conditions"></a>

**Topics**
+ [LIKE](r_patternmatching_condition_like.md)
+ [SIMILAR TO](pattern-matching-conditions-similar-to.md)
+ [POSIX 运算符](pattern-matching-conditions-posix.md)

模式匹配运算符针对搜索条件表达式中指定的模式搜索字符串，然后根据是否找到匹配项来返回 true 或 false。Amazon Redshift 使用三种模式匹配方法：
+ LIKE 表达式

  LIKE 运算符将字符串表达式（如列名称）与使用通配符 `%`（百分比）和 `_`（下划线）的模式进行比较。LIKE 模式匹配始终涵盖整个字符串。LIKE 执行区分大小写的匹配，而 ILIKE 执行不区分大小写的匹配。
+ SIMILAR TO 正则表达式

  SIMILAR TO 运算符使用 SQL 标准正则表达式模式来匹配字符串表达式，该模式可包含一组模式匹配元字符，其中包括 LIKE 运算符支持的两个元字符。SIMILAR TO 匹配整个字符串并且执行区分大小写的匹配。
+ POSIX 样式的正则表达式 

  与 LIKE 和 SIMILAR TO 运算符相比，POSIX 正则表达式提供了更强大的模式匹配手段。POSIX 正则表达式模式可与字符串的任何部分匹配，并执行区分大小写的匹配。

使用 SIMILAR TO 或 POSIX 运算符的正则表达式匹配的计算成本高昂。我们建议尽可能使用 LIKE，尤其是在处理非常多的行时。例如，下列查询的功能相同，但使用 LIKE 的查询相比于使用正则表达式的查询的运行速度快若干倍：

```
select count(*) from event where eventname SIMILAR TO '%(Ring|Die)%'; 
select count(*) from event where eventname LIKE '%Ring%' OR eventname LIKE '%Die%';
```

# LIKE
<a name="r_patternmatching_condition_like"></a>

LIKE 运算符将字符串表达式（如列名称）与使用通配符 %（百分比）和 \$1（下划线）的模式进行比较。LIKE 模式匹配始终涵盖整个字符串。若要匹配字符串中任意位置的序列，模式必须以百分比符号开始和结尾。

LIKE 区分大小写；ILIKE 不区分大小写。

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

```
expression [ NOT ] LIKE | ILIKE pattern [ ESCAPE 'escape_char' ]
```

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

 *expression*   
有效的 UTF-8 字符表达式（如列名称）。

LIKE \$1 ILIKE   
LIKE 执行区分大小写的模式匹配。ILIKE 对单字节 UTF-8 (ASCII) 字符执行不区分大小写的模式匹配。要为多字节字符执行不区分大小写的模式匹配，请将 *expression* 上的 [LOWER](r_LOWER.md) 函数和带有 LIKE 函数的 *pattern* 一起使用。  
与比较谓词（例如 = 和 <>）相反，LIKE 和 ILIKE 谓词并不会隐式忽略尾随空格。要忽略尾随空格，请使用 RTRIM 或者将 CHAR 列显式强制转换为 VARCHAR。  
`~~` 运算符等同于 LIKE，而 `~~*` 等同于 ILIKE。此外，`!~~` 和 `!~~*` 运算符等同于 NOT LIKE 和 NOT ILIKE。

 *pattern*   
具有要匹配的模式的有效的 UTF-8 字符表达式。

 *escape\$1char*   
将对模式中的元字符进行转义的字符表达式。默认为两个反斜杠 ('\$1\$1')。

如果 *pattern* 不包含元字符，则模式仅表示字符串本身；在此情况下，LIKE 的行为与等于运算符相同。

其中一个字符表达式可以是 CHAR 或 VARCHAR 数据类型。如果它们不同，Amazon Redshift 会将 *pattern* 转换为 *expression* 的数据类型。

LIKE 支持下列模式匹配元字符：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/r_patternmatching_condition_like.html)

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

下表显示使用 LIKE 的模式匹配的示例：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/r_patternmatching_condition_like.html)

以下示例查找名称以“E”开头的所有城市：

```
select distinct city from users
where city like 'E%' order by city;
city
---------------
East Hartford
East Lansing
East Rutherford
East St. Louis
Easthampton
Easton
Eatontown
Eau Claire
...
```

以下示例查找姓中包含“ten”的用户：

```
select distinct lastname from users
where lastname like '%ten%' order by lastname;
lastname
-------------
Christensen
Wooten
...
```

以下示例演示如何匹配多个模式。

```
select distinct lastname from tickit.users
where lastname like 'Chris%' or lastname like '%Wooten' order by lastname;
lastname
-------------
Christensen
Christian
Wooten
...
```

以下示例查找第三和第四个字符为“ea”的城市。此命令使用 ILIKE 来演示不区分大小写的匹配：

```
select distinct city from users where city ilike '__EA%' order by city;
city
-------------
Brea
Clearwater
Great Falls
Ocean City
Olean
Wheaton
(6 rows)
```

以下示例使用默认转义字符串（\$1\$1）搜索包含“start\$1”（文本 `start` 后跟下划线 `_`)的字符串：

```
select tablename, "column" from pg_table_def 
where "column" like '%start\\_%'
limit 5;

     tablename     |    column
-------------------+---------------
 stl_s3client      | start_time
 stl_tr_conflict   | xact_start_ts
 stl_undone        | undo_start_ts
 stl_unload_log    | start_time
 stl_vacuum_detail | start_row
(5 rows)
```

以下示例指定“^”作为转义字符，然后使用该转义字符搜索包含“start\$1”（文本 `start` 后跟下划线 `_`)的字符串：

```
select tablename, "column" from pg_table_def 
where "column" like '%start^_%' escape '^' 
limit 5;

     tablename     |    column
-------------------+---------------
 stl_s3client      | start_time
 stl_tr_conflict   | xact_start_ts
 stl_undone        | undo_start_ts
 stl_unload_log    | start_time
 stl_vacuum_detail | start_row
(5 rows)
```

以下示例使用 `~~*` 运算符对以“Ag”开头的城市进行不区分大小写（ILIKE）的搜索。

```
select distinct city from users where city ~~* 'Ag%' order by city;
                   
city
------------
Agat	
Agawam	
Agoura Hills	
Aguadilla
```

# SIMILAR TO
<a name="pattern-matching-conditions-similar-to"></a>

SIMILAR TO 运算符使用 SQL 标准正则表达式模式来匹配字符串表达式（如列名称）。SQL 正则表达式可包含一组模式匹配元字符，包括 [LIKE](r_patternmatching_condition_like.md) 运算符支持的两个元字符。

仅当模式与整个字符串匹配时，SIMILAR TO 运算符才会返回 true，这与 POSIX 正则表达式的行为不同（其中的模式可与字符串的任何部分匹配）。

SIMILAR TO 执行区分大小写的匹配。

**注意**  
使用 SIMILAR TO 的正则表达式匹配的计算成本高昂。我们建议尽可能使用 LIKE，尤其是在处理非常多的行时。例如，下列查询的功能相同，但使用 LIKE 的查询相比于使用正则表达式的查询的运行速度快若干倍：  

```
select count(*) from event where eventname SIMILAR TO '%(Ring|Die)%'; 
select count(*) from event where eventname LIKE '%Ring%' OR eventname LIKE '%Die%';
```

## 语法
<a name="pattern-matching-conditions-similar-to-synopsis"></a>

```
expression [ NOT ] SIMILAR TO pattern [ ESCAPE 'escape_char' ]
```

## 参数
<a name="pattern-matching-conditions-similar-to-arguments"></a>

 *expression*   
有效的 UTF-8 字符表达式（如列名称）。

SIMILAR TO  
SIMILAR TO 对 *expression* 中的整个字符串执行区分大小写的模式匹配。

 *pattern*   
有效的 UTF-8 字符表达式，表示 SQL 标准正则表达式模式。

 *escape\$1char*   
将对模式中的元字符进行转义的字符表达式。默认为两个反斜杠 ('\$1\$1')。

如果 *pattern* 不包含元字符，则模式仅表示字符串本身。

其中一个字符表达式可以是 CHAR 或 VARCHAR 数据类型。如果它们不同，Amazon Redshift 会将 *pattern* 转换为 *expression* 的数据类型。

SIMILAR TO 支持下列模式匹配元字符：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/pattern-matching-conditions-similar-to.html)

## 示例
<a name="pattern-matching-conditions-similar-to-examples"></a>

下表显示了使用 SIMILAR TO 的模式匹配的示例：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/pattern-matching-conditions-similar-to.html)

以下示例查找名称包含“E”或“H”的城市：

```
SELECT DISTINCT city FROM users
WHERE city SIMILAR TO '%E%|%H%' ORDER BY city LIMIT 5;

      city
-----------------
 Agoura Hills
 Auburn Hills
 Benton Harbor
 Beverly Hills
 Chicago Heights
```

以下示例使用默认转义字符串（“`\\`”）搜索包含“`_`”的字符串：

```
SELECT tablename, "column" FROM pg_table_def
WHERE "column" SIMILAR TO '%start\\_%'
ORDER BY tablename, "column" LIMIT 5;

        tablename         |       column
--------------------------+---------------------
 stcs_abort_idle          | idle_start_time
 stcs_abort_idle          | txn_start_time
 stcs_analyze_compression | start_time
 stcs_auto_worker_levels  | start_level
 stcs_auto_worker_levels  | start_wlm_occupancy
```

以下示例指定“`^`”作为转义字符串，然后使用此转义字符串搜索包含“`_`”的字符串：

```
SELECT tablename, "column" FROM pg_table_def
WHERE "column" SIMILAR TO '%start^_%' ESCAPE '^'
ORDER BY tablename, "column" LIMIT 5;

        tablename         |       column
--------------------------+---------------------
 stcs_abort_idle          | idle_start_time
 stcs_abort_idle          | txn_start_time
 stcs_analyze_compression | start_time
 stcs_auto_worker_levels  | start_level
 stcs_auto_worker_levels  | start_wlm_occupancy
```

# POSIX 运算符
<a name="pattern-matching-conditions-posix"></a>

POSIX 正则表达式是指定匹配模式的字符序列。如果字符串是正则表达式描述的正则集的成员，则该字符串与正则表达式匹配。

与 [LIKE](r_patternmatching_condition_like.md) 和 [SIMILAR TO](pattern-matching-conditions-similar-to.md) 运算符相比，POSIX 正则表达式提供了更强大的模式匹配手段。POSIX 正则表达式模式可匹配字符串的任何部分，这与 SIMILAR TO 运算符不同，SIMILAR TO 运算符仅当其模式匹配整个字符串时才返回 true。

**注意**  
使用 POSIX 运算符的正则表达式匹配的计算成本高昂。我们建议尽可能使用 LIKE，尤其是在处理非常多的行时。例如，下列查询的功能相同，但使用 LIKE 的查询相比于使用正则表达式的查询的运行速度快若干倍：  

```
select count(*) from event where eventname ~ '.*(Ring|Die).*'; 
select count(*) from event where eventname LIKE '%Ring%' OR eventname LIKE '%Die%';
```

## 语法
<a name="pattern-matching-conditions-posix-synopsis"></a>

```
expression [ ! ] ~ pattern
```

## 参数
<a name="pattern-matching-conditions-posix-arguments"></a>

 *expression*   
有效的 UTF-8 字符表达式（如列名称）。

\$1  
求反运算符。请不要与正则表达式匹配。

\$1  
对 *expression* 的任何子字符串执行区分大小写的匹配。  
`~~` 是 [LIKE](r_patternmatching_condition_like.md) 的同义词。

 * 模式*   
表示正则表达式模式的字符串文本。

如果 *pattern* 不包含通配符，则模式仅表示字符串本身。

要搜索包含元字符的字符串（如“`. * | ? `”等），请使用两个反斜杠（“` \\`”）对字符进行转义。与 `SIMILAR TO` 和 `LIKE` 不同，POSIX 正则表达式语法不支持用户定义的转义字符。

其中一个字符表达式可以是 CHAR 或 VARCHAR 数据类型。如果它们不同，Amazon Redshift 会将 *pattern* 转换为 *expression* 的数据类型。

所有字符表达式都可以是 CHAR 或 VARCHAR 数据类型。如果表达式的数据类型不同，Amazon Redshift 会将其转换为 *expression* 的数据类型。

POSIX 模式匹配支持下列元字符：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/pattern-matching-conditions-posix.html)

Amazon Redshift 支持下列 POSIX 字符类。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/pattern-matching-conditions-posix.html)

 Amazon Redshift 在正则表达式中支持下列受 Perl 影响的运算符。使用两个反斜杠（“`\\`”）转义此运算符。  

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/pattern-matching-conditions-posix.html)

## 示例
<a name="pattern-matching-conditions-posix-synopsis-examples"></a>

下表显示了使用 POSIX 运算符的模式匹配的示例：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/redshift/latest/dg/pattern-matching-conditions-posix.html)

以下示例查找名称包含 `E` 或 `H` 的城市：

```
SELECT DISTINCT city FROM users
WHERE city ~ '.*E.*|.*H.*' ORDER BY city LIMIT 5;

      city
-----------------
 Agoura Hills
 Auburn Hills
 Benton Harbor
 Beverly Hills
 Chicago Heights
```

以下示例查找名称不包含 `E` 或 `H` 的城市：

```
SELECT DISTINCT city FROM users WHERE city !~ '.*E.*|.*H.*' ORDER BY city LIMIT 5;

      city
-----------------
 Aberdeen	
 Abilene	
 Ada	
 Agat	
 Agawam
```

以下示例使用转义字符串（“`\\`”）搜索包含句点的字符串。

```
SELECT venuename FROM venue
WHERE venuename ~ '.*\\..*'
ORDER BY venueid;

          venuename
------------------------------
 St. Pete Times Forum
 Jobing.com Arena
 Hubert H. Humphrey Metrodome
 U.S. Cellular Field
 Superpages.com Center
 E.J. Nutter Center
 Bernard B. Jacobs Theatre
 St. James Theatre
```

# BETWEEN 范围条件
<a name="r_range_condition"></a>

`BETWEEN` 条件使用关键字 `BETWEEN` 和 `AND` 测试表达式是否包含在某个值范围中。

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

```
expression [ NOT ] BETWEEN expression AND expression
```

表达式可以是数字、字符或日期时间数据类型，但它们必须是可兼容的。此范围包含起始值。

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

第一个示例计算有多少个事务登记了 2、3 或 4 票证的销售：

```
select count(*) from sales
where qtysold between 2 and 4;

count
--------
104021
(1 row)
```

范围条件包含开始和结束值。

```
select min(dateid), max(dateid) from sales
where dateid between 1900 and 1910;

min  | max 
-----+-----
1900 | 1910
```

范围条件中的第一个表达式必须是较小的值，第二个表达式必须是较大的值。在以下示例中，由于表达式的值，将始终返回零行：

```
select count(*) from sales
where qtysold between 4 and 2;

count
-------
0
(1 row)
```

但是，应用 NOT 修饰符将反转逻辑并生成所有行的计数：

```
select count(*) from sales
where qtysold not between 4 and 2;

count
--------
172456
(1 row)
```

以下查询将返回拥有 20000 到 50000 个座位的场馆的列表：

```
select venueid, venuename, venueseats from venue
where venueseats between 20000 and 50000
order by venueseats desc;

venueid |       venuename               | venueseats
---------+-------------------------------+------------
116 | Busch Stadium                 |      49660
106 | Rangers BallPark in Arlington |      49115
96 | Oriole Park at Camden Yards   |      48876
...
(22 rows)
```

以下示例演示了如何为日期值使用 BETWEEN：

```
select salesid, qtysold, pricepaid, commission, saletime 
from sales 
where eventid between 1000 and 2000 
   and saletime between '2008-01-01' and '2008-01-03'
order by saletime asc;

salesid | qtysold | pricepaid | commission |   saletime
--------+---------+-----------+------------+---------------
  65082 |       4 |       472 |       70.8 | 1/1/2008 06:06
 110917 |       1 |       337 |      50.55 | 1/1/2008 07:05
 112103 |       1 |       241 |      36.15 | 1/2/2008 03:15
 137882 |       3 |      1473 |     220.95 | 1/2/2008 05:18
  40331 |       2 |        58 |        8.7 | 1/2/2008 05:57
 110918 |       3 |      1011 |     151.65 | 1/2/2008 07:17
  96274 |       1 |       104 |       15.6 | 1/2/2008 07:18
 150499 |       3 |       135 |      20.25 | 1/2/2008 07:20
  68413 |       2 |       158 |       23.7 | 1/2/2008 08:12
```

请注意，尽管 BETWEEN 的范围包括在内，但日期默认具有 00:00:00 的时间值。示例查询中唯一有效的 1 月 3 日行是 saletime 为 `1/3/2008 00:00:00` 的行。

# Null 条件
<a name="r_null_condition"></a>

在缺少值或值未知时，null 条件测试是否存在 null。

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

```
expression IS [ NOT ] NULL
```

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

 *expression*   
任何表达式（如列）。

IS NULL   
当表达式的值为 null 时为 true；当表达式具有一个值时，为 false。

 IS NOT NULL   
当表达式的值为 null 时为 false；当表达式具有一个值时，为 true。

## 示例
<a name="r_null_condition-example"></a>

此示例指示 SALES 表的 QTYSOLD 字段中包含 null 的次数：

```
select count(*) from sales
where qtysold is null;
count
-------
0
(1 row)
```

# EXISTS 条件
<a name="r_exists_condition"></a>

EXISTS 条件测试子查询中是否存在行，并在子查询返回至少一个行时返回 true。如果指定 NOT，此条件将在子查询未返回任何行时返回 true。

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

```
[ NOT ] EXISTS (table_subquery)
```

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

 EXISTS   
当 *table\$1subquery* 返回至少一行时，为 true。

NOT EXISTS   
当 *table\$1subquery* 未返回任何行时，为 true。

 *table\$1subquery*   
计算结果为包含一个或多个列和一个或多个行的表的子查询。

## 示例
<a name="r_exists_condition-example"></a>

此示例针对具有任何类型的销售的日期返回所有日期标识符，一次返回一个日期：

```
select dateid from date
where exists (
select 1 from sales
where date.dateid = sales.dateid
)
order by dateid;

dateid
--------
1827
1828
1829
...
```

# IN 条件
<a name="r_in_condition"></a>

IN 条件测试一组值或一个子查询中的成员值。

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

```
expression [ NOT ] IN (expr_list | table_subquery)
```

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

 *expression*   
数字、字符或日期时间表达式，针对 *expr\$1list* 或 *table\$1subquery* 进行计算，必须是与列表或子查询的数据类型兼容的。

 *expr\$1list*   
一个或多个逗号分隔的表达式，或一组或多组逗号分隔的表达式（用括号限定）。

 *table\$1subquery*   
一个子查询，计算结果为具有一行或多行的表，但在其选择列表中限制为一列。

IN \$1 NOT IN   
如果表达式是表达式列表或查询的成员，则 IN 将返回 true。如果表达式不是成员，NOT IN 将返回 true。在下列情况下，IN 和 NOT IN 将返回 NULL 并且不会返回任何行：如果 *expression* 生成 null；或者，如果没有匹配的 *expr\$1list* 或 *table\$1subquery* 值并且至少一个比较行生成 null。

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

下列条件仅对列出的值有效：

```
qtysold in (2, 4, 5)
date.day in ('Mon', 'Tues')
date.month not in ('Oct', 'Nov', 'Dec')
```

## 优化大型 IN 列表
<a name="r_in_condition-optimization-for-large-in-lists"></a>

为了优化查询性能，包含 10 个以上的值的 IN 列表将在内部作为标量数组计算。少于 10 个值的 IN 列表将作为一系列 OR 谓词计算。SMALLINT、INTEGER、BIGINT、REAL、DOUBLE PRECISION、BOOLEAN、CHAR、VARCHAR、DATE、TIMESTAMP 和 TIMESTAMPTZ 数据类型均支持此优化。

查看查询的 EXPLAIN 输出以查看此优化的效果。例如：

```
explain select * from sales
QUERY PLAN
--------------------------------------------------------------------
XN Seq Scan on sales  (cost=0.00..6035.96 rows=86228 width=53)
Filter: (salesid = ANY ('{1,2,3,4,5,6,7,8,9,10,11}'::integer[]))
(2 rows)
```