select.7
来自「PostgreSQL 8.2中增加了很多企业用户所需要的功能和性能上的提高,其开」· 7 代码 · 共 886 行 · 第 1/2 页
7
886 行
.sp.nfORDER BY \fIexpression\fR [ ASC | DESC | USING \fIoperator\fR ] [, ...].sp.fi\fIexpression\fR can be thename or ordinal number of an output column(\fBSELECT\fR list item), or it can be an arbitraryexpression formed from input-column values..PPThe ORDER BY clause causes the result rows tobe sorted according to the specified expressions. If two rows areequal according to the leftmost expression, the are comparedaccording to the next expression and so on. If they are equalaccording to all specified expressions, they are returned inan implementation-dependent order..PPThe ordinal number refers to the ordinal (left-to-right) positionof the result column. This feature makes it possible to define anordering on the basis of a column that does not have a uniquename. This is never absolutely necessary because it is alwayspossible to assign a name to a result column using theAS clause..PPIt is also possible to use arbitrary expressions in theORDER BY clause, including columns that do notappear in the \fBSELECT\fR result list. Thus thefollowing statement is valid:.sp.nfSELECT name FROM distributors ORDER BY code;.sp.fiA limitation of this feature is that an ORDER BYclause applying to the result of a UNION,INTERSECT, or EXCEPT clause may onlyspecify an output column name or number, not an expression..PPIf an ORDER BY expression is a simple name thatmatches 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 willmake in the same situation. This inconsistency is made to becompatible with the SQL standard..PPOptionally one may add the key word ASC (ascending) orDESC (descending) after any expression in theORDER BY clause. If not specified, ASC isassumed by default. Alternatively, a specific ordering operatorname may be specified in the USING clause.ASC is usually equivalent to USING < andDESC is usually equivalent to USING >.(But the creator of a user-defined data type can define exactly what thedefault sort ordering is, and it might correspond to operators with othernames.).PPThe null value sorts higher than any other value. In other words,with ascending sort order, null values sort at the end, and withdescending sort order, null values sort at the beginning..PPCharacter-string data is sorted according to the locale-specificcollation order that was established when the database clusterwas initialized..SS "DISTINCT CLAUSE".PPIf DISTINCT is specified, all duplicate rows areremoved from the result set (one row is kept from each group ofduplicates). ALL specifies the opposite: all rows arekept; that is the default..PPDISTINCT ON ( \fIexpression\fR [, ...] )keeps only the first row of each set of rows where the givenexpressions evaluate to equal. The DISTINCT ONexpressions are interpreted using the same rules as forORDER BY (see above). Note that the ``firstrow'' of each set is unpredictable unless ORDERBY is used to ensure that the desired row appears first. Forexample,.sp.nfSELECT DISTINCT ON (location) location, time, report FROM weather_reports ORDER BY location, time DESC;.sp.firetrieves the most recent weather report for each location. Butif we had not used ORDER BY to force descending orderof time values for each location, we'd have gotten a report froman unpredictable time for each location..PPThe DISTINCT ON expression(s) must match the leftmostORDER BY expression(s). The ORDER BY clausewill normally contain additional expression(s) that determine thedesired precedence of rows within each DISTINCT ON group..SS "LIMIT CLAUSE".PPThe LIMIT clause consists of two independentsub-clauses:.sp.nfLIMIT { \fIcount\fR | ALL }OFFSET \fIstart\fR.sp.fi\fIcount\fR specifies themaximum number of rows to return, while \fIstart\fR specifies the number of rowsto skip before starting to return rows. When both are specified,\fIstart\fR rows are skippedbefore starting to count the \fIcount\fR rows to be returned..PPWhen using LIMIT, it is a good idea to use anORDER BY clause that constrains the result rows into aunique order. Otherwise you will get an unpredictable subset ofthe query's rows \(em you may be asking for the tenth throughtwentieth rows, but tenth through twentieth in what ordering? Youdon't know what ordering unless you specify ORDER BY..PPThe query planner takes LIMIT into account whengenerating a query plan, so you are very likely to get differentplans (yielding different row orders) depending on what you usefor LIMIT and OFFSET. Thus, usingdifferent LIMIT/OFFSET values to selectdifferent subsets of a query result \fBwill giveinconsistent results\fR unless you enforce a predictableresult ordering with ORDER BY. This is not a bug; itis an inherent consequence of the fact that SQL does not promiseto deliver the results of a query in any particular order unlessORDER BY is used to constrain the order..SS "FOR UPDATE/FOR SHARE CLAUSE".PPThe FOR UPDATE clause has this form:.sp.nfFOR UPDATE [ OF \fItable_name\fR [, ...] ] [ NOWAIT ].sp.fi.PPThe closely related FOR SHARE clause has this form:.sp.nfFOR SHARE [ OF \fItable_name\fR [, ...] ] [ NOWAIT ].sp.fi.PPFOR UPDATE causes the rows retrieved by the\fBSELECT\fR statement to be locked as though forupdate. This prevents them from being modified or deleted byother transactions until the current transaction ends. That is,other transactions that attempt \fBUPDATE\fR,\fBDELETE\fR, or \fBSELECT FOR UPDATE\fRof these rows will be blocked until the current transaction ends.Also, if an \fBUPDATE\fR, \fBDELETE\fR,or \fBSELECT FOR UPDATE\fR from another transactionhas already locked a selected row or rows, \fBSELECT FORUPDATE\fR will wait for the other transaction to complete,and will then lock and return the updated row (or no row, if therow was deleted). For further discussion see in the documentation..PPTo prevent the operation from waiting for other transactions to commit,use the NOWAIT option. \fBSELECT FOR UPDATENOWAIT\fR reports an error, rather than waiting, if a selected rowcannot be locked immediately. Note that NOWAIT applies onlyto the row-level lock(s) \(em the required ROW SHAREtable-level lock is still taken in the ordinary way (seein the documentation). You can use the NOWAIT option ofLOCK [\fBlock\fR(7)]if you need to acquire the table-level lock without waiting..PPFOR SHARE behaves similarly, except that itacquires a shared rather than exclusive lock on each retrievedrow. A shared lock blocks other transactions from performing\fBUPDATE\fR, \fBDELETE\fR, or \fBSELECTFOR UPDATE\fR on these rows, but it does not prevent themfrom performing \fBSELECT FOR SHARE\fR..PPIf specific tables are named in FOR UPDATEor FOR SHARE,then only rows coming from those tables are locked; any othertables used in the \fBSELECT\fR are simply read asusual. A FOR UPDATE or FOR SHAREclause without a table list affects all tables used in the command.If FOR UPDATE or FOR SHARE isapplied to a view or sub-query, it affects all tables used inthe view or sub-query..PPMultiple FOR UPDATE and FOR SHAREclauses can be written if it is necessary to specify different lockingbehavior for different tables. If the same table is mentioned (orimplicitly affected) by both FOR UPDATE andFOR SHARE clauses, then it is processed asFOR UPDATE. Similarly, a table is processedas NOWAIT if that is specified in any of the clausesaffecting it..PPFOR UPDATE and FOR SHARE cannot beused in contexts where returned rows can't be clearly identified withindividual table rows; for example they can't be used with aggregation..sp.RS.B "Caution:"Avoid locking a row and then modifying it within a later savepoint or\fBPL/pgSQL\fR exception block. A subsequentrollback would cause the lock to be lost. For example,.sp.nfBEGIN;SELECT * FROM mytable WHERE key = 1 FOR UPDATE;SAVEPOINT s;UPDATE mytable SET ... WHERE key = 1;ROLLBACK TO s;.sp.fiAfter the \fBROLLBACK\fR, the row is effectively unlocked, ratherthan returned to its pre-savepoint state of being locked but not modified.This hazard occurs if a row locked in the current transaction is updatedor deleted, or if a shared lock is upgraded to exclusive: in all thesecases, the former lock state is forgotten. If the transaction is thenrolled back to a state between the original locking command and thesubsequent change, the row will appear not to be locked at all. This isan implementation deficiency which will be addressed in a future releaseof PostgreSQL..RE.sp.sp.RS.B "Caution:"It is possible for a \fBSELECT\fR command using bothLIMIT and FOR UPDATE/SHAREclauses to return fewer rows than specified by LIMIT.This is because LIMIT is applied first. The commandselects the specified number of rows,but might then block trying to obtain lock on one or more of them.Once the SELECT unblocks, the row might have been deletedor updated so that it does not meet the query WHERE conditionanymore, in which case it will not be returned..RE.sp.SH "EXAMPLES".PPTo join the table films with the tabledistributors:.sp.nfSELECT 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 ....sp.fi.PPTo sum the column len of all films and groupthe results by kind:.sp.nfSELECT 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.sp.fi.PPTo sum the column len of all films, groupthe results by kind and show those group totalsthat are less than 5 hours:.sp.nfSELECT kind, sum(len) AS total FROM films GROUP BY kind HAVING sum(len) < interval '5 hours'; kind | total----------+------- Comedy | 02:58 Romantic | 04:38.sp.fi.PPThe following two examples are identical ways of sorting the individualresults according to the contents of the second column(name):.sp.nfSELECT * 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.sp.fi.PPThe next example shows how to obtain the union of the tablesdistributors andactors, restricting the results to those that beginwith the letter W in each table. Only distinct rows are wanted, so thekey word ALL is omitted..sp.nfdistributors: 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%'UNIONSELECT actors.name FROM actors WHERE actors.name LIKE 'W%'; name---------------- Walt Disney Walter Matthau Warner Bros. Warren Beatty Westward Woody Allen.sp.fi.PPThis example shows how to use a function in the FROMclause, both with and without a column definition list:.sp.nfCREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$ SELECT * FROM distributors WHERE did = $1;$$ LANGUAGE SQL;SELECT * FROM distributors(111); did | name-----+------------- 111 | Walt DisneyCREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$ SELECT * FROM distributors WHERE did = $1;$$ LANGUAGE SQL;SELECT * FROM distributors_2(111) AS (f1 int, f2 text); f1 | f2-----+------------- 111 | Walt Disney.sp.fi.SH "COMPATIBILITY".PPOf course, the \fBSELECT\fR statement is compatiblewith the SQL standard. But there are some extensions and somemissing features..SS "OMITTED FROM CLAUSES".PPPostgreSQL allows one to omit theFROM clause. It has a straightforward use tocompute the results of simple expressions:.sp.nfSELECT 2+2; ?column?---------- 4.sp.fiSome other SQL databases cannot do this exceptby introducing a dummy one-row table from which to do the\fBSELECT\fR..PPNote that if a FROM clause is not specified,the query cannot reference any database tables. For example, thefollowing query is invalid:.sp.nfSELECT distributors.* WHERE distributors.name = 'Westward';.sp.fiPostgreSQL releases prior to8.1 would accept queries of this form, and add an implicit entryto the query's FROM clause for each tablereferenced by the query. This is no longer the default behavior,because it does not comply with the SQL standard, and isconsidered by many to be error-prone. For compatibility withapplications that rely on this behavior the add_missing_from configuration variable can beenabled..SS "THE AS KEY WORD".PPIn the SQL standard, the optional key word AS is justnoise and can be omitted without affecting the meaning. ThePostgreSQL parser requires this keyword when renaming output columns because the type extensibilityfeatures lead to parsing ambiguities without it.AS is optional in FROMitems, however..SS "NAMESPACE AVAILABLE TO GROUP BY AND ORDER BY".PPIn the SQL-92 standard, an ORDER BY clause mayonly use result column names or numbers, while a GROUPBY clause may only use expressions based on input columnnames. PostgreSQL extends each ofthese clauses to allow the other choice as well (but it uses thestandard's interpretation if there is ambiguity).PostgreSQL also allows both clauses tospecify arbitrary expressions. Note that names appearing in anexpression will always be taken as input-column names, not asresult-column names..PPSQL:1999 and later use a slightly different definition which is notentirely upward compatible with SQL-92. In most cases, however, PostgreSQLwill interpret an ORDER BY or GROUPBY expression the same way SQL:1999 does..SS "NONSTANDARD CLAUSES".PPThe clauses DISTINCT ON,LIMIT, and OFFSET are notdefined in the SQL standard.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?