天天看點

oracle 2 過濾和排序

過濾:條件查詢

排序:order by

--查詢10号部門的員工

select *

  from emp

  where deptno=10;

oracle 2 過濾和排序

1.oracle嚴格區分大小寫(mysql不區分)

 --字元串大小寫敏感

 --查詢名叫KING的員工

select *

from emp

where ename ='KING';

oracle 2 過濾和排序

select *

from emp

where ename='King';

oracle 2 過濾和排序

2.日期格式敏感

--日期格式敏感

--查詢入職日期是17-11月-81的員工

select *

from emp

where hiredate='17-11月-81';

oracle 2 過濾和排序

-- 錯誤寫法

select *

from emp

where hiredate='1981-11-17'

oracle 2 過濾和排序
報錯:與字元串格式不比對,說明是簡單的字元串比對,格式必須和系統設定的一樣,否則就失敗!

2.1修改日期格式

--修改日期格式

-- 查詢資料字典

select * from v$nls_parameters;

oracle 2 過濾和排序

修改日期格式

alter system set NLS_DATE_FORMAT='yyyy-mm-dd'; --system 整個系統有效    系統管理者才有資格                                           alter session set NLS_DATE_FORMAT='yyyy-mm-dd'; --session目前會話有效 scott有資格

alter session set NLS_DATE_FORMAT='yyyy-mm-dd';

oracle 2 過濾和排序
此時上面的錯誤寫法正确了,相應的正确寫法'17-11月-81'就會出錯,也即是符合系統設定的才是正确的
oracle 2 過濾和排序
目前所有的日期類型都變了:
oracle 2 過濾和排序

3.比較運算符

oracle比較運算符

操作符 含義
= 等于(不是==)
> 大于
>= 大于等于
< 小于
<= 小于等于
<>  不等于(也可以是!=)
:= 指派
oracle 2 過濾和排序

其他比較運算符

操作符 含義
between...and... 在兩個值之間(包含邊界)
in(set) 等于值清單中的一個
like 模糊查詢
is null 空值

--between  and 在。。。。之間

--查詢薪水1000~2000之間的員工

select * from emp where sal between 1000 and 2000;

oracle 2 過濾和排序

注意:

--between  and: 1. 含有邊界  2. 小值在前 大值在後

oracle 2 過濾和排序

null值 

1.null值永遠不等于null      2.含有null值的表達式都是null

3.集合中有null,不能使用not in但可以使用in

-- 查不出任何結果

select * from emp where deptno not in (10,20,null);

--ok

select * from emp where deptno not in (10,20,null);

邏輯運算符:and or not

oracle 2 過濾和排序

4.模糊查詢

%:可以比對任意長度的内容

"_":可以比對一個長度的内容

--查詢名字以S開頭的員工
--注意字元串用'' 而不是 ""
select * from emp where ename like 'S%';

--查詢名字是四個字的員工
select * from emp where ename like '____';

-- 查詢名字中含有下劃線的員工
select * from emp where ename like '%_%';
-- select * from emp where ename like '%_%'; 錯誤寫法
-- 主動聲明轉移字元
select * from emp where ename like '%\_%' escape '\';
--附加 可以復原剛才的插入操作
rollback;      

where子句解析順序: 從右往左

    where condition1 and condition2  

    where condition2 and condition1

oracle裡兩條sql子句完全不同隻是運作結果相同罷了

對于上面兩天語句,若右邊條件為假,左邊的語句就不會執行了.是以寫代碼時盡量将可能為假的條件放到後面

學習方向:sql執行計劃

5.排序

--查詢員工資訊,按月薪升序排序
--order by 列
select * from emp order by sal;

--查詢員工資訊,按年薪升序排序
--order by 表達式
select empno,ename,sal,sal*12 年薪 from emp order by sal*12 desc;

--查詢員工資訊,按年薪升序排序
--order by (select後查詢列的)序号
select empno,ename,sal,sal*12 年薪 from emp order by 4 desc;

--多個列排序 order by作用于後面所有列 最靠近的一級排序 其次二級三級
select * from emp order by deptno,sal;
 
--多個列排序  desc僅作用于前面一個  下面兩句執行結果不同
select * from emp order by deptno,sal desc;
select * from emp order by deptno desc,sal desc;      

空值排序:

select * from emp order by comm;

預設升序沒問題

oracle 2 過濾和排序

但是降序有問題

select * from emp order by comm desc;

oracle 2 過濾和排序

解決方法:

select * from emp order by comm desc nulls last;

--nulls last 如果有空值 所有空值都在最後

oracle 2 過濾和排序
分析原因:oracle中空值最大