一、空值處理:
1. 查找空值 null:
select * from emp where emp.empdesc = null;
select * from emp where emp.empdesc is null;
2. 空值 null 不能做“加、減、乘、除、比較”等運算:
select * from emp where emp.empsalary >= null; select * from emp where emp.empsalary <= null;
select * from emp where emp.empsalary is not null;
3. nvl、coalesce 將空值轉換爲實際值:
nvl 只能接受兩個參數,而 coalesce 可以接受多個參數,返回第一個不是 null 的值。例如下邊的兩個 SQL 是等價的:
/* 數據準備 */ create table coal( c1 number(6, 2), c2 number(6, 2), c3 number(6, 2), c4 number(6, 2), c5 number(6, 2), c6 number(6, 2) ); insert into coal values(null, null, 1, null, 2, null); insert into coal values(null, null, null, 3, null, 2); /* coal 表數據 */ select * from coal;
下邊兩句等價,coalesce 函數從第一個參數開始從左到右,依次判斷是否爲 null, 返回第一不爲 null 的值,直至最後一個參數的值。
/* nvl、coalesce 下邊兩句等價 */ select coalesce(c1, c2, c3, c4, c5, c6) c from coal; select nvl(nvl(nvl(nvl(nvl(c1, c2), c3), c4), c5), c6) c from coal;
二、rownum 限制返回的行數:
1. rownum 是返回數據一個排序標識:
rownum 會依次對返回的每一條數據做一個標識,經常在分頁的時候會見到。這裏紅色着重標註“返回”兩字,是指 rownum 不是記錄的固有標識(比如 rowId 是記錄的物理標誌),這個下邊會舉例。先說 rownum 的用法:
select * from emp where rownum <= 2;
2. rownum 不是記錄的固有標誌:只有數據返回以後才能用 rownum,只是返回數據的一個標識,例如下邊的查詢結果就爲空:
select * from emp where rownum = 2
而如果想要返回結果集的第二條數據,需要嵌套一層,這也是分頁的做法:
select * from (select emp.*, rownum rown from emp) where rown = 2
三、模糊查詢的通配符與轉義字符:
1. 模糊查詢的兩個通配符 ‘%’、‘_’:
‘%’ 是替代一個或多個字符,而 ‘_’ 是替代一個字符。‘%’ 都清楚,只舉例 ‘_’:
select * from emp where emp.empno like '_mp%';
模糊查詢條件改爲 ‘_p’ 就查不出結果,‘_’ 只能匹配一個字符:
select * from emp where emp.empno like '_p%';
2. sql 中查詢類似 ‘_’、‘%’ 特殊字符的,用 ‘/’ escape ‘/’ 實現:
select * from emp where emp.empdesc like '/_%' escape '/';