1. 程式人生 > >postgresql常見數值,字元,日期型別常見函式總結

postgresql常見數值,字元,日期型別常見函式總結

一.字元函式

函式 描述 例子
char_length(string) 獲取字串中字元的個數 test=> select char_length('abc123蘇'); char_length  -------------           7
length(string) 獲取字元的數目.經過測試好像和char_length沒有區別. test=> select length('abc123中國'); length  --------       8
convert() 使用指定的轉換名改變編碼 test=> select convert('aa','utf8','gbk'); convert  --------- \x6161
lower/upper(strings) 將字串轉換為小寫/大寫 test=> select lower('ABC'),upper('abc'); lower | upper  -------+------- abc  | ABC
initcap(string) 將字串的第一個字母轉換為大寫,其它保留小寫 test=> select initcap('abc'); initcap  --------- Abc
octet_length(string) 返回字串中的位元組數 test=> select octet_length('abc中國'),octet_length('abcdef'); octet_length | octet_length  --------------+--------------             9 |            6
position(strings in string) 返回指定字串的位置,如果沒有則為0 test=> select position('a'  in '123abc'); position  ----------         4
strpos(str,str) 獲取指定字串的位置,和position類似,不過引數順序不一致 test=> select strpos('abcdefgh','c'); strpos  --------       3
substr(string,int,int) 抽取字串中的指定位置的字元 test=> select substr('abcdef',2,5); substr  -------- bcdef (1 row)
substring 抽取更多規則的子字串,支援正則表示式,例如抽取字串最後一個字元 test=> select substring('abcdef','.$'); substring  ----------- f
trim(string,string)  在字串兩邊擷取指定字元,可以是多個字元.預設為空字元 test=> select trim('xyxtrimyyx', 'xyt'); btrim  ------- rim
rtrim,ltrim 在字串的右邊/左邊刪除指定的字串 test=> select rtrim('abcdefa','a'),ltrim('abcdefa','a'); rtrim  | ltrim   --------+-------- abcdef | bcdefa  
btrim(string,string) 在字串的兩邊刪除指定的字串,直到遇到一個不是指定的字串為止.注意與trim的區別. 經過測試和trim好像是一樣的
lpad(string,int,string)/rpad 在字串的左邊/右邊填充字串,使得字串的長度達到指定長度. test=> select lpad('abc',10,'x'),rpad('abc',10,'x');     lpad    |    rpad     ------------+------------ xxxxxxxabc | abcxxxxxxx
ascii(str)/chr(int) 將字串轉換為ascii碼,將ascii碼轉換成字串 test=> select ascii('a'),chr(97); ascii | chr  -------+-----     97 | a
decode/encode 將encode編碼的strings轉換為二進位制/將二進位制的編碼轉換為strings.注意和oracle中decode的區別. test=> select decode('b3NkYmEAAQ==','base64');       decode       ------------------ \x6f73646261000
md5(string) 獲取字串的md5值 test=> select md5('brent');               md5                 ---------------------------------- fddd76411252e465ab9edde8ebed3d0a
quote_ident(string) 返回適合於sql語句的識別符號形式只有在必要的才會新增引號.一般用在有特殊字元的地方 test=> select quote_ident('"ss'),quote_ident('abc'),quote_ident('abc\'); quote_ident | quote_ident | quote_ident  -------------+-------------+------------- """ss"      | abc        | "abc\"  
quote_literal(string) 返回適用於sql語句中的文字形式 test=> select quote_literal('"ss'),quote_literal('abc'),quote_literal('abc\'); quote_literal | quote_literal | quote_literal  ---------------+---------------+--------------- '"ss'        | 'abc'        | E'abc\\'
regxp_replace(strings,pattern,strings) 匹配替換posix正則表示式的字串 test=> select regexp_replace('abc123efg','..[1-9]+','#'); regexp_replace  ---------------- a#efg
repeat(strings,int) 將字串重複N次 test=> select repeat('abc',3);   repeat   ----------- abcabcabc
replace(str,str) 將字串替換成指定字串.注意這裡的字串是連續的字串,而不是按照字元進行替換 test=> select replace('aaabbbccc','b','23');   replace     -------------- aaa232323ccc
translate(str,str) 將字串中的字元轉換成指定字元,注意這裡的是進行字串的轉換,和replace是不同的. test=> select translate('aaabbbccc','ab','xy'),replace('aaabbbccc','ab','xy'); translate |  replace   -----------+----------- xxxyyyccc | aaxybbccc 這裡的例子中,translate只是將a轉換成x,b轉換成y,和replace完全不同
split_part(str,delimiter,int) 根據delimiter擷取,獲取指定的part,有點像shell中的awk命令 test=> select split_part('brent,no.1,93',',',2); split_part  ------------ no.1 (1 row)  
to_hex(int) 將number轉換為16進位制 test=> select to_hex(1000); to_hex  -------- 3e8 (1 row)

二.數值函式

函式 描述 例子
ceil 取整數,取大值 test=> select ceil(35.7); ceil  ------   36 (1 row)
floor 取整數,取小值 test=> select floor(35.7); floor  -------     35  
round(numeric,int) 四捨五入.後面的值為精度,如果後面的精度沒有則取整 test=> select round(36.12),round(36.567,2); round | round  -------+-------     36 | 36.57  
trunc(numeric,int) 截斷,後面的為精度,如果不設定精度則為取整,類似於floor test=> select trunc(32.567),trunc(32.567,2); trunc | trunc  -------+-------     32 | 32.56  
random() 0.0到1.0之間的隨機數 test=> select random();       random       ------------------- 0.679839549586177  

三.日期函式

函式 描述 例子
age(timstamp,timestamp) 返回一個時間差,例如年齡,第一個時間減去第二個時間.如果第一個引數不寫,那麼預設是當前時間,第二個引數需要格式為timestamp型別 test=>  select age(timestamp '1987-10-15'),age('2018-09-16','1987-10-16');           age          |      age         ------------------------+------------------ 30 years 11 mons 1 day | 30 years 11 mons
clock_timestamp() 實時時鐘的當前時間戳.和current_timestamp的區別是,當開啟一個事務後,current_timestamp是不變的表示事務的開啟時間,而clock_timestamp()表示時鐘時間,所以在一個sql語句中的clock時間也有可能是不同的. test=> begin; BEGIN test=> select current_timestamp,clock_timestamp();       current_timestamp      |        clock_timestamp         -------------------------------+------------------------------- 2018-09-16 10:45:53.653818+08 | 2018-09-16 10:46:04.311372+08 (1 row) test=> select current_timestamp,clock_timestamp();       current_timestamp      |        clock_timestamp         -------------------------------+------------------------------- 2018-09-16 10:45:53.653818+08 | 2018-09-16 10:46:11.469315+08 (1 row) test=> end; COMMIT
statement_timestamp() 當前語句執行的系統時間,在一個sql中的時間是一致的.可以看這個例子,同一個sql中,三個時間都不一致 test=> select clock_timestamp(),clock_timestamp(),statement_timestamp();         clock_timestamp        |        clock_timestamp        |      statement_timestamp       -------------------------------+-------------------------------+------------------------------- 2018-09-16 11:33:59.982234+08 | 2018-09-16 11:33:59.982235+08 | 2018-09-16 11:33:59.982161+08  
timeofday() 等同於clock_timestamp(),但是返回的是一個text字串 test=> select timeofday();               timeofday               ------------------------------------- Sun Sep 16 10:51:58.989842 2018 CST
current_timestamp 當前事務的開啟時間戳.在一個事務內時間保持不變.帶時區.還可以接一個引數,指定精度,該精度導致結果的秒數四捨五入到小數位. test=> select current_timestamp(0),current_timestamp;   current_timestamp    |      current_timestamp       ------------------------+------------------------------- 2018-09-16 11:27:19+08 | 2018-09-16 11:27:19.112954+08
current_date 當前事務的日期,在一個事務內日期不變
current_time 當前事務的時間,在一個事務內時間不變
localtime 等同於current_time,不帶時區
localtimestamp 等同於current_timestamp,不帶時區.還可以接一個引數,指定精度,該精度導致結果的秒數四捨五入到小數位. test=> select localtimestamp,localtimestamp(0);       localtimestamp      |  localtimestamp     ----------------------------+--------------------- 2018-09-16 11:26:37.935849 | 2018-09-16 11:26:38
now() 等同於current_timestamp
transaction_timestamp() 等同於current_timestamp
extract() 獲取子域 test=> select now(),extract(year from now()),extract(month from now()),extract(day from now()),extract(minute from now()),extract(second from now());               now              | date_part | date_part | date_part | date_part | date_part  -------------------------------+-----------+-----------+-----------+-----------+----------- 2018-09-16 11:08:25.431863+08 |      2018 |        9 |        16 |        8 | 25.431863  
date_part(text,timestamp) 獲取子域,等同於extract test=> select date_part('hour',now()),date_part('minute',now()),date_part('month',now()); date_part | date_part | date_part  -----------+-----------+-----------         11 |        10 |        9
date_trunc(text,timestamp) 截斷指定的精度 test=> select date_trunc('day',current_timestamp),date_trunc('hour',current_timestamp);       date_trunc      |      date_trunc       ------------------------+------------------------ 2018-09-16 00:00:00+08 | 2018-09-16 11:00:00+08

EXTRACT和date_part函式的引數

說明 示例
century 世紀
year
decade 年份/10
millennium 第幾個千年,0-1000是1,1000-2000是2,2000-3000是3
quarter 第幾季度
month
week 第幾個星期
dow 星期幾,0是星期天...
day 本月的第幾天
doy 本年的第幾天
hour 得到時間中的小時
minute 得到時間中的分鐘
second 得到時間中的秒
epoch 相對於1970-01-01 00:00:00以來的時間. test=> select date_part('epoch',now());     date_part     ------------------ 1537069799.45484  
milliseconds 秒域/毫秒數,即秒數乘以1000 test=> select current_timestamp,extract(milliseconds from current_timestamp);       current_timestamp      | date_part  -------------------------------+----------- 2018-09-16 11:55:58.041867+08 | 58041.867
microseconds 秒域/微秒數,即秒數乘以1000 test=> select current_timestamp,extract(microseconds from current_timestamp);       current_timestamp      | date_part  -------------------------------+----------- 2018-09-16 11:56:26.533713+08 |  26533713
timezone 時區偏移量(秒).+8就是8*3600=28800 test=> select extract(timezone from current_timestamp); date_part  -----------     28800
timezone_hour 時區偏移量(小時),+8就是8 test=> select extract(timezone_hour from current_timestamp); date_part  -----------         8
timezone_minute 時區偏移量的小時部分,整數都返回0 test=> select extract(timezone_minute from current_timestamp); date_part  -----------         0

總結:

1.如果是取事務時間,如果需要時區,一般用current_timestamp或者now(),current_timestamp的好處是可以去精度

2.如果是取事務時間,如果不需要時區,一般用localtimestamp.localtimestamp也可以取精度

3.如果是取每個語句執行的時間,則使用statement_timestamp()