Postgresql 中文操作指南

8.6. Boolean Type #

PostgreSQL 提供标准 SQL 类型 boolean;请参阅 Table 8.19。_boolean_类型可以有几个状态:“真”、“假”和第三种状态“未知”,由 SQL 空值表示。

PostgreSQL provides the standard SQL type boolean; see Table 8.19. The boolean type can have several states: “true”, “false”, and a third state, “unknown”, which is represented by the SQL null value.

Table 8.19. Boolean Data Type

Name

Storage Size

Description

boolean

1 byte

state of true or false

布尔常量在SQL查询中可以通过SQL关键字_TRUE_、_FALSE_及_NULL_表示。

Boolean constants can be represented in SQL queries by the SQL key words TRUE, FALSE, and NULL.

类型_boolean_的数据类型输入函数接受以下字符串表示表示“true”状态:

The datatype input function for type boolean accepts these string representations for the “true” state:

以及以下表示表示“false”状态:

and these representations for the “false” state:

这些字符串的唯一前缀也被接受,例如_t_或_n_。前导或尾随空格被忽略,且区分大小写。

Unique prefixes of these strings are also accepted, for example t or n. Leading or trailing whitespace is ignored, and case does not matter.

类型 boolean_的数据类型输出函数总是会发出 _t_或 _f,如 Example 8.2所示。

The datatype output function for type boolean always emits either t or f, as shown in Example 8.2.

Example 8.2. Using the boolean Type

Example 8.2. Using the boolean Type

CREATE TABLE test1 (a boolean, b text);
INSERT INTO test1 VALUES (TRUE, 'sic est');
INSERT INTO test1 VALUES (FALSE, 'non est');
SELECT * FROM test1;
 a |    b
---+---------
 t | sic est
 f | non est

SELECT * FROM test1 WHERE a;
 a |    b
---+---------
 t | sic est

关键词 TRUE_和 _FALSE_是 SQL 查询中编写布尔常量的首选(与 SQL 兼容的)方法。但你也可以按照 Section 4.1.2.7中描述的通用字符串文本常量语法来使用字符串表示,例如 _'yes'::boolean

The key words TRUE and FALSE are the preferred (SQL-compliant) method for writing Boolean constants in SQL queries. But you can also use the string representations by following the generic string-literal constant syntax described in Section 4.1.2.7, for example 'yes'::boolean.

请注意,解析器自动理解_TRUE_和_FALSE_的类型是_boolean_,但_NULL_并不如此,因为其可以具有任何类型。所以在某些情况下,您可能必须将_NULL_显式转换为_boolean_,例如_NULL::boolean_。相反,在解析器可以推断文本必须是类型_boolean_的情况下,可以从字符串文本布尔值中省略转换。

Note that the parser automatically understands that TRUE and FALSE are of type boolean, but this is not so for NULL because that can have any type. So in some contexts you might have to cast NULL to boolean explicitly, for example NULL::boolean. Conversely, the cast can be omitted from a string-literal Boolean value in contexts where the parser can deduce that the literal must be of type boolean.