SELECT 中文man頁(yè)面
NAME
SELECT - 從表或視圖中取出若干行
SYNOPSIS
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] * | expression [ AS output_name ] [, ...] [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY expression [, ...] ] [ HAVING condition [, ...] ] [ { UNION | INTERSECT | EXCEPT } [ ALL ] select ] [ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ] [ LIMIT { count | ALL } ] [ OFFSET start ] [ FOR UPDATE [ OF table_name [, ...] ] ] where from_item can be one of: [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ] ( select ) [ AS ] alias [ ( column_alias [, ...] ) ] function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ] function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] ) from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ]
[Comment: FIXME: This last syntax is incorrect if the join type is an INNER or OUTER join (in which case one of NATURAL, ON ..., or USING ... is mandatory, not optional). What's the best way to fix this?]
DESCRIPTION 描述
SELECT 將從一個(gè)或更多表中返回記錄行。 SELECT 通常的處理如下:
- 1.
計(jì)算列出在 FROM 中的所有元素。(FROM 中的每個(gè)元素都是一個(gè)真正的或者虛擬的表。)如果在 FROM 列表里聲明了多過(guò)一個(gè)元素,那么他們就交叉連接在一起。(參閱下面的 FROM Clause [select(7)] )。- 2.
如果聲明了 WHERE 子句,那么在輸出中消除所有 不滿足條件的行。(參閱下面的 WHERE Clause [select(7)] )。- 3.
如果聲明了 GROUP BY 子句,輸出就分成匹配一個(gè)或多個(gè)數(shù)值的不同組里。 如果出現(xiàn)了 HAVING 子句,那么它消除那些不滿足給出條件的組。(參閱下面的 GROUP BY Clause [select(7)] 和 HAVING Clause [select(7)] )。- 4.
使用 UNION,INTERSECT, 和 EXCEPT,我們可以把多個(gè) SELECT 語(yǔ)句的輸出合并成一個(gè)結(jié)果集。UNION 操作符返回在兩個(gè)結(jié)果集或者其中一個(gè)中的行, INTERSECT 操作符返回嚴(yán)格地在兩個(gè)結(jié)果集中都有的行。 EXCEPT 操作符返回在第一個(gè)結(jié)果集中,但是不在第二個(gè)結(jié)果集中的行。不管哪種情況, 重復(fù)的行都被刪除,除非聲明了 ALL。(參閱下面的 UNION Clause [select(7)], INTERSECT Clause [select(l)], 和 EXCEPT Clause [select(7)] )。- 5.
實(shí)際輸出行的時(shí)候,SELECT 先為每個(gè)選出的行計(jì)算輸出表達(dá)式 (參閱下面的 SELECT List [select(7)] )。- 6.
如果聲明了 ORDER BY 子句,那么返回的行是按照指定的順序排序的。 如果沒(méi)有給出 ORDER BY,那么數(shù)據(jù)行是按照系統(tǒng)認(rèn)為可以最快生成的方法給出的。 (參閱下面的 ORDER BY Clause [select(7)] )。- 7.
如果給出了 LIMIT 或者 OFFSET 子句,那么 SELECT 語(yǔ)句只返回結(jié)果行的一個(gè)子集。(參閱下面的 LIMIT Clause [select(7)] )。- 8.
- DISTINCT 從結(jié)果中刪除那些重復(fù)的行。 DISTINCT ON 刪除那些匹配所有指定表達(dá)式的行。 ALL (缺省)將返回所有候選行,包括重復(fù)的。 (參閱下面的 DISTINCT Clause [select(7)] )。
- 9.
- FOR UPDATE 子句導(dǎo)致 SELECT 語(yǔ)句對(duì)并發(fā)的更新鎖住選定的行。(參閱下面的 FOR UPDATE Clause [select(7)] )。
你必須有 SELECT 權(quán)限用來(lái)從表中讀取數(shù)值。 使用 FOR UPDATE 還要求 UPDATE 權(quán)限。
PARAMETERS 參數(shù)
FROM 子句
FROM 子句為 SELECT 聲明一個(gè)或者多個(gè)源表。 如果聲明了多個(gè)源表,那么結(jié)果就是所有源表的笛卡兒積(交叉連接)。 但是通常我們會(huì)添加一些條件,把返回行限制成笛卡兒積的一個(gè)小的結(jié)果集。
FROM-子句可以包括:
- table_name
一個(gè)現(xiàn)存的表或視圖的名字(可以有模式修飾)。 如果聲明了ONLY,則只掃描該表。 如果沒(méi)有聲明ONLY,該表和所有其派生表(如果有的話)都被掃描。 可以在表名后面跟一個(gè)*來(lái)表示掃所有其后代表, 但在目前的版本里,這是缺省特性。 (在 PostgreSQL 7.1 以前的版本里,ONLY是缺省特性。) 缺省的特性可以通過(guò)修改配置選項(xiàng) sql_interitance 來(lái)改變。- alias
為那些包含別名的 FROM 項(xiàng)目取的別名。別名用于縮寫(xiě)或者在自連接中消除歧義(自連接里,同一個(gè)表掃描了多次)。 如果提供了別名,那么它就會(huì)完全隱藏表或者函數(shù)的實(shí)際名字; 比如,如果給出 FROM foo AS f,那么 SELECT 剩下的東西必須吧這個(gè) FROM 項(xiàng)以 f 而不是 foo 引用。如果寫(xiě)了別名, 我們也可以提供一個(gè)字段別名列表,這樣可以替換表中一個(gè)或者多個(gè)字段的名字。- select
一個(gè)子 SELECT 在 FROM 子句里出現(xiàn)的。 它的輸出作用好象是為這條 SELECT 命令在其生存期里創(chuàng)建一個(gè)臨時(shí)表。 請(qǐng)注意這個(gè)子 SELECT 必須用園括弧包圍。 并且必須給它加別名。- function_name
函數(shù)調(diào)用可以出現(xiàn)在 FROM 子句里。 (對(duì)于那些返回結(jié)果集的函數(shù)特別有用,但是任何函數(shù)都能用。) 這么做就好像在這個(gè) SELECT 命令的生命期中, 把函數(shù)的輸出創(chuàng)建為一個(gè)臨時(shí)表一樣。我們也可以使用別名。如果寫(xiě)了別名, 我們還可以寫(xiě)一個(gè)字段別名列表,為函數(shù)返回的復(fù)合類型的一個(gè)或多個(gè)屬性提供名字替換。 如果函數(shù)定義為了 record 數(shù)據(jù)類型, 那么必須出現(xiàn)一個(gè) AS 關(guān)鍵字或者別名,后面跟著一個(gè)字段定義列表, 形如:( column_name data_type [, ... ])。 這個(gè)字段定義列表必須匹配函數(shù)返回的字段的實(shí)際數(shù)目和類型。- join_type
- *
- [ INNER ] JOIN
- *
- LEFT [ OUTER ] JOIN
- *
- RIGHT [ OUTER ] JOIN
- *
- FULL [ OUTER ] JOIN
- *
- CROSS JOIN
之一。 就 INNER 和 OUTER 連接類型, 我們必須聲明一個(gè)連接條件,也就是說(shuō)一個(gè) NATURAL, ON join_condition, 或者 USING (join_column [, ...])。 見(jiàn)下文獲取它們的含義,對(duì)于 CROSS JOIN,這些子句都不能出現(xiàn)。
一個(gè) JOIN 子句,組合了兩個(gè) FROM 項(xiàng)。 必要時(shí)使用圓括弧以決定嵌套的順序。 如果沒(méi)有圓括弧,JOIN 的嵌套從左向右。 在任何情況下,JOIN 都比逗號(hào)分隔的 FROM 項(xiàng)綁定得更緊。
CROSS JOIN 和 INNER JOIN 生成一個(gè)簡(jiǎn)單的笛卡兒積,和你在 FROM 的頂層列出兩個(gè)項(xiàng)的結(jié)果相同。 CROSS JOIN 等效于 INNER JOIN ON (true), 也就是說(shuō),沒(méi)有被條件刪除的行。這種連接類型只是符號(hào)上的方便, 因?yàn)樗鼈兒湍阌煤?jiǎn)單的 FROM 和 WHERE 干的事情是一樣的。
LEFT OUTER JOIN 返回有條件的笛卡兒積(也就是說(shuō), 所有組合出來(lái)的行都通過(guò)了連接條件)中的行,加上左手邊的表中沒(méi)有對(duì)應(yīng)的右手邊表的行可以一起匹配通過(guò)連接條件的那些行。 這樣的左手邊的行擴(kuò)展成連接生成表的全長(zhǎng),方法是在那些右手邊表對(duì)應(yīng)的字段位置填上空。請(qǐng)注意,只有在決定那些行是匹配的時(shí)候, 之計(jì)算 JOIN 子句自己的條件。外層的條件是在這之后施加的。
對(duì)應(yīng)的是,RIGHT OUTER JOIN 返回所有連接出來(lái)的行, 加上每個(gè)不匹配的右手邊行(左邊用空值擴(kuò)展)。這只是一個(gè)符號(hào)上的便利,因?yàn)槲覀兛偸强梢园阉D(zhuǎn)換成一個(gè) LEFT OUTER JOIN, 只要把左邊和右邊的輸入對(duì)掉一下即可。
FULL OUTER JOIN 返回所有連接出來(lái)的行,加上每個(gè)不匹配的左手邊的行(右邊用空值擴(kuò)展), 加上每個(gè)不匹配的右手邊的行(左邊用空值擴(kuò)展)。
- ON join_condition
- join_condition 是一個(gè)表達(dá)式, 生成類型為 boolean 的結(jié)果(類似WHERE 子句), 表示連接中那些行被認(rèn)為是匹配的。
- USING (join_column [, ...])
一個(gè)形如 USING ( a, b, ... ) 的子句, 是ON left_table.a = right_table.a AND left_table.b = right_table.b ... 的縮寫(xiě)。同樣,USING 蘊(yùn)涵著:每對(duì)等效字段中只有一個(gè)包含在連接輸出中,而不是兩個(gè)都輸出的意思。- NATURAL
- NATURAL 是一個(gè) USING 列表的縮寫(xiě),這個(gè)列表說(shuō)的是兩個(gè)表中同名的的字段。
WHERE 子句
可選的 WHERE 條件有如下常見(jiàn)的形式:
WHERE condition
這里 condition 可以是任意生成類型為 boolean 的表達(dá)式。 任何不滿足這個(gè)條件的行都會(huì)從輸出中刪除。如果一個(gè)行的數(shù)值替換到條件的引用中計(jì)算出來(lái)的條件為真,那么該行就算滿足條件。
GROUP BY 子句
可選的 GROUP BY 子句的一般形式
GROUP BY expression [, ...]
GROUP BY 將把所有在組合了的表達(dá)式上共享同樣的值的行壓縮成一行。 expression 可以是一個(gè)輸入字段名字, 或者是一個(gè)輸入字段(SELECT 列表)的序號(hào),或者也可以是任意從輸入字段值形成的任意表達(dá)式。 在有歧義的情況下,一個(gè) GROUP BY 的名字將被解釋成輸入字段的名字,而不是輸出字段的名字。
如果使用了聚集函數(shù),那么就會(huì)對(duì)組成一組的所有行進(jìn)行計(jì)算,為每個(gè)組生成一個(gè)獨(dú)立的值(而如果沒(méi)有 GROUP BY, 那么聚集對(duì)選出來(lái)的所有行計(jì)算出一個(gè)值)。如果出現(xiàn)了 GROUP BY, 那么 SELECT 列表表達(dá)式中再引用那些沒(méi)有分組的字段就是非法的, 除非放在聚集函數(shù)里,因?yàn)閷?duì)于未分組的字段,可能會(huì)返回多個(gè)數(shù)值。
HAVING 子句
可選的 HAVING 子句有如下形式:
HAVING condition
這里 condition 和為 WHERE 子句里聲明的相同。
HAVING 去除了一些不滿足條件的組行。 HAVING 與 WHERE 不同: WHERE 在使用 GROUP BY 之前過(guò)濾出單獨(dú)的行,而 HAVING 過(guò)濾由 GROUP BY 創(chuàng)建的行。 在 condition 里引用的每個(gè)字段都必須無(wú)歧義地引用一個(gè)分組的行,除非引用出現(xiàn)在一個(gè)聚集函數(shù)里。
UNION 子句
UNION 子句的一般形式是:
select_statement UNION [ ALL ] select_statement
這里 select_statement 是任意沒(méi)有 ORDER BY,LIMIT,或者 FOR UPDATE 子句的 SELECT語(yǔ)句。 (如果用圓括弧包圍,ORDER BY 和 LIMIT 可以附著在子表達(dá)式里。 如果沒(méi)有圓括弧,這些子句將交給 UNION 的結(jié)果使用, 而不是給它們右手邊的輸入表達(dá)式。)
UNION 操作符計(jì)算那些涉及到的所有 SELECT 語(yǔ)句返回的行的結(jié)果聯(lián)合。 一個(gè)行如果至少在兩個(gè)結(jié)果集中的一個(gè)里面出現(xiàn),那么它就會(huì)在這兩個(gè)結(jié)果集的集合聯(lián)合中。 兩個(gè)做為 UNION 直接操作數(shù)的SELECT必須生成相同數(shù)目的字段, 并且對(duì)應(yīng)的字段必須有兼容的數(shù)據(jù)類型。
缺省地,UNION 的結(jié)果不包含任何重復(fù)的行,除非聲明了 ALL 子句。 ALL 制止了消除重復(fù)的動(dòng)作。
同一SELECT語(yǔ)句中的多個(gè) UNION 操作符是從左向右計(jì)算的, 除非用圓括弧進(jìn)行了標(biāo)識(shí)。
目前,F(xiàn)OR UPDATE 不能在 UNION 的結(jié)果或輸入中聲明。
INTERSECT 子句
INTERSECT 子句的一般形式是:
select_statement INTERSECT [ ALL ] select_statement
select_statement 是任何不帶 ORDER BY, LIMIT,或者 FOR UPDATE 子句的 SELECT 語(yǔ)句。
INTERSECT 計(jì)算涉及的 SELECT 語(yǔ)句返回的行的集合交集。 如果一個(gè)行在兩個(gè)結(jié)果集中都出現(xiàn),那么它就在兩個(gè)結(jié)果集的交集中。
NTERSECT 的結(jié)果不包含任何重復(fù)行,除非你聲明了 ALL 選項(xiàng)。 用了 ALL 以后,一個(gè)在左手邊的表里有 m 個(gè)重復(fù)而在右手邊表里有 n 個(gè)重復(fù)的行將出現(xiàn) min(m,n) 次。
除非用圓括號(hào)指明順序, 同一 SELECT 語(yǔ)句中的多個(gè) INTERSECT 操作符是從左向右計(jì)算的。 INTERSECT 比 UNION 綁定得更緊 --- 也就是說(shuō) A UNION B INTERSECT C 將讀做 A UNION (B INTERSECT C),除非你用圓括弧聲明。
EXCEPT 子句
EXCEPT 子句有如下的通用形式:
select_statement EXCEPT [ ALL ] select_statement
這里 fIselect_statement 是任何沒(méi)有 ORDER BY,LIMIT,或者 FOR UPDATE 子句的 SELECT 表達(dá)式。
EXCEPT 操作符計(jì)算存在于左邊SELECT 語(yǔ)句的輸出而不存在于右邊語(yǔ)句輸出的行。
EXCEPT 的結(jié)果不包含任何重復(fù)的行,除非聲明了 ALL 選項(xiàng)。 使用 ALL 時(shí),一個(gè)在左手邊表中有 m 個(gè)重復(fù)而在右手邊表中有 n 個(gè)重復(fù)的行將出現(xiàn) max(m-n,0) 次。
除非用圓括弧指明順序,同一 SELECT 語(yǔ)句中的多個(gè) EXCEPT 操作符是從左向右計(jì)算的。 EXCEPT 和 UNION 綁定級(jí)別相同。
SELECT 列表
SELECT 列表(在關(guān)鍵字 SELECT 和 FROM) 之間的東西)聲明一個(gè)表達(dá)式,這個(gè)表達(dá)式形成 SELECT 語(yǔ)句的輸出行。這個(gè)表達(dá)式可以(通常也的確是)引用那些在 FROM 子句里計(jì)算的字段。 通過(guò)使用 AS output_name, 我們可以為一個(gè)輸出行聲明另外一個(gè)名字。這個(gè)名字主要用做顯示該行的標(biāo)簽。 它也可以在 ORDER BY 和 GROUP BY 子句里當(dāng)作字段值的引用, 但是不能在 WHERE 或者 HAVING 子句里這么用;在那里,你必須寫(xiě)出表達(dá)式。
除了表達(dá)式之外,我們也可以在輸出列表上寫(xiě)一個(gè) * 表示選出的行的所有字段的縮寫(xiě)。同樣,我們可以寫(xiě) table_name.* 作為來(lái)自某個(gè)特定表的字段的縮寫(xiě)。
ORDER BY 子句
可選的 ORDER BY 子句有下面的一般形式:
ORDER BY expression [ ASC | DESC | USING operator ] [, ...]
expression 可以是一個(gè)輸出字段(SELECT 列表)的名字或者序號(hào), 或者也可以是用輸入字段的數(shù)值組成的任意表達(dá)式。
ORDER BY 子句導(dǎo)致結(jié)果行根據(jù)指定的表達(dá)式進(jìn)行排序。 如果根據(jù)最左邊的表達(dá)式,兩行的結(jié)果相同,那么就根據(jù)下一個(gè)表達(dá)式進(jìn)行比較, 依此類推。如果對(duì)于所有聲明的表達(dá)式他們都相同,那么以隨機(jī)順序返回。
序數(shù)指的是列/字段按順序(從左到右)的位置。 這個(gè)特性讓我們可以對(duì)沒(méi)有唯一名稱的列/字段進(jìn)行排序。 這一點(diǎn)從來(lái)不是必須的, 因?yàn)榭偸强梢酝ㄟ^(guò) AS 子句給一個(gè)要計(jì)算的列/字段賦予一個(gè)名稱。
在 ORDER BY 里還可以使用任意表達(dá)式, 包括那些沒(méi)有出現(xiàn)在SELECT結(jié)果列表里面的字段。 因此下面的語(yǔ)句現(xiàn)在是合法的:
SELECT name FROM distributors ORDER BY code;
這個(gè)特性的一個(gè)局限就是應(yīng)用于 UNION,INTERSECT, 或者 EXCEPT 查詢的 ORDER BY 子句只能在一個(gè)輸出字段名或者數(shù)字上聲明,而不能在一個(gè)表達(dá)式上聲明。
請(qǐng)注意如果一個(gè) ORDER BY 表達(dá)式是一個(gè)簡(jiǎn)單名稱, 同時(shí)匹配結(jié)果字段和輸入字段, ORDER BY 將把它解釋成結(jié)果字段名稱。 這和 GROUP BY 在同樣情況下做的選擇正相反。 這樣的不一致是由 SQL 標(biāo)準(zhǔn)強(qiáng)制的。
我們可以給 ORDER BY 子句里每個(gè)列/字段加一個(gè)關(guān)鍵字 DESC (降序)或 ASC(升序)。如果不聲明, ASC 是缺省。 我們還可以在 USING 子句里聲明一個(gè)排序操作符來(lái)實(shí)現(xiàn)排序。 ASC 等效于使用 USING < 而 DESC 等效于使用 USING >。 (But the creator of a user-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names.)
在一個(gè)域里,空值排序時(shí)排在其它數(shù)值前面。換句話說(shuō),升序排序時(shí), 空值排在末尾,而降序排序時(shí)空值排在開(kāi)頭。
字符類型的數(shù)據(jù)是按照區(qū)域相關(guān)的字符集順序排序的,這個(gè)區(qū)域是在數(shù)據(jù)庫(kù)集群初始化的時(shí)候建立的。
LIMIT 子句
LIMIT 子句由兩個(gè)獨(dú)立的子句組成:
LIMIT { count | ALL } OFFSET start
這里 count 聲明返回的最大行數(shù),而 start 聲明開(kāi)始返回行之前忽略的行數(shù)。
.PP
LIMIT 允許你檢索由查詢其他部分生成的行的某一部分。 如果給出了限制計(jì)數(shù),那么返回的行數(shù)不會(huì)超過(guò)哪個(gè)限制。 如果給出了一個(gè)偏移量,那么開(kāi)始返回行之前會(huì)忽略那個(gè)數(shù)量的行。
在使用 LIMIT 時(shí), 一個(gè)好習(xí)慣是使用一個(gè) ORDER BY 子句把結(jié)果行限制成一個(gè)唯一的順序。 否則你會(huì)得到無(wú)法預(yù)料的查詢返回的子集 --- 你可能想要第十行到第二十行, 但以什么順序?除非你聲明 ORDER BY,否則你不知道什么順序。
查詢優(yōu)化器在生成查詢規(guī)劃時(shí)把 LIMIT 考慮進(jìn)去了, 所以你很有可能因給出的 LIMIT 和 OFFSET 值不同而得到不同的規(guī)劃(生成不同的行序)。 因此用不同的 LIMIT/OFFSET 值選擇不同的查詢結(jié)果的子集將不會(huì)產(chǎn)生一致的結(jié)果, 除非你用 ORDER BY 強(qiáng)制生成一個(gè)可預(yù)計(jì)的結(jié)果順序。 這可不是毛??;這是 SQL 生來(lái)的特點(diǎn),因?yàn)槌怯昧?nbsp;ORDER BY 約束順序, SQL 不保證查詢生成的結(jié)果有任何特定的順序。
DISTINCT 子句
如果聲明了 DISTINCT,那么就從結(jié)果集中刪除所有重復(fù)的行(每個(gè)有重復(fù)的組都保留一行)。 ALL 聲明相反的作用:所有行都被保留;這個(gè)是缺省。
DISTINCT ON ( expression [, ...] ) 只保留那些在給出的表達(dá)式上運(yùn)算出相同結(jié)果的行集合中的第一行。 DISTINCT ON 表達(dá)式是使用與 ORDER BY (見(jiàn)上文) 相同的規(guī)則進(jìn)行解釋的。請(qǐng)注意,除非我們使用了 ORDER BY 來(lái)保證我們需要的行首先出現(xiàn),否則,每個(gè) "第一行" 是不可預(yù)測(cè)的。 比如,
SELECT DISTINCT ON (location) location, time, report FROM weather_reports ORDER BY location, time DESC;
為每個(gè)地點(diǎn)檢索最近的天氣報(bào)告。但是如果我們沒(méi)有使用 ORDER BY 來(lái)強(qiáng)制對(duì)每個(gè)地點(diǎn)的時(shí)間值進(jìn)行降序排序,那么我們就會(huì)得到每個(gè)地點(diǎn)的不知道什么時(shí)候的報(bào)告。
DISTINCT ON 表達(dá)式必須匹配最左邊的 ORDER BY 表達(dá)式。 ORDER BY 子句將通常包含額外的表達(dá)式來(lái)判斷每個(gè) DISTINCT ON 組里面需要的行的優(yōu)先級(jí)。
FOR UPDATE 子句
FOR UPDATE 子句有下面的形式
FOR UPDATE [ OF table_name [, ...] ]
FOR UPDATE 令那些被 SELECT 語(yǔ)句檢索出來(lái)的行被鎖住,就像要更新一樣。 這樣就避免它們?cè)诋?dāng)前事務(wù)結(jié)束前被其它事務(wù)修改或者刪除; 也就是說(shuō),其它視圖 UPDATE,DELETE, 或者 SELECT FOR UPDATE 這些行的事務(wù)將被阻塞, 直到當(dāng)前事務(wù)結(jié)束。同樣,如果一個(gè)來(lái)自其它事務(wù)的 UPDATE, DELETE,或者 SELECT FOR UPDATE 已經(jīng)鎖住了某個(gè)或某些選定的行,SELECT FOR UPDATE 將等到那些事務(wù)結(jié)束, 并且將隨后鎖住并返回更新的行(或者不返回行,如果行已經(jīng)被刪除)。更多的討論參閱 Chapter 12 ``Concurrency Control'' 。
如果特定的表在 FOR UPDATE 中,那么只有來(lái)自這些表中的行才被鎖住; 任何在 SELECT 中使用的其它表都只是和平常一樣讀取。
FOR UPDATE 不能在那些無(wú)法使用獨(dú)立的表數(shù)據(jù)行清晰標(biāo)識(shí)返回行的環(huán)境里; 比如,它不能和聚集一起使用。
FOR UPDATE 可以在 LIMIT 前面出現(xiàn), 主要是為了和 7.3 之前的 PostgreSQL 兼容。 不過(guò),它在 LIMIT 后面執(zhí)行更高效,因此我們建議放在 LIMIT 后面。
EXAMPLES 例子
將表 films 和表 distributors 連接在一起:
SELECT f.title, f.did, d.name, f.date_prod, f.kind FROM distributors d, films f WHERE f.did = d.did title | did | name | date_prod | kind -------------------+-----+--------------+------------+---------- The Third Man | 101 | British Lion | 1949-12-23 | Drama The African Queen | 101 | British Lion | 1951-08-11 | Romantic ...
統(tǒng)計(jì)用kind 分組的所有電影和組的列/字段的 len(長(zhǎng)度)的和:
SELECT kind, sum(len) AS total FROM films GROUP BY kind; kind | total ----------+------- Action | 07:34 Comedy | 02:58 Drama | 14:28 Musical | 06:42 Romantic | 04:38
統(tǒng)計(jì)所有電影(films),組的列/字段 len(長(zhǎng)度)的和,用 kind 分組并且顯示小于5小時(shí)的組總和:
SELECT kind, sum(len) AS total FROM films GROUP BY kind HAVING sum(len) < interval '5 hours'; kind | total ----------+------- Comedy | 02:58 Romantic | 04:38
下面兩個(gè)例子是根據(jù)第二列(name)的內(nèi)容對(duì)單獨(dú)的結(jié)果排序的經(jīng)典的方法:
SELECT * FROM distributors ORDER BY name; SELECT * FROM distributors ORDER BY 2; did | name -----+------------------ 109 | 20th Century Fox 110 | Bavaria Atelier 101 | British Lion 107 | Columbia 102 | Jean Luc Godard 113 | Luso films 104 | Mosfilm 103 | Paramount 106 | Toho 105 | United Artists 111 | Walt Disney 112 | Warner Bros. 108 | Westward
下面這個(gè)例子演示如何獲得表 distributors 和 actors的連接, 只將每個(gè)表中以字母 W 開(kāi)頭的取出來(lái)。 因?yàn)橹蝗×瞬幌嚓P(guān)的行,所以關(guān)鍵字 ALL 被省略了:
distributors: actors: did | name id | name -----+-------------- ----+---------------- 108 | Westward 1 | Woody Allen 111 | Walt Disney 2 | Warren Beatty 112 | Warner Bros. 3 | Walter Matthau ... ... SELECT distributors.name FROM distributors WHERE distributors.name LIKE 'W%' UNION SELECT actors.name FROM actors WHERE actors.name LIKE 'W%'; name ---------------- Walt Disney Walter Matthau Warner Bros. Warren Beatty Westward Woody Allen
這個(gè)例子顯示了如何在 FROM 子句中使用一個(gè)函數(shù), 包括帶有和不帶字段定義列表的。
CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS ' SELECT * FROM distributors WHERE did = $1; SELECT * FROM distributors(111); did | name -----+------------- 111 | Walt Disney CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS ' SELECT * FROM distributors WHERE did = $1; SELECT * FROM distributors_2(111) AS (f1 int, f2 text); f1 | f2 -----+------------- 111 | Walt Disney
COMPATIBILITY 兼容性
當(dāng)然,SELECT 語(yǔ)句和 SQL 標(biāo)準(zhǔn)兼容。但是還有一些擴(kuò)展和一些缺少的特性。
省略 FROM 子句
PostgreSQL 允許我們?cè)谝粋€(gè)查詢里省略 FROM 子句。 它的最直接用途就是計(jì)算簡(jiǎn)單的常量表達(dá)式的結(jié)果:
SELECT 2+2; ?column? ---------- 4
其它有些 SQL 數(shù)據(jù)庫(kù)不能這么做,除非引入一個(gè)單行的偽表做 SELECT 的數(shù)據(jù)源。
這個(gè)特性的另外一個(gè)不太明顯的用途是把一個(gè)普通的從一個(gè)或多個(gè)表的 SELECT 縮寫(xiě):
SELECT distributors.* WHERE distributors.name = 'Westward'; did | name -----+---------- 108 | Westward
這樣也可以運(yùn)行是因?yàn)槲覀兘o SELECT 中引用了但沒(méi)有在 FROM 中提到的每個(gè)表都加了一個(gè)隱含的 FROM 項(xiàng)。
盡管這是個(gè)很方便的寫(xiě)法,但它卻容易誤用。 比如,下面的查詢
SELECT distributors.* FROM distributors d;
可能就是個(gè)錯(cuò)誤;用戶最有可能的意思是
SELECT d.* FROM distributors d;
而不是下面的他實(shí)際上得到的無(wú)約束的連接
SELECT distributors.* FROM distributors d, distributors distributors;
為了幫助檢測(cè)這種錯(cuò)誤, PostgreSQL 以及以后的版本將在你使用一條即有隱含 FROM 特性又有明確的 FROM 子句的查詢的時(shí)候給出警告。 Also, it is possible to disable the implicit-FROM feature by setting the ADD_MISSING_FROM parameter to false.
AS 關(guān)鍵字
在 SQL 標(biāo)準(zhǔn)里,可選的關(guān)鍵字 AS 是多余的,可以忽略掉而不對(duì)語(yǔ)句產(chǎn)生任何影響。 PostgreSQL 分析器在重命名列/字段時(shí)需要這個(gè)關(guān)鍵字, 因?yàn)轭愋蛿U(kuò)展的特性會(huì)導(dǎo)致在這個(gè)環(huán)境里的歧義。 不過(guò),AS 在 FROM 項(xiàng)里是可選的。
GROUP BY 和 ORDER BY 里可用的名字空間
在 SQL92 標(biāo)準(zhǔn)里,ORDER BY 子句只能使用結(jié)果字段名或者編號(hào), 而 GROUP BY 子句只能用基于輸入字段名的表達(dá)式。 PostgreSQL 對(duì)這兩個(gè)子句都進(jìn)行了擴(kuò)展, 允許另外一種選擇(但是如果存在歧義,則使用標(biāo)準(zhǔn)的解釋)。 PostgreSQL 還允許兩個(gè)子句聲明任意的表達(dá)式。 請(qǐng)注意在表達(dá)式中出現(xiàn)的名字強(qiáng)總是被當(dāng)作輸入字段名,而不是結(jié)果字段名。
SQL99 uses a slightly different definition which is not upward compatible with SQL92. In most cases, however, PostgreSQL will interpret an ORDER BY or GROUP BY expression the same way SQL99 does.
非標(biāo)準(zhǔn)子句
DISTINCT ON, LIMIT, 和 OFFSET 都沒(méi)有在 SQL 標(biāo)準(zhǔn)中定義。
#p#
NAME
SELECT - retrieve rows from a table or view
SYNOPSIS
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] * | expression [ AS output_name ] [, ...] [ FROM from_item [, ...] ] [ WHERE condition ] [ GROUP BY expression [, ...] ] [ HAVING condition [, ...] ] [ { UNION | INTERSECT | EXCEPT } [ ALL ] select ] [ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ] [ LIMIT { count | ALL } ] [ OFFSET start ] [ FOR UPDATE [ OF table_name [, ...] ] ] where from_item can be one of: [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ] ( select ) [ AS ] alias [ ( column_alias [, ...] ) ] function_name ( [ argument [, ...] ] ) [ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ] function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] ) from_item [ NATURAL ] join_type from_item [ ON join_condition | USING ( join_column [, ...] ) ]
[Comment: FIXME: This last syntax is incorrect if the join type is an INNER or OUTER join (in which case one of NATURAL, ON ..., or USING ... is mandatory, not optional). What's the best way to fix this?]
DESCRIPTION
SELECT retrieves rows from one or more tables. The general processing of SELECT is as follows:
- 1.
- All elements in the FROM list are computed. (Each element in the FROM list is a real or virtual table.) If more than one element is specified in the FROM list, they are cross-joined together. (See FROM Clause [select(7)] below.)
- 2.
- If the WHERE clause is specified, all rows that do not satisfy the condition are eliminated from the output. (See WHERE Clause [select(7)] below.)
- 3.
- If the GROUP BY clause is specified, the output is divided into groups of rows that match on one or more values. If the HAVING clause is present, it eliminates groups that do not satisfy the given condition. (See GROUP BY Clause [select(7)] and HAVING Clause [select(7)] below.)
- 4.
- Using the operators UNION, INTERSECT, and EXCEPT, the output of more than one SELECT statement can be combined to form a single result set. The UNION operator returns all rows that are in one or both of the result sets. The INTERSECT operator returns all rows that are strictly in both result sets. The EXCEPT operator returns the rows that are in the first result set but not in the second. In all three cases, duplicate rows are eliminated unless ALL is specified. (See UNION Clause [select(7)], INTERSECT Clause [select(l)], and EXCEPT Clause [select(7)] below.)
- 5.
- The actual output rows are computed the SELECT output expressions for each selected row. (See SELECT List [select(7)] below.)
- 6.
- If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. (See ORDER BY Clause [select(7)] below.)
- 7.
- If the LIMIT or OFFSET clause is specified, the SELECT statement only returns a subset of the result rows. (See LIMIT Clause [select(7)] below.)
- 8.
- DISTINCT eliminates duplicate rows from the result. DISTINCT ON eliminates rows that match on all the specified expressions. ALL (the default) will return all candidate rows, including duplicates. (See DISTINCT Clause [select(7)] below.)
- 9.
- The FOR UPDATE clause causes the SELECT statement to lock the selected rows against concurrent updates. (See FOR UPDATE Clause [select(7)] below.)
You must have SELECT privilege on a table to read its values. The use of FOR UPDATE requires UPDATE privilege as well.
PARAMETERS
FROM CLAUSE
The FROM clause specifies one or more source tables for the SELECT. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources. But usually qualification conditions are added to restrict the returned rows to a small subset of the Cartesian product.
FROM-clause elements can contain:
- table_name
- The name (optionally schema-qualified) of an existing table or view. If ONLY is specified, only that table is scanned. If ONLY is not specified, the table and all its descendant tables (if any) are scanned. * can be appended to the table name to indicate that descendant tables are to be scanned, but in the current version, this is the default behavior. (In releases before 7.1, ONLY was the default behavior.) The default behavior can be modified by changing the sql_interitance configuration option.
- alias
- A substitute name for the FROM item containing the alias. An alias is used for brevity or to eliminate ambiguity for self-joins (where the same table is scanned multiple times). When an alias is provided, it completely hides the actual name of the table or function; for example given FROM foo AS f, the remainder of the SELECT must refer to this FROM item as f not foo. If an alias is written, a column alias list can also be written to provide substitute names for one or more columns of the table.
- select
- A sub-SELECT can appear in the FROM clause. This acts as though its output were created as a temporary table for the duration of this single SELECT command. Note that the sub-SELECT must be surrounded by parentheses, and an alias must be provided for it.
- function_name
- Function calls can appear in the FROM clause. (This is especially useful for functions that return result sets, but any function can be used.) This acts as though its output were created as a temporary table for the duration of this single SELECT command. An alias may also be used. If an alias is written, a column alias list can also be written to provide substitute names for one or more attributes of the function's composite return type. If the function has been defined as returning the record data type, then an alias or the key word AS must be present, followed by a column definition list in the form ( column_name data_type [, ... ] ). The column definition list must match the actual number and types of columns returned by the function.
- join_type
- One of
- *
- [ INNER ] JOIN
- *
- LEFT [ OUTER ] JOIN
- *
- RIGHT [ OUTER ] JOIN
- *
- FULL [ OUTER ] JOIN
- *
- CROSS JOIN
For the INNER and OUTER join types, a join condition must be specified, namely exactly one of NATURAL, ON join_condition, or USING (join_column [, ...]). See below for the meaning. For CROSS JOIN, none of these clauses may appear.
A JOIN clause, combines two FROM items. (Use parentheses if necessary to determine the order of nesting.)
CROSS JOIN and INNER JOIN produce a simple Cartesian product, the same as you get from listing the two items at the top level of FROM. CROSS JOIN is equivalent to INNER JOIN ON (true), that is, no rows are removed by qualification. These join types are just a notational convenience, since they do nothing you couldn't do with plain FROM and WHERE.
LEFT OUTER JOIN returns all rows in the qualified Cartesian product (i.e., all combined rows that pass its join condition), plus one copy of each row in the left-hand table for which there was no right-hand row that passed the join condition. This left-hand row is extended to the full width of the joined table by inserting null values for the right-hand columns. Note that only the JOIN clauses own condition is considered while deciding which rows have matches. Outer conditions are applied afterwards.
Conversely, RIGHT OUTER JOIN returns all the joined rows, plus one row for each unmatched right-hand row (extended with nulls on the left). This is just a notational convenience, since you could convert it to a LEFT OUTER JOIN by switching the left and right inputs.
FULL OUTER JOIN returns all the joined rows, plus one row for each unmatched left-hand row (extended with nulls on the right), plus one row for each unmatched right-hand row (extended with nulls on the left).
- ON join_condition
- join_condition is an expression resulting in a value of type boolean (similar to a WHERE clause) that specifies which rows in a join are considered to match.
- USING (join_column [, ...])
- A clause of the form USING ( a, b, ... ) is shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b .... Also, USING implies that only one of each pair of equivalent columns will be included in the join output, not both.
- NATURAL
- NATURAL is shorthand for a USING list that mentions all columns in the two tables that have the same names.
WHERE CLAUSE
The optional WHERE clause has the general form
WHERE condition
where condition is any expression that evaluates to a result of type boolean. Any row that does not satisfy this condition will be eliminated from the output. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references.
GROUP BY CLAUSE
The optional GROUP BY clause has the general form
GROUP BY expression [, ...]
GROUP BY will condense into a single row all selected rows that share the same values for the grouped expressions. expression can be an input column name, or the name or ordinal number of an output column (SELECT list), or it can be an arbitrary expression formed from input-column values. In case of ambiguity, a GROUP BY name will be interpreted as an input-column name rather than an output column name.
Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group (whereas without GROUP BY, an aggregate produces a single value computed across all the selected rows). When GROUP BY is present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions, since there would be more than one possible value to return for an ungrouped column.
HAVING CLAUSE
The optional HAVING clause has the general form
HAVING condition
where condition is the same as specified for the WHERE clause.
HAVING eliminates group rows that do not satisfy the condition. HAVING is different from WHERE: WHERE filters individual rows before the application of GROUP BY, while HAVING filters group rows created by GROUP BY. Each column referenced in condition must unambiguously reference a grouping column, unless the reference appears within an aggregate function.
UNION CLAUSE
The UNION clause has this general form:
select_statement UNION [ ALL ] select_statement
select_statement is any SELECT statement without an ORDER BY, LIMIT, or FOR UPDATE clause. (ORDER BY and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
The UNION operator computes the set union of the rows returned by the involved SELECT statements. A row is in the set union of two result sets if it appears in at least one of the result sets. The two SELECT statements that represent the direct operands of the UNION must produce the same number of columns, and corresponding columns must be of compatible data types.
The result of UNION does not contain any duplicate rows unless the ALL option is specified. ALL prevents elimination of duplicates.
Multiple UNION operators in the same SELECT statement are evaluated left to right, unless otherwise indicated by parentheses.
Currently, FOR UPDATE may not be specified either for a UNION result or for the inputs of UNION.
INTERSECT CLAUSE
The INTERSECT clause has this general form:
select_statement INTERSECT [ ALL ] select_statement
select_statement is any SELECT statement without an ORDER BY, LIMIT, or FOR UPDATE clause.
The INTERSECT operator computes the set intersection of the rows returned by the involved SELECT statements. A row is in the intersection of two result sets if it appears in both result sets.
The result of INTERSECT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear min(m,n) times in the result set.
Multiple INTERSECT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. INTERSECT binds more tightly than UNION. That is, A UNION B INTERSECT C will be read as A UNION (B INTERSECT C).
EXCEPT CLAUSE
The EXCEPT clause has this general form:
select_statement EXCEPT [ ALL ] select_statement
select_statement is any SELECT statement without an ORDER BY, LIMIT, or FOR UPDATE clause.
The EXCEPT operator computes the set of rows that are in the result of the left SELECT statement but not in the result of the right one.
The result of EXCEPT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear max(m-n,0) times in the result set.
Multiple EXCEPT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. EXCEPT binds at the same level as UNION.
SELECT LIST
The SELECT list (between the key words SELECT and FROM) specifies expressions that form the output rows of the SELECT statement. The expressions can (and usually do) refer to columns computed in the FROM clause. Using the clause AS output_name, another name can be specified for an output column. This name is primarily used to label the column for display. It can also be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.
Instead of an expression, * can be written in the output list as a shorthand for all the columns of the selected rows. Also, one can write table_name.* as a shorthand for the columns coming from just that table.
ORDER BY CLAUSE
The optional ORDER BY clause has this general form:
ORDER BY expression [ ASC | DESC | USING operator ] [, ...]
expression can be the name or ordinal number of an output column (SELECT list), or it can be an arbitrary expression formed from input-column values.
The ORDER BY clause causes the result rows to be sorted according to the specified expressions. If two rows are equal according to the leftmost expression, the are compared according to the next expression and so on. If they are equal according to all specified expressions, they are returned in random order.
The ordinal number refers to the ordinal (left-to-right) position of the result column. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name. This is never absolutely necessary because it is always possible to assign a name to a result column using the AS clause.
It is also possible to use arbitrary expressions in the ORDER BY clause, including columns that do not appear in the SELECT result list. Thus the following statement is valid:
SELECT name FROM distributors ORDER BY code;
A limitation of this feature is that an ORDER BY clause applying to the result of a UNION, INTERSECT, or EXCEPT clause may only specify an output column name or number, not an expression.
If an ORDER BY expression is a simple name that matches both a result column name and an input column name, ORDER BY will interpret it as the result column name. This is the opposite of the choice that GROUP BY will make in the same situation. This inconsistency is made to be compatible with the SQL standard.
Optionally one may add the key word ASC (ascending) or DESC (descending) after each expression in the ORDER BY clause. If not specified, ASC is assumed by default. Alternatively, a specific ordering operator name may be specified in the USING clause. ASC is usually equivalent to USING < and DESC is usually equivalent to USING >. (But the creator of a user-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names.)
The null value sorts higher than any other value. In other words, with ascending sort order, null values sort at the end, and with descending sort order, null values sort at the beginning.
Character-string data is sorted according to the locale-specific collation order that was established when the database cluster was initialized.
LIMIT CLAUSE
The LIMIT clause consists of two independent clauses:
LIMIT { count | ALL } OFFSET start
count specifies the maximum number of rows to return, and start specifies the number of rows to skip before starting to return rows.
When using LIMIT, it is a good idea to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows---you may be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You don't know what ordering unless you specify ORDER BY.
The query planner takes LIMIT into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you use for LIMIT and OFFSET. Thus, using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order.
DISTINCT CLAUSE
If DISTINCT is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates). ALL specifies the opposite: all rows are kept; that is the default.
DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the ``first row'' of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. For example,
SELECT DISTINCT ON (location) location, time, report FROM weather_reports ORDER BY location, time DESC;
retrieves the most recent weather report for each location. But if we had not used ORDER BY to force descending order of time values for each location, we'd have gotten a report from an unpredictable time for each location.
FOR UPDATE CLAUSE
The FOR UPDATE clause has this form:
FOR UPDATE [ OF table_name [, ...] ]
FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being modified or deleted by other transactions until the current transaction ends. That is, other transactions that attempt UPDATE, DELETE, or SELECT FOR UPDATE of these rows will be blocked until the current transaction ends. Also, if an UPDATE, DELETE, or SELECT FOR UPDATE from another transaction has already locked a selected row or rows, SELECT FOR UPDATE will wait for the other transaction to complete, and will then lock and return the updated row (or no row, if the row was deleted). For further discussion see the chapter called ``Concurrency Control'' in the documentation.
If specific tables are named in FOR UPDATE, then only rows coming from those tables are locked; any other tables used in the SELECT are simply read as usual.
FOR UPDATE cannot be used in contexts where returned rows can't be clearly identified with individual table rows; for example it can't be used with aggregation.
FOR UPDATE may appear before LIMIT for compatibility with PostgreSQL versions before 7.3. It effectively executes after LIMIT, however, and so that is the recommended place to write it.
EXAMPLES
To join the table films with the table distributors:
SELECT f.title, f.did, d.name, f.date_prod, f.kind FROM distributors d, films f WHERE f.did = d.did title | did | name | date_prod | kind -------------------+-----+--------------+------------+---------- The Third Man | 101 | British Lion | 1949-12-23 | Drama The African Queen | 101 | British Lion | 1951-08-11 | Romantic ...
To sum the column len of all films and group the results by kind:
SELECT kind, sum(len) AS total FROM films GROUP BY kind; kind | total ----------+------- Action | 07:34 Comedy | 02:58 Drama | 14:28 Musical | 06:42 Romantic | 04:38
To sum the column len of all films, group the results by kind and show those group totals that are less than 5 hours:
SELECT kind, sum(len) AS total FROM films GROUP BY kind HAVING sum(len) < interval '5 hours'; kind | total ----------+------- Comedy | 02:58 Romantic | 04:38
The following two examples are identical ways of sorting the individual results according to the contents of the second column (name):
SELECT * FROM distributors ORDER BY name; SELECT * FROM distributors ORDER BY 2; did | name -----+------------------ 109 | 20th Century Fox 110 | Bavaria Atelier 101 | British Lion 107 | Columbia 102 | Jean Luc Godard 113 | Luso films 104 | Mosfilm 103 | Paramount 106 | Toho 105 | United Artists 111 | Walt Disney 112 | Warner Bros. 108 | Westward
This example shows how to obtain the union of the tables distributors and actors, restricting the results to those that begin with letter W in each table. Only distinct rows are wanted, so the key word ALL is omitted.
distributors: actors: did | name id | name -----+-------------- ----+---------------- 108 | Westward 1 | Woody Allen 111 | Walt Disney 2 | Warren Beatty 112 | Warner Bros. 3 | Walter Matthau ... ... SELECT distributors.name FROM distributors WHERE distributors.name LIKE 'W%' UNION SELECT actors.name FROM actors WHERE actors.name LIKE 'W%'; name ---------------- Walt Disney Walter Matthau Warner Bros. Warren Beatty Westward Woody Allen
This example shows how to use a function in the FROM clause, both with and without a column definition list.
CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS ' SELECT * FROM distributors WHERE did = $1; SELECT * FROM distributors(111); did | name -----+------------- 111 | Walt Disney CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS ' SELECT * FROM distributors WHERE did = $1; SELECT * FROM distributors_2(111) AS (f1 int, f2 text); f1 | f2 -----+------------- 111 | Walt Disney
COMPATIBILITY
Of course, the SELECT statement is compatible with the SQL standard. But there are some extensions and some missing features.
OMITTED FROM CLAUSES
PostgreSQL allows one to omit the FROM clause. It has a straightforward use to compute the results of simple expressions:
SELECT 2+2; ?column? ---------- 4
Some other SQL databases cannot do this except by introducing a dummy one-row table from which to do the SELECT.
A less obvious use is to abbreviate a normal SELECT from tables:
SELECT distributors.* WHERE distributors.name = 'Westward'; did | name -----+---------- 108 | Westward
This works because an implicit FROM item is added for each table that is referenced in other parts of the SELECT statement but not mentioned in FROM.
While this is a convenient shorthand, it's easy to misuse. For example, the command
SELECT distributors.* FROM distributors d;
is probably a mistake; most likely the user meant
SELECT d.* FROM distributors d;
rather than the unconstrained join
SELECT distributors.* FROM distributors d, distributors distributors;
that he will actually get. To help detect this sort of mistake, PostgreSQL will warn if the implicit-FROM feature is used in a SELECT statement that also contains an explicit FROM clause. Also, it is possible to disable the implicit-FROM feature by setting the ADD_MISSING_FROM parameter to false.
THE AS KEY WORD
In the SQL standard, the optional key word AS is just noise and can be omitted without affecting the meaning. The PostgreSQL parser requires this key word when renaming output columns because the type extensibility features lead to parsing ambiguities without it. AS is optional in FROM items, however.
NAMESPACE AVAILABLE TO GROUP BY AND ORDER BY
In the SQL92 standard, an ORDER BY clause may only use result column names or numbers, while a GROUP BY clause may only use expressions based on input column names. PostgreSQL extends each of these clauses to allow the other choice as well (but it uses the standard's interpretation if there is ambiguity). PostgreSQL also allows both clauses to specify arbitrary expressions. Note that names appearing in an expression will always be taken as input-column names, not as result-column names.
SQL99 uses a slightly different definition which is not upward compatible with SQL92. In most cases, however, PostgreSQL will interpret an ORDER BY or GROUP BY expression the same way SQL99 does.
NONSTANDARD CLAUSES
The clauses DISTINCT ON, LIMIT, and OFFSET are not defined in the SQL standard.