# Write queries

This self-contained example uses a common table expression to provide a small order dataset. It does not require a persistent sample table.

## Filter rows

`WHERE` keeps only input rows satisfying the condition:

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

```sql
SELECT region, amount
FROM sales
WHERE amount >= 10
ORDER BY amount
FORMAT csv;
```

```text
"East",10
"East",20
```

## Group and aggregate

`GROUP BY` forms one group per region. `count` counts its rows and `sum` calculates its amount:

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

```text
"East",2,30
"West",1,5
```

## Filter grouped results

`HAVING` filters an aggregate result after grouping:

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

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

Use `ORDER BY` whenever row order matters. See the [`SELECT` reference](https://coordinatordb.com/docs/reference/statements/select) for joins, windows, set operations and limits.
