Commands
Commons (Data Manipulation)
SELECT
Selects data from a table or multiple tables.
Command is executed in the following logical order:
Data is taken from a table value expressions that are specified in the
FROMclause, joins are executed. IfFROMclause is not specified a single row is constructed.WHEREfilters rows. Aggregate or window functions are not allowed in this clause.GROUP BYgroups the result by the given expression(s). ifGROUP BYclause is not specified, but non-window aggregate function are used orHAVINGis specified all rows are grouped together.Aggregate functions are evaluated.
Having filters rows after grouping and evaluation of aggregate functions. Non-window aggregate functions are allowed in this clause.
Window functions are evaluated.
QUALIFYfilters rows after evaluation of window functions. Aggregate and window functions are allowed in this clause. (Non-standard syntax)DISTINCTremoves duplicates. IfDISTINCTis used only the specified expressions are checked for duplicated;ORDER BYcaluse, if any, is used to datetime preserved rows. First row is eachDISTINCT ONgroup is preserved. In absence ofORDER BYpreserved rows are not datermined, database may choose any row from eachDISTINCT ONgroup.UNION,EXCEPTandINTERSECTcombine the result of this query with the results of another query.INTERSECThas higher precedence thanUNIONandEXCEPT. Operators with equal precedence are evaluated from left to right.ORDER BYsorts the result by the given column(s) or expression(s).Number of rows in output can be limited with
OFFSETandFETCHclauses.OFFSETspecifies how many rows to skip. Please note that queries with high offset values can be slow.FETCH FIRST/NEXTlimits the number of rows returned by the query. IfPERCENTis specified number of rows is specified as a percent of the total number of rows and should be an integer value between 0 and 100 inclusive.WITH TIEScan be used only together withORDER BYand means that all additional rows that have the same sorting position as the last row will be also returned.
Example:
SELECT * FROM TEST;
SELECT * FROM TEST ORDER BY NAME;
SELECT ID, COUNT(*) FROM TEST GROUP BY ID;
SELECT NAME, COUNT(*) FROM TEST GROUP BY NAME HAVING COUNT(*) > 2;
SELECT 'ID' COL, MAX(ID) AS MAX FROM TEST UNION SELECT 'NAME', MAX(NAME) FROM TEST;
SELECT * FROM TEST OFFSET 1000 ROWS FETCH FIRST 1000 ROWS ONLY;
SELECT A, B FROM TEST ORDER BY A FETCH FIRST 10 ROWS WITH TIES;
SELECT * FROM (SELECT ID, COUNT(*) FROM TEST
GROUP BY ID UNION SELECT NULL, COUNT(*) FROM TEST)
ORDER BY 1 NULLS LAST;
SELECT DISTINCT C1, C2 FROM TEST;
SELECT DISTINCT ON(C1) C1, C2 FROM TEST ORDER BY C1;Last updated
Was this helpful?