# 条件表达式

## CASE

``````CASE expression
WHEN value THEN result
[ WHEN ... ]
[ ELSE result ]
END
``````

``````SELECT a,
CASE a
WHEN 1 THEN 'one'
WHEN 2 THEN 'two'
ELSE 'many'
END
``````

“搜索”形式从左向右计算每个 boolean `condition` 的值，直到其中一个为 true 并返回匹配的 `result`

``````CASE
WHEN condition THEN result
[ WHEN ... ]
[ ELSE result ]
END
``````

``````SELECT a, b,
CASE
WHEN a = 1 THEN 'aaa'
WHEN b = 2 THEN 'bbb'
ELSE 'ccc'
END
``````

## IF

`IF` 函数实际上是一个语言构造，该函数等效于下面的 `CASE` 表达式：

``````CASE
WHEN condition THEN true_value
[ ELSE false_value ]
END
``````

if(condition, true_value)

if(condition, true_value, false_value)

## COALESCE

coalesce(value1, value2[, …])

## NULLIF

nullif(value1, value2)

## TRY

try(expression)

`TRY` 处理以下错误：

• 被零除
• 无效的转换或函数参数
• 数值超出范围

### 示例

``````SELECT * FROM shipping;
``````
``````origin_state | origin_zip | packages | total_cost
--------------+------------+----------+------------
California   |      94131 |       25 |        100
California   |      P332a |        5 |         72
California   |      94025 |        0 |        155
New Jersey   |      08544 |      225 |        490
(4 rows)
``````

``````SELECT CAST(origin_zip AS BIGINT) FROM shipping;
``````
``````Query failed: Can not cast 'P332a' to BIGINT
``````

`TRY``NULL` 值：

``````SELECT TRY(CAST(origin_zip AS BIGINT)) FROM shipping;
``````
``````origin_zip
------------
94131
NULL
94025
08544
(4 rows)
``````

``````SELECT total_cost / packages AS per_package FROM shipping;
``````
``````Query failed: Division by zero
``````

`TRY``COALESCE` 的默认值：

``````SELECT COALESCE(TRY(total_cost / packages), 0) AS per_package FROM shipping;
``````
``````per_package
-------------
4
14
0
19
(4 rows)
``````