SELECT

Transcripción

SELECT
WikiPrint - from Polar Technologies
Tutorial PostgreSQL...
Referencia: Comandos SQL:
•
ALTER TABLE: cambiar la definición de una tabla
•
ANALYZE: colecta estadísticas sobre una bb.dd.
•
CREATE INDEX: define un nuevo índice
•
CREATE TABLE: define una nueva tabla
•
DELETE: elimina filas de una tabla
•
DROP TABLE: elimina una tabla
•
EXPLAIN: muestra el plan de ejecución
•
INSERT: crea nuevas filas en una tabla
•
SELECT: obtiene filas de una tabla o vista
•
TRUNCATE: vacía una tabla o un conjunto de ellas
•
UPDATE: modifica filas de una tabla
•
VACUUM: limpia y opcionalmente analiza una bb.dd.
Tipos de datos...
Funciones y Operadores...
SELECT
Nombre
SELECT, TABLE, WITH -- recuperar filas desde una tabla o vista
Sinopsis
[ WITH [ RECURSIVE ] consulta_with [, ...] ]
SELECT [ ALL | DISTINCT [ ON ( expresión [, ...] ) ] ]
* | expresión [ [ AS ] nombre_salida ] [, ...]
[ FROM item_from [, ...] ]
[ WHERE condición ]
[ GROUP BY expresión [, ...] ]
[ HAVING condición [, ...] ]
[ WINDOW nombre_ventana AS ( definicion_ventana ) [,
[ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
[ ORDER BY expresión [ ASC | DESC | USING operador ]
[ LIMIT { cantidad | ALL } ]
[ OFFSET inicio [ ROW | ROWS ] ]
[ FETCH { FIRST | NEXT } [ cantidad ] { ROW | ROWS }
[ FOR { UPDATE | SHARE } [ OF nombre_tabla [, ...] ]
...] ]
[ NULLS { FIRST | LAST } ] [, ...] ]
ONLY ]
[ NOWAIT ] [...] ]
donde item_from puede ser uno de:
[ ONLY ] nombre_tabla [ * ] [ [ AS ] alias [ ( alias_columna [, ...] ) ] ]
( select ) [ AS ] alias [ ( alias_columna [, ...] ) ]
nombre_consulta_with [ [ AS ] alias [ ( alias_columna [, ...] ) ] ]
nombre_función ( [ argumento [, ...] ] ) [ AS ] alias [ ( alias_columna [, ...] | definición_columna [, ...] ) ]
nombre_función ( [ argumento [, ...] ] ) AS ( definición_columna [, ...] )
item_from [ NATURAL ] tipo_join item_from [ ON condición_join | USING ( columna_join [, ...] ) ]
y consulta_with es:
1
WikiPrint - from Polar Technologies
nombre_consulta_with [ ( nombre_columna [, ...] ) ] AS ( select )
TABLE { [ ONLY ] nombre_tabla [ * ] | nombre_consulta_with }
Descripción
SELECT recupera filas de cero o más tablas. El procesamiento general de SELECT es el siguiente:
1. Todas las consultas en la lista WITH son computadas. Estas sirven efectivamente como tablas temporales que pueden ser referenciadas en la lista
FROM. Una consulta WITH que es referenciada más de una vez en el FROM es computada solamente una vez. (Ver Clausula WITH abajo.)
1. Todos los elementos de la lista FROM son computados. (Cada elemento en la lista FROM es una tabla real o virtual.) Si más de un elemento es
especificado en la lista FROM, son unidos cruzadamente (producto cartesiano) entre sí. (Ver Clausula FROM abajo.)
1. Si una clausula WHERE es especificada, todas las filas que no satisfagan la condición son eliminadas de la salida. (Ver Clausula WHERE abajo.)
1. Si la clausula GROUP BY es especificada, la salida es dividida en grupos de filas que coinciden en uno o más valores. Si la clausula HAVING está
presente, elimina los grupos que no satisfacen la condición dada. (Ver Clausula GROUP BY y Clausula HAVING abajo.)
1. La salida real es computada usando las expresiones de salida del SELECT para cada fila seleccionada. (Ver Lista SELECT abajo.)
1. Usando los operadores UNION, INTERSECT, y EXCEPT, la salida de más de una instrucción SELECT puede ser combinada para formar un conjunto
de resultados único. El operador UNION devuelve todas las filas que estan en una o en ambos conjuntos de resultados. El operador INTERSECT
devuelve todas las filas que estan estrictamente en ambos conjuntos de resultados. El operador EXCEPT devuelve las filas que estan en el primer
conjunto de resultados y no en el segundo. En los tres casos, las filas duplicadas son eliminadas salvo que se especifique ALL. (Ver Clausula
UNION, Clausula INTERSECT, y Clausula EXCEPT abajo.)
1. Si la clausula ORDER BY es especificada, las filas devueltas son ordenadas en el órden especificado. Si ORDER BY no es dado, las filas son
devueltas en cualquier orden que el sistema encuentre más rápido de producir. (Ver Clausula ORDER BY abajo.)
1. DISTINCT elimina filas repetidas del resultado. DISTINCT ON elimina filas que coinciden con todas las expresiones especificadas. ALL (por
defecto) devolverá todas las filas candidatas, incuyendo duplicados. (Ver Clausula DISTINCT abajo.)
1. Si es especificada la clausula LIMIT (o FETCH FIRST) o OFFSET , la instrucción SELECT solo devuelve un subconjunto de las filas resultantes.
(Ver Clausula LIMIT abajo.)
1. Si se especifica FOR UPDATE o FOR SHARE, la instrucción SELECT bloquea las filas seleccionadas contra actualizaciones concurrentes. (Ver
Clausula FOR UPDATE/FOR SHARE Clause abajo.)
Debe tener privilegios SELECT en cada columna usada en una órden SELECT. A su vez, el uso de FOR UPDATE o FOR SHARE requiere privilegios
UPDATE (al menos por cada columna de cada tabla a ser seleccionada).
Parámetros
Clausula WITH
La clausula WITH permite especificar uno o más subconsultas que serán referenciadas por su nombre en la consulta principal. Las consultas
efectivamente actúan como unas tablas o vistas temporales por la duración de la consulta primaria.
Un nombre (sin calificador de esquema) debe ser especificado a cada consulta WITH. Opcionalmente, una lista de nombres puede ser especificada: si
es omitida, el nombre de las columnas serán inferidos de la subconsulta.
Si se especifica RECURSIVE, permite a una subconsulta referenciar a sí misma. Dicha subconsulta debe tener la forma
término_no_recursivo UNION [ ALL ] término_recursivo
donde la referencia recursiva a si misma debe aparecer en el lado derecho de la UNION. Solo se permite una referencia a si misma por consulta.
Otro efecto de RECURSIVE es que las consultas WITH no necesitan ser ordenadas: una consulta puede referenciar otra que esté luego en esta lista.
(Aunque no estan implementadas las referencias circulares o recursión mutua) Sin RECURSIVE, las consultas WITH solo pueden referenciar consultas
WITH hermanas que son anteriores en la lista WITH.
Una propiedad útil de las consultas WITH es que son evaluadas solo una vez por cada ejecución de la consulta principal, aún si la consulta primaria se
refiere a ellas más de una vez.
Ver Section 7.8 para información adicional.
Clausula FROM
2
WikiPrint - from Polar Technologies
La clausula FROM especifica una o más tablas de origen para el SELECT. Si multiples orígenes son especificados, el resultado es el producto
Cartesiano (junta cruzada) de todos los orígenes. Pero usualmente son agregadas condiciones de calificación para restringir las filas devueltas a un
pequeño subconjunto del producto Cartesiano.
La clausula FROM puede contener los siguientes elementos:
nombre_tabla
El nombre (opcionalmente calificado por el esquema) de una tabla existente o vista. Si se especifica ONLY, solo una tabla es recorrida. Si no se
especifica ONLY, la tabla y cualquiera de sus descendientes es recorrida.
alias
Un sustituto para el nombre del item FROM conteniendo el alias. Un alias es usado por brevedad o para eliminar ambiguedades entre juntas a si
mismas (donde la misma tabla es recorrida múltiples veces). Cuando se provee un alias, oculta completamente el nombre real de la tabla o función;
por ejemplo dado FROM foo AS f, el resto del SELECT debe referise a este ítem FROM como f y no foo. Si un alias es escrito, un alias de
columna puede ser también escrito para proveer nombres sustitutos para una o más columnas de la tabla.
select
Un sub-SELECT puede aparecer en la clausula FROM. Este actua como si su salida fuera creada como una tabla temporal por la duración de una
órden SELECT simple. Notar que los sub-SELECT deben ser rodeados con paréntesis, y un alias debe ser provisto para el. Una órden VALUES
puede ser usada también aquí.
nombre_consulta_with
Una consulta WITH es referenciada escribiendo su nombre, simplemente como si el nombre de la consulta fuera un nombre de tabla. (De hecho, la
consulta WITH oculta cualquier tabla real del mismo nombre a la consulta primaria. Si es necesario, puede referirse a la tabla real del mismo
nombre al calificar con el esquema el nombre de la tabla.) Un alias puede ser provisto de la misma manera que para una tabla.
nombre_función
En la clausula FROM pueden aparecer llamadas a función. (Esto es especialmente útil para funciones que devuelven conjuntos de resultados, pero
cualquier función puede ser usada.) Actua como si su salida fuera creada a modo de tabla temporal por la duración de la órden SELECT original.
También se puede usar un alias. Si se escribe un alias, una lista de alias de columna puede ser también escrita para proveer nombres sustitutos de
uno o más atributos del tipo de retorno compuesto de la función. Si la función ha sido definida que devuelve el tipo de datos record, un alias o
palabra clave AS debe estar presente, seguido por una lista de definición de columnas en la forma ( nombre_column tipo_dato [, ... ]
). La lista de definición de columna debe coincidir con la cantidad y tipo de datos devueltos por la función.
tipo_junta
Uno de:
•
[ INNER ] JOIN
•
LEFT [ OUTER ] JOIN
•
RIGHT [ OUTER ] JOIN
•
FULL [ OUTER ] JOIN
•
CROSS JOIN
Para los tipos de junta INNER y OUTER, una condicion debe ser especificada, a saber exactamente una de NATURAL, ON condición_junta, o
USING (columna_junta [, ...]). Ver abajo por su significado.Para CROSS JOIN, ningúna de estas clausulas pueden aparecer.
Una clausula JOIN combina dos items FROM. Usar paréntesis si es necesario determinar el orden de anidamiento. En ausencia de paréntesis, los
JOINs se anidan de izquierda a derecha. En cualquier caso JOIN se enlaza más estrechamente que separando por comas los items FROM.
CROSS JOIN e INNER JOIN producen un producto Cartesiano simple, el mismo resultado que obtendría de listar los dos items en primer nivel del
FROM, pero restringidos por la condición de junta (si existe). CROSS JOIN es equivalente a INNER JOIN ON (TRUE), dicho de otro modo, ninguna fila
es removida por calificación. Estos tipos de junta son solo una conveniencia de notación, ya que no hacen más de lo que se podría hacer con FROM y
WHERE simples.
LEFT OUTER JOIN devuelve todas las filas en el producto Cartesiano calificadas (todas las filas combinadas que cumplieron la condición de junta),
más una copia de cada fila en la tabla izquierda para la cual ninguna fila derecha cumplió la condición de junta. Esta fila izquierda es extendida al ancho
total de la tabla juntada insertando valores nulos para las columnas derechas. Note que solo la condición propia de la clausula JOIN es conciderada
mientras se decide que filas tienen coincidencias. Las condiciones externas son aplicadas después.
A la inversa, RIGHT OUTER JOIN devuelve todas las filas combinadas, más una por cada fila derecha sin coincidencias (extendida a la izquierda con
nulos). Esto es solo una conveniencia de notación, ya que podría convertirla a LEFT OUTER JOIN cambiando las entrada izquierda por derecha.
FULL OUTER JOIN devuelve todas las filas combinadas, más una fila por cada una sin coincidencia izquierda (extendido con nulos a la derecha), más
una fila por cada una sin coincidencia derecha (extendido con nulos a la izquierda).
ON condición_junta
3
WikiPrint - from Polar Technologies
condición_junta es una expresión resultando en valores del tipo boolean (similar a la clausula WHERE) que especifican que filas en una junta
son concideradas que coinciden.
USING ( columna_junta [, ...] )
Una clausula de la forma USING ( a, b, ... ) es la forma reducida de ON tabla_izquierda.a = tabla_derecha.a AND
tabla_izquierda.b = tabla_derecha.b ....A su vez , USING implica que solo una de cada par de columnas equivalentes será incluida en
la salida de la junta, no ambas.
NATURAL
NATURAL es la forma reducida de una lista USING que mencione todas las columnas en las dos tablas que tienen el mismo nombre.
Clausula WHERE
La clausula opcional WHERE tiene la forma general
WHERE condición
donde condición es cualquier expresión que evalua a un resultado de tipo boolean. Cualquier fila que no satisface esta condición será eliminada de
la salida. Una fila satisface la condición si esta devuelve verdadero cuando los valores de la fila actual son sustituidos por las referencias a variables.
Clausula GROUP BY
La clausula opcional GROUP BY tiene la siguiente forma general
GROUP BY expresión [, ...]
GROUP BY condensará en una única fila todas las filas seleccionadas que compartan los mismos valores para las expresiones de agrupamiento.
expresión puede ser un nombre de columna de entrada, o el nombre o el número ordinal de una columna de salida (items lista SELECT), o una
expresión arbitraria formada por valores de las columnas de entrada. En caso de ambiguedad, el nombre en GROUP BY será interpretado como el
nombre de una columna de entrada antes que el de una de salida.
Funciones de agregado, si alguna es usada, son computadas sobre todas las filas que conforman cada grupo, produciendo un valor separado para cada
grupo (mientras que sin GROUP BY, un agregado produce un valor individual computado sobre todas las filas seleccionadas). Cuando GROUP BY está
presente, no es válido para la lista de expresiones del SELECT referirse a columnas no agrupadas excepto entre las funciones de agregado, ya que
habría más de un posible valor a devolver de una columna sin agrupar.
Clausula HAVING
La clausula HAVING opcional tiene la forma general
HAVING condición
donde condición es idéntico a lo especificado para la clausula WHERE.
HAVING elimina filas agrupadas que no satisfacen la condición. HAVING es diferente a WHERE: WHERE filtra filas individuales antes de la aplicación de
GROUP BY, mientras que HAVING filtra filas agrupadas creadas por GROUP BY. Cada columna referenciada en condición debe referenciar sin
ambiguedad una columna de agrupación, salvo que la referencia aparezca dentro de una función de agregado.
La presencia de HAVING torna a la consulta en una consulta agrupada aún si no hay clausula GROUP BY. Esto es lo mismo que sucede cuando una
consulta contiene funciones de agregado sin clausula GROUP BY. Todas las filas seleccionadas son consideradas que forman un grupo individual, y la
lista SELECT y clausula HAVING solamente puede referenciar columnas de tabla desde funciones agregadas. Dicha consulta emitirá solo una fila si la
condición HAVING es verdadera, cero filas si es falsa.
Clausula WINDOW
La clausula opcional WINDOW tiene la siguiente forma
WINDOW nombre_ventana AS ( definición_ventana ) [, ...]
donde nombre_ventana es el nombre que puede ser referenciado desde definiciones subsecuentes de ventanas o clausulas OVER, y
definición_ventana es
4
WikiPrint - from Polar Technologies
[
[
[
[
nombre_ventana_existente ]
PARTITION BY expresión [, ...] ]
ORDER BY expresión [ ASC | DESC | USING operador ] [ NULLS { FIRST | LAST } ] [, ...] ]
clausula_marco ]
Si se especifica nombre_ventana_existente debe referirse a una entrada anterior en la lista WINDOW; la nueva ventana copia su clausula de
particionamiento de aquella entrada, y lo mismo para su clausula de ordenamiento si existe. En este caso la nueva ventana no puede especificar su
propia clausula PARTITION BY, y puede especificar ORDER BY solo si la ventana copiada no tiene una. La nueva ventana siempre usa so propia
clausula marco; la ventana copiada no debe especificar una clausula marco.
Los elementos de la lista PARTITION BY son interpretados en una manera muy similar a los elementos en una Clausula GROUP BY, exceptuando
que son siempre expresiones simples y nunca el nombre o numero de una columna de salida. Otra diferencia es que estas expresiones pueden
contener llamadas a funciones de agregado, que no son permitidas en una clausula GROUP BY normal . Son permitidas aquí porque las ventanas
ocurren después de la agrupación y agregación.
Similarmente, los elementos de una lista ORDER BY son interpretados en una manera muy similar a los elementos en una Clausula O RDER BY,
exceptuando que la expresión siempre son tomadas como expresiones simples y nunca el nombre o número de una columna de salida.
La clausula_marco opcional define el marco de ventana para funciones de ventana que dependan de este marco (no todas lo hacen). Puede ser una
de
RANGE UNBOUNDED PRECEDING
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
ROWS UNBOUNDED PRECEDING
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
Las primeras dos son equivalente y también son las predeterminadas: establecen que el marco serán todas las filas de la partición empezando a través
del último par de la fila actual en el ordenamiento ORDER BY (lo que significa que serán todas las filas si no hay ORDER BY). Las opciones RANGE
BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING y ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING son
equivalentes: siempre seleccionan todas las filas de la partición. Par último, ROWS UNBOUNDED PRECEDING o su equivalente ROWS BETWEEN
UNBOUNDED PRECEDING AND CURRENT ROW seleccionan todas las filas hasta la fila actual (sin importar los duplicados). Tener cuidado ya que esta
opción puede producir resultados dependientes de la implementación si el orden ORDER BY no ordena las filas de manera única.
El propósito de la clausula WINDOW es especificar el comportamiento de las funciones de ventana apareciendo en la lista SELECT o Clausula ORDER
BY de la consulta. Estas funciones pueden referenciar entradas de la clausula WINDOW por su nombre en sus clausulas OVER. Una entrada de clausula
WINDOW no necesita ser referenciada en otro lugar, aunque; si no es usada en la consulta simplemente es ignorada. Es posible usar funciones de
ventana sin siquiera una clausula WINDOW, ya que una llamada a función de ventana puede especificar su definición de ventana directamente en su
clausula OVER. Sin embargo, la clausula WINDOW ahorra tipear cuando la misma definición de ventana es necesaria para más de una función de
ventana.
Funciones de ventana son descritas en detalle en Section 3.5, Section 4.2.8, y Section 7.2.4.
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.
Just as in a table, every output column of a SELECT has a name. In a simple SELECT this name is just used to label the column for display, but when
the SELECT is a sub-query of a larger query, the name is seen by the larger query as the column name of the virtual table produced by the sub-query.
To specify the name to use for an output column, write AS output_name after the column's expression. (You can omit AS, but only if the desired output
name does not match any PostgreSQL keyword (see Appendix C). For protection against possible future keyword additions, it is recommended that you
always either write AS or double-quote the output name.) If you do not specify a column name, a name is chosen automatically by PostgreSQL. If the
column's expression is a simple column reference then the chosen name is the same as that column's name; in more complex cases a generated name
looking like ?columnN? is usually chosen.
An output column's name can 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, you can write table_name.*
as a shorthand for the columns coming from just that table. In these cases it is not possible to specify new names with AS; the output column names will
5
WikiPrint - from Polar Technologies
be the same as the table columns' names.
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, FOR UPDATE, or FOR SHARE 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. (Therefore, UNION
ALL is usually significantly quicker than UNION; use ALL when you can.)
Multiple UNION operators in the same SELECT statement are evaluated left to right, unless otherwise indicated by parentheses.
Currently, FOR UPDATE and FOR SHARE cannot be specified either for a UNION result or for any input of a 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, FOR UPDATE, or FOR SHARE 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).
Currently, FOR UPDATE and FOR SHARE cannot be specified either for an INTERSECT result or for any input of an INTERSECT.
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, FOR UPDATE, or FOR SHARE 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.
Currently, FOR UPDATE and FOR SHARE cannot be specified either for an EXCEPT result or for any input of an EXCEPT.
ORDER BY Clause
The optional ORDER BY clause has this general form:
6
WikiPrint - from Polar Technologies
ORDER BY ''`expression`'' [ ASC | DESC | USING ''`operator`'' ] [ NULLS { FIRST | LAST } ] [, ...]
The ORDER BY clause causes the result rows to be sorted according to the specified expression(s). If two rows are equal according to the leftmost
expression, they are compared according to the next expression and so on. If they are equal according to all specified expressions, they are returned in
an implementation-dependent order.
Each expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from
input-column values.
The ordinal number refers to the ordinal (left-to-right) position of the output 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 an output 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 output 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 can only specify an output
column name or number, not an expression.
If an ORDER BY expression is a simple name that matches both an output column name and an input column name, ORDER BY will interpret it as the
output 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 can add the key word ASC (ascending) or DESC (descending) after any expression in the ORDER BY clause. If not specified, ASC is
assumed by default. Alternatively, a specific ordering operator name can be specified in the USING clause. An ordering operator must be a less-than or
greater-than member of some B-tree operator family. 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.)
If NULLS LAST is specified, null values sort after all non-null values; if NULLS FIRST is specified, null values sort before all non-null values. If neither is
specified, the default behavior is NULLS LAST when ASC is specified or implied, and NULLS FIRST when DESC is specified (thus, the default is to act
as though nulls are larger than non-nulls). When USING is specified, the default nulls ordering depends on whether the operator is a less-than or
greater-than operator.
Note that ordering options apply only to the expression they follow; for example ORDER BY x, y DESC does not mean the same thing as ORDER BY
x DESC, y DESC.
Character-string data is sorted according to the locale-specific collation order that was established when the database was created.
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.
The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause will normally contain additional
expression(s) that determine the desired precedence of rows within each DISTINCT ON group.
LIMIT Clause
The LIMIT clause consists of two independent sub-clauses:
7
WikiPrint - from Polar Technologies
LIMIT { ''`count`'' | ALL }
OFFSET ''`start`''
count specifies the maximum number of rows to return, while start specifies the number of rows to skip before starting to return rows. When both are
specified, start rows are skipped before starting to count the count rows to be returned.
If the count expression evaluates to NULL, it is treated as LIMIT ALL, i.e., no limit. If start evaluates to NULL, it is treated the same as OFFSET 0.
SQL:2008 introduced a different syntax to achieve the same thing, which PostgreSQL also supports. It is:
OFFSET ''`start`'' { ROW | ROWS }
FETCH { FIRST | NEXT } [ ''`count`'' ] { ROW | ROWS } ONLY
Both clauses are optional, but if present the OFFSET clause must come before the FETCH clause. ROW and ROWS as well as FIRST and NEXT are
noise words that don't influence the effects of these clauses. In this syntax, when using expressions other than simple constants for start or count,
parentheses will be necessary in most cases. If count is omitted in FETCH, it defaults to 1.
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 might 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.
It is even possible for repeated executions of the same LIMIT query to return different subsets of the rows of a table, if there is not an ORDER BY to
enforce selection of a deterministic subset. Again, this is not a bug; determinism of the results is simply not guaranteed in such a case.
FOR UPDATE/FOR SHARE Clause
The FOR UPDATE clause has this form:
FOR UPDATE [ OF ''`table_name`'' [, ...] ] [ NOWAIT ]
The closely related FOR SHARE clause has this form:
FOR SHARE [ OF ''`table_name`'' [, ...] ] [ NOWAIT ]
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 Chapter 13.
To prevent the operation from waiting for other transactions to commit, use the NOWAIT option. SELECT FOR UPDATE NOWAIT reports an error, rather
than waiting, if a selected row cannot be locked immediately. Note that NOWAIT applies only to the row-level lock(s) - the required ROW SHARE
table-level lock is still taken in the ordinary way (see Chapter 13). You can use the NOWAIT option of LOCK if you need to acquire the table-level lock
without waiting.
FOR SHARE behaves similarly, except that it acquires a shared rather than exclusive lock on each retrieved row. A shared lock blocks other transactions
from performing UPDATE, DELETE, or SELECT FOR UPDATE on these rows, but it does not prevent them from performing SELECT FOR SHARE.
If specific tables are named in FOR UPDATE or FOR SHARE, then only rows coming from those tables are locked; any other tables used in the SELECT
are simply read as usual. A FOR UPDATE or FOR SHARE clause without a table list affects all tables used in the command. If FOR UPDATE or FOR
SHARE is applied to a view or sub-query, it affects all tables used in the view or sub-query.
Multiple FOR UPDATE and FOR SHARE clauses can be written if it is necessary to specify different locking behavior for different tables. If the same table
is mentioned (or implicitly affected) by both FOR UPDATE and FOR SHARE clauses, then it is processed as FOR UPDATE. Similarly, a table is processed
as NOWAIT if that is specified in any of the clauses affecting it.
8
WikiPrint - from Polar Technologies
FOR UPDATE and FOR SHARE cannot be used in contexts where returned rows cannot be clearly identified with individual table rows; for example they
cannot be used with aggregation.
Caution
Avoid locking a row and then modifying it within a later savepoint or PL/pgSQL exception block. A subsequent rollback would cause the lock to be lost.
For example:
[[BR]]BEGIN;[[BR]]SELECT * FROM mytable WHERE key = 1 FOR UPDATE;[[BR]]SAVEPOINT s;[[BR]]UPDATE mytable SET ...
WHERE key = 1;[[BR]]ROLLBACK TO s;[[BR]]
After the ROLLBACK, the row is effectively unlocked, rather than returned to its pre-savepoint state of being locked but not modified. This hazard occurs
if a row locked in the current transaction is updated or deleted, or if a shared lock is upgraded to exclusive: in all these cases, the former lock state is
forgotten. If the transaction is then rolled back to a state between the original locking command and the subsequent change, the row will appear not to
be locked at all. This is an implementation deficiency which will be addressed in a future release of PostgreSQL.
Caution
It is possible for a SELECT command using both LIMIT and FOR UPDATE/SHARE clauses to return fewer rows than specified by LIMIT. This is
because LIMIT is applied first. The command selects the specified number of rows, but might then block trying to obtain a lock on one or more of
them. Once the SELECT unblocks, the row might have been deleted or updated so that it does not meet the query WHERE condition anymore, in which
case it will not be returned.
Caution
Similarly, it is possible for a SELECT command using ORDER BY and FOR UPDATE/SHARE to return rows out of order. This is because ORDER BY is
applied first. The command orders the result, but might then block trying to obtain a lock on one or more of the rows. Once the SELECT unblocks, one
of the ordered columns might have been modified and be returned out of order. A workaround is to perform SELECT ... FOR UPDATE/SHARE and
then SELECT ... ORDER BY.
TABLE Command
The command
TABLE ''`name`''
is completely equivalent to
SELECT * FROM ''`name`''
It can be used as a top-level command or as a space-saving syntax variant in parts of complex queries.
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
9
WikiPrint - from Polar Technologies
Comedy
Drama
Musical
Romantic
|
|
|
|
02:58
14:28
06:42
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
The next example shows how to obtain the union of the tables distributors and actors, restricting the results to those that begin with the letter W
in each table. Only distinct rows are wanted, so the key word ALL is omitted.
distributors:
did |
name
-----+-------------108 | Westward
111 | Walt Disney
112 | Warner Bros.
...
actors:
id |
name
----+---------------1 | Woody Allen
2 | Warren Beatty
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
10
WikiPrint - from Polar Technologies
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;
$$ LANGUAGE SQL;
SELECT * FROM distributors(111);
did |
name
-----+------------111 | Walt Disney
CREATE 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
This example shows how to use a simple WITH clause:
WITH t AS (
SELECT random() as x FROM generate_series(1, 3)
)
SELECT * FROM t
UNION ALL
SELECT * FROM t
x
-------------------0.534150459803641
0.520092216785997
0.0735620250925422
0.534150459803641
0.520092216785997
0.0735620250925422
Notice that the WITH query was evaluated only once, so that we got two sets of the same three random values.
This example uses WITH RECURSIVE to find all subordinates (direct or indirect) of the employee Mary, and their level of indirectness, from a table that
shows only direct subordinates:
WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
SELECT 1, employee_name, manager_name
FROM employee
WHERE manager_name = 'Mary'
UNION ALL
SELECT er.distance + 1, e.employee_name, e.manager_name
FROM employee_recursive er, employee e
WHERE er.employee_name = e.manager_name
)
SELECT distance, employee_name FROM employee_recursive;
11
WikiPrint - from Polar Technologies
Notice the typical form of recursive queries: an initial condition, followed by UNION, followed by the recursive part of the query. Be sure that the recursive
part of the query will eventually return no tuples, or else the query will loop indefinitely. (See Section 7.8 for more examples.)
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 otherSQLdatabases cannot do this except by introducing a dummy one-row table from which to do the SELECT.
Note that if a FROM clause is not specified, the query cannot reference any database tables. For example, the following query is invalid:
SELECT distributors.* WHERE distributors.name = 'Westward';
PostgreSQL releases prior to 8.1 would accept queries of this form, and add an implicit entry to the query's FROM clause for each table referenced by the
query. This is no longer the default behavior, because it does not comply with the SQL standard, and is considered by many to be error-prone. For
compatibility with applications that rely on this behavior the add_missing_from configuration variable can be enabled.
Omitting the AS Key Word
In the SQL standard, the optional key word AS can be omitted before an output column name whenever the new column name is a valid column name
(that is, not the same as any reserved keyword). PostgreSQL is slightly more restrictive: AS is required if the new column name matches any keyword at
all, reserved or not. Recommended practice is to use AS or double-quote output column names, to prevent any possible conflict against future keyword
additions.
In FROM items, both the standard and PostgreSQL allow AS to be omitted before an alias that is an unreserved keyword. But this is impractical for
output column names, because of syntactic ambiguities.
ONLY and Parentheses
The SQL standard requires parentheses around the table name after ONLY, as in SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE ....
PostgreSQL supports that as well, but the parentheses are optional. (This point applies equally to all SQL commands supporting the ONLY option.)
Namespace Available to GROUP BY and ORDER BY
In the SQL-92 standard, an ORDER BY clause can only use output column names or numbers, while a GROUP BY clause can 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 output-column names.
SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL-92. In most cases, however, PostgreSQL will
interpret an ORDER BY or GROUP BY expression the same way SQL:1999 does.
WINDOW Clause Restrictions
The SQL standard provides additional options for the window frame_clause. PostgreSQL currently supports only the options listed above.
LIMIT and OFFSET
The clauses LIMIT and OFFSET are PostgreSQL-specific syntax, also used by MySQL. The SQL:2008 standard has introduced the clauses OFFSET
... FETCH {FIRST|NEXT} ... for the same functionality, as shown above in LIMIT Clause, and this syntax is also used by IBM DB2. (Applications
written for Oracle frequently use a workaround involving the automatically generated rownum column, not available in PostgreSQL, to implement the
effects of these clauses.)
12
WikiPrint - from Polar Technologies
Nonstandard Clauses
The clause DISTINCT ON is not defined in the SQL standard.
13

Documentos relacionados