相似Oracle ,PostgreSQL也有強大的類型轉換函數, 下面僅舉兩個類型轉換例子。 --1 例子 postgres=# select 1/4; ?column? ---------- 0 (1 row) 在PG裏若是想作除法並想保留小數,用上面的方法卻行不通,由於"/" 運算結果爲取整,並 且會截掉小數部分。 --2 類型轉換 postgres=# select round(1::numeric/4::numeric,2); round ------- 0.25 (1 row) 備註:類型轉換後,就能保留小數部分了。 --3 也能夠經過 cast 函數進行轉換 postgres=# select round( cast ( 1 as numeric )/ cast( 4 as numeric),2); round ------- 0.25 (1 row) --4 關於 cast 函數的用法 substr 索引默認爲1 下面是從 第3位開始,截取1位 postgres=# SELECT substr(CAST (1234 AS text), 3,1); substr -------- 3 (1 row)
|| 字符串拼接 語法 string || string 示例 'Post' || 'greSQL' -- 返回PostgreSQL length() 字符串的長度 語法 length(string) 示例 length('Odoo') -- 返回4 LIKE 模式匹配 語法 string LIKE pattern 示例 ’abc’ LIKE ’abc’ -- 返回true ’abc’ LIKE ’a%’ -- 返回true to_char() 把時間戳轉換成字符串 語法 to_char(timestamp, text) 示例 to_char(create_date, 'YYYY/MM/DD') to_char(create_date, ’HH12:MI:SS’) to_date() 把字符串轉換成日期 語法 to_date(text, text) 示例 to_date(’05 Jan 2015’,’DD Mon YYYY’) to_timestamp() 把字符串轉換成時間戳 語法 to_timestamp(text, text) 示例 to_timestamp(’05 Jan 2015’, ’DD Mon YYYY’) CASE 條件表達式, 相似於其餘編程語言中的if/else 語法1 CASE WHEN condition THEN result [WHEN ...] [ELSE result] END 示例1 CASE WHEN gender='male' THEN '程序猿' ELSE '程序媛' END 語法2(簡化形式) CASE expression WHEN value THEN result [WHEN ...] [ELSE result] END 示例2 CASE gender WHEN 'male' THEN '程序猿' ELSE '程序媛' END COALESCE() 返回第一個非NULL的參數,全部參數均爲NULL時則返回NULL 語法 COALESCE(value [, ...]) 示例 COALESCE(actual_qty,0) as actual_qty NULLIF() 若是value1與value2相等則返回NULL, 不然返回value1 語法 NULLIF(value1, value2) 示例 NULLIF(value, ’(none)’)