SELECT

Updated at:

Use SELECT to query rows from one or more tables.

Syntax

SELECT ( select_clause | '*' )
       FROM table_name
       [ WHERE where_clause ]
       [ ORDER BY ordering_clause ]
       [ LIMIT integer ] | [ LIMIT integer, integer ]

select_clause    ::=  selector [ AS identifier ] ( ',' selector [ AS identifier ] )
selector         ::=  column_name
                      | term
                      | function_name '(' [ selector ( ',' selector )* ] ')'
                      | COUNT '(' '*' ')'
where_clause     ::=  relation ( AND | OR relation )*
relation         ::=  column_name operator term
                      '(' column_name ( ',' column_name )* ')' operator tuple_literal
operator         ::=  '=' | '<' | '>' | '<=' | '>=' | '!=' | IN
group_by_clause  ::=  column_name, (',' column_name)*
ordering_clause  ::=  column_name [ ASC | DESC ] ( ',' column_name [ ASC | DESC ] )*

Syntax conventions:

SymbolMeaning
UPPERCASELiteral keyword
lowercasePlaceholder — replace with an actual value
[ ]Optional element
( )Group of choices
|OR — choose one alternative
*Wildcard — selects all columns

Parameters

ParameterDescription
table_nameThe name of the table to query.
LIMIT integerMaximum number of rows to return.
LIMIT integer, integerThe first integer is the number of rows to skip; the second is the maximum number of rows to return. For example, LIMIT 5, 20 skips five rows and returns up to 20 rows. Equivalent to LIMIT 20 OFFSET 5.

Examples

Basic queries

SELECT * FROM dt;               -- Select all columns
SELECT c1, c2 FROM dt;          -- Select specific columns
SELECT * FROM dt LIMIT 10;      -- Return at most 10 rows
SELECT * FROM dt WHERE c1 = 10;
SELECT c2 FROM dt WHERE c1 > 10;

Pagination with LIMIT

-- Skip 5 rows, return the next 20
SELECT * FROM dt WHERE c1 > 10 LIMIT 5, 20;

-- Equivalent syntax using OFFSET
SELECT * FROM dt WHERE c1 > 10 LIMIT 20 OFFSET 5;

Column aliases

Use AS to assign an alias to a column in the result set.

SELECT c2 AS xx FROM dt WHERE c1 > 10;
SELECT COUNT(*) AS countRow FROM t1;
SELECT c1 AS testC FROM t1 WHERE c1 = '2';

Aggregate functions

COUNT, SUM, AVG, MIN, and MAX operate on all rows matched by the query.

SELECT COUNT(*) FROM dt;
SELECT SUM(c2) FROM dt;
SELECT SUM(c2), AVG(c2), MIN(c2), MAX(c2) FROM dt;

IS NULL

SELECT c1, c2 FROM dt WHERE c1 > 1 OR c2 IS NULL;

IN operator

Match any value in a list:

SELECT * FROM dt WHERE c1 IN ('a', 'b');