# SELECT

SELECT reads rows from tables or other sources and evaluates expressions. It supports joins, subqueries, common table expressions, aggregate functions, window functions and set operations.

A SELECT without `FROM` evaluates expressions once. Without `ORDER BY`, result row order is unspecified.

## Syntax

```text
[WITH ...]
SELECT [ALL | DISTINCT] expression [AS alias] [, ...]
[FROM source]
[WHERE condition]
[GROUP BY expression, ...]
[HAVING condition]
[WINDOW name AS (...), ...]
[ORDER BY expression [ASC | DESC], ...]
[LIMIT count [OFFSET offset]]
[SETTINGS ...]
[FORMAT name]
```

## Query clauses

`FROM` chooses the input, `WHERE` filters its rows, `GROUP BY` forms groups and `HAVING` filters aggregate results. `ORDER BY` defines output order and `LIMIT` selects a bounded result. `FORMAT` controls server-side encoding.

Use aliases to name expressions and qualify column names when several sources expose the same name. The format and setting clauses are server extensions; the embedded library returns values without an encoding clause.

## Examples

### Evaluating expressions

```sql
SELECT 2 + 3 AS result, upper('hello') AS greeting
FORMAT csv;
```

```text
5,"HELLO"
```

### Grouped totals

```sql
CREATE TABLE sales (region TEXT, amount INTEGER);
INSERT INTO sales VALUES ('East', 10), ('East', 20), ('West', 5);
```

```sql
SELECT region, count(*) AS orders, sum(amount) AS total
FROM sales
GROUP BY region
HAVING sum(amount) >= 10
ORDER BY total DESC, region
FORMAT csv;
```

```text
"East",2,30
```

Use [window functions](https://coordinatordb.com/docs/reference/functions/window-functions) when a calculation must retain individual rows rather than collapse each group.

## Clause reference

* [ALL](https://coordinatordb.com/docs/reference/statements/select/all)
* [DISTINCT](https://coordinatordb.com/docs/reference/statements/select/distinct)
* [EXCEPT](https://coordinatordb.com/docs/reference/statements/select/except)
* [FORMAT](https://coordinatordb.com/docs/reference/statements/select/format)
* [FROM](https://coordinatordb.com/docs/reference/statements/select/from)
* [GROUP BY](https://coordinatordb.com/docs/reference/statements/select/group-by)
* [HAVING](https://coordinatordb.com/docs/reference/statements/select/having)
* [INTERSECT](https://coordinatordb.com/docs/reference/statements/select/intersect)
* [JOIN](https://coordinatordb.com/docs/reference/statements/select/join)
* [LIMIT](https://coordinatordb.com/docs/reference/statements/select/limit)
* [OFFSET](https://coordinatordb.com/docs/reference/statements/select/offset)
* [ORDER BY](https://coordinatordb.com/docs/reference/statements/select/order-by)
* [UNION](https://coordinatordb.com/docs/reference/statements/select/union)
* [WHERE](https://coordinatordb.com/docs/reference/statements/select/where)
* [WITH](https://coordinatordb.com/docs/reference/statements/select/with)
