簡單的WHERE子句無法對包含空值的資料進行篩選,您可以在PolarDB PostgreSQL版(相容Oracle)叢集中安裝LNNVL函數,對包含空值的資料進行篩選。
安裝
PolarDB PostgreSQL版(相容Oracle)通過外掛程式的形式支援LNNVL函數,您需要完成安裝後才能使用該函數,安裝命令如下:
SET client_min_messages TO 'ERROR';
CREATE EXTENSION if not exists polar_lnnvl;
RESET client_min_messages;文法
lnnvl(condition)| 參數 | 說明 |
condition | LNNVL函數查詢條件。 |
描述
說明 LNNVL函數僅支援在WHERE子句中使用。
LNNVL函數以條件作為參數。
- 如果該條件可在表中匹配到資料,則返回所有未匹配該條件的資料(含空值)。
- 如果該條件無法在表中匹配到資料,則返回表中所有資料(含空值)。
- 如果該條件僅匹配到表中的空值,則返回表中所有資料(不含空值)。
例如,某張表中存在如下兩行資料:
name | id
------------
a | 2
b | null使用不同的條件,LNNVL函數的返回結果如下。
| 條件 | 是否匹配到資料或空值 | LNNVL傳回值 |
lnnvl(id=1) | 否 | a行和b行 |
lnnvl(id=2) | 是 | b行 |
lnnvl(id>2) | 否 | a行和b行 |
lnnvl(id<2) | 否 | a行和b行 |
lnnvl(id is null) | 是 | a行 |
樣本
使用如下命令建立一個名為account的表,並插入測試資料:
create table account(name varchar2(20),year number);
insert into account values('peter2001',2001);
insert into account values('peter2002',2002);
insert into account values('peter2003',2003);
insert into account values('peter2004',2004);
insert into account values('peter2005',2005);
insert into account values('peter2006',2006);
insert into account values('peter2007',null);- 當條件為
year<2003時,LNNVL就會返回年份大於等於2003或者空值的行。查詢語句如下:
select * from account where lnnvl(year<2003);查詢結果如下:
name | year -----------+------ peter2003 | 2003 peter2004 | 2004 peter2005 | 2005 peter2006 | 2006 peter2007 | null - 當條件為
year is not null時,LNNVL就會返回年份是空值的行。查詢語句如下:
select * from account where lnnvl(year is not null);查詢結果如下:
name | year -----------+------ peter2007 | null - 當條件為
year is null時,LNNVL就會返回年份不是空值的行。查詢語句如下:
select * from account where lnnvl(year is null);查詢結果如下:
name | year -----------+------ peter2001 | 2001 peter2002 | 2002 peter2003 | 2003 peter2004 | 2004 peter2005 | 2005 peter2006 | 2006 - 當條件為
year=2008時,LNNVL就會返回年份不為2008的行。查詢語句如下:
select * from account where lnnvl(year=2008);查詢結果如下:
name | year -----------+------ peter2001 | 2001 peter2002 | 2002 peter2003 | 2003 peter2004 | 2004 peter2005 | 2005 peter2006 | 2006 peter2007 | null - 當條件為
year!=2008時,LNNVL就會返回年份為2008或空值的行。查詢語句如下:
select * from account where lnnvl(year!=2008);查詢結果如下:
name | year -----------+------ peter2007 | null