SQL
SELECT Statement
The `SELECT` statement retrieves rows from the database.  
#### Examples {#docs:sql:statements:select::examples}  
Select all columns from the table `tbl`:  
```sql
SELECT * FROM tbl;
```  
Select the rows from `tbl`:  
```sql
SELECT j FROM tbl WHERE i = 3;
```  
Perform an aggregate grouped by the column `i`:  
```sql
SELECT i, sum(j) FROM tbl GROUP BY i;
```  
Select only the top 3 rows from the `tbl`:  
```sql
SELECT * FROM tbl ORDER BY i DESC LIMIT 3;
```  
Join two tables together using the `USING` clause:  
```sql
SELECT * FROM t1 JOIN t2 USING (a, b);
```  
Use column indexes to select the first and third column from the table `tbl`:  
```sql
SELECT #1, #3 FROM tbl;
```  
Select all unique cities from the addresses table:  
```sql
SELECT DISTINCT city FROM addresses;
```  
Return a `STRUCT` by using a row variable:  
```sql
SELECT d
FROM (SELECT 1 AS a, 2 AS b) d;
```  
#### Syntax {#docs:sql:statements:select::syntax}  
The `SELECT` statement retrieves rows from the database. The canonical order of a `SELECT` statement is as follows, with less common clauses being indented:  
```sql
SELECT ⟨select_list⟩
FROM ⟨tables⟩
USING SAMPLE ⟨sample_expression⟩
WHERE ⟨condition⟩
GROUP BY ⟨groups⟩
HAVING ⟨group_filter⟩
WINDOW ⟨window_expression⟩
QUALIFY ⟨qualify_filter⟩
ORDER BY ⟨order_expression⟩
LIMIT ⟨n⟩;
```  
Optionally, the `SELECT` statement can be prefixed with a [`WITH` clause](#docs:sql:query_syntax:with).  
As the `SELECT` statement is so complex, we have split up the syntax diagrams into several parts. The full syntax diagram can be found at the bottom of the page.