PostgreSQL與Oracle的sql差異

u_7deeb657158f發表於2019-12-04

1.rownum

(1)Oracle分頁查詢使用rownum,PostgreSQL使用limit offset

Oracle PostgreSQL
select * from (select rownum r,e.* from emp e where rownum <=5) t where r>0; select * from emp limit 5 offset 0;

(2)Oracle中rownum=1,PostgreSQL中使用limit 1

Oracle PostgreSQL
select * from emp where rownum = 1; select * from emp limit 1;

(3)Oracle中序號列rownum,PostgreSQL使用視窗函式

Oracle PostgreSQL
select rownum,t.* from emp t; select row_number() over(), t.* from emp t;

2.系統日期

Oracle PostgreSQL
SYSDATE current_timestamp, current_date

3.delete語句

Oracle delete語句可以沒有from,pg必須要有from

Oracle PostgreSQL
delete from emp where empno = xxx;
delete emp where empno = xxx
delete from emp where empno = xxx

4.型別自動轉換

Oracle支援型別自動轉換,例如數字自動換換為字串等;PG中需要顯示轉換,或者新增CAST

5.子查詢別名

PostgreSQL在from關鍵字後的子查詢必須要有別名,Oralce可以沒有。

6. group by having

PG having語句必須在group by之後,oracle可以在group by之前

7.遞迴查詢

Oracle中使用start with … connect by…, PG中使用with recusive

Oracle PostgreSQL
select *
from larearrelation
where rearedgens = 1
and rearflag = 1
and rearlevel = ‘01’
connect by prior agentcode = rearagentcode
start with rearagentcode = ‘10032226’;
with recursive rs as (
select * from larearrelation where rearagentcode = ‘10032226’
union all
select a. from larearrelation a, rs where a.rearagentcode = rs.agentcode
)
select * from rs where rearedgens = 1 and rearflag = ‘1’ and rearlevel = ‘01’

8.update語句別名

postgresql中update語句時,set的欄位不能有別名

Oracle PostgreSQL
update emp t set t.name = ‘xxx’ where t.empno = 2 update emp set name = ‘xxx’ where empno = 2

9. 日期相減

oracle日期相減自動轉換為數字,結果為相差的天數。
pg日期相減為interval型別,得到相差天數需要進行型別轉換

10.遞迴查詢中的level

oracle的遞迴查詢中level表示查詢深度(或者遞迴層次),在PG中沒有此含義的關鍵字,需要自行在with recursive實現

Oracle PostgreSQL
select max(level) from larearrelation
where rearedgens = 1
and rearflag = 1
and rearlevel = ‘01’
connect by prior agentcode = rearagentcode
start with rearagentcode = ‘10032226’;
with recursive rs as (
select larearrelation. , 1 depth from larearrelation where rearagentcode = ‘10032226’
union all
select a./*, rs.depth + 1 depth from larearrelation a, rs where a.rearagentcode = rs.agentcode
)
select max(rs.depth) from rs where rearedgens = 1 and rearflag = ‘1’ and rearlevel = ‘01’

11.序列的呼叫

Oracle PostgreSQL
select seqname.nextval from dual; select nextval(‘seqname’)

12.外連線

Oralce外連線支援使用 (+), PostgreSQL需使用left jion或者right join標準sql語法

13.distinct去重複

oracle支援unique關鍵字去重複,pg中只能使用distinct

14.字串分割

Oracle PostgreSQL
listagg string_agg

15.集合相減

Oracle PostgreSQL
Minus except

16.null與”

null和’’在oracle中是一致的,最終都會儲存為null,在PG中會進行區分

17.不等於

Oracle中 ! =,< >操作符中間允許有空格,PG中不可以

18.別名

PG中無效的別名,可以嘗試加as關鍵字,例如name

19.正規表示式

Oracle PostgreSQL
SELECT REGEXP_SUBSTR(‘17,20,23’,’[^,]+’,1,1,’i’) FROM DUAL; select (regexp_matches(‘17,20,23’, ‘[^,]+’))[1]

20.欄位大小寫

oracle欄位名大寫,PG欄位名小寫

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69956102/viewspace-2666880/,如需轉載,請註明出處,否則將追究法律責任。

相關文章