---
title: "SELECT statement"
description: "Retrieve rows with the CoraDB SELECT statement: WHERE, GROUP BY, ORDER BY, LIMIT, joins, subqueries and graph MATCH patterns."
url: "https://www.coradb.ai/manual/sql/query/select.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/query/select.md"
product: "CoraDB"
version: "1.0"
keywords: "select statement, select from clause, select where clause, group by, having clause, limit clause, join query, subquery, select for update, coradb select"
---

# SELECT statement

The **SELECT** statement retrieves rows from one or more tables, views, derived tables or graph patterns. In CoraDB the same statement queries relational tables and graph data: vertex and edge tables can be read like ordinary tables, or traversed with a [MATCH](https://www.coradb.ai/manual/graph/match.html) pattern in the `FROM` clause.

> **Try it yourself:**
> Every example on this page runs on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html), and the results shown are the real output. Connect with `corasql -u dba e-commerce` and paste any query.


## Syntax

```sql
SELECT [ <qualifier> ] <select_expressions>
    [{TO | INTO} <variable_comma_list>]
    [FROM <extended_table_specification_comma_list>]
    [WHERE <search_condition>]
    [GROUP BY {col_name | expr} [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING <search_condition>]
    [ORDER BY {col_name | expr} [ASC | DESC], ... [NULLS {FIRST | LAST}]]
    [LIMIT [offset,] row_count]
    [USING INDEX { index_name [, index_name, ...] | NONE }]
    [FOR UPDATE [OF <spec_name_comma_list>]]

<qualifier> ::= ALL | DISTINCT | DISTINCTROW | UNIQUE

<select_expressions> ::= * | <expression_comma_list> | *, <expression_comma_list>

<variable_comma_list> ::= [:] identifier, [:] identifier, ...

<extended_table_specification_comma_list> ::=
    <table_specification> [ {, <table_specification> } ...
                          | <join_table_specification> ...
                          | <join_table_specification2> ... ]

<table_specification> ::=
    <single_table_spec> [<correlation>]
  | <metaclass_specification> [<correlation>]
  | <subquery> <correlation>
  | TABLE ( <expression> ) <correlation>
  | MATCH <graph_pattern> [, <graph_pattern> ...]

<correlation> ::= [AS] <identifier> [(<identifier_comma_list>)]

<single_table_spec> ::= [ONLY] <table_name> | ALL <table_name> [ EXCEPT <table_name> ]

<metaclass_specification> ::= CLASS <class_name>

<join_table_specification> ::=
    [INNER | {LEFT | RIGHT} [OUTER]] JOIN <table_specification> ON <search_condition>

<join_table_specification2> ::=
    { CROSS JOIN | NATURAL [ LEFT | RIGHT ] JOIN } <table_specification>
```

- *qualifier*: when omitted, **ALL** is used.
  - **ALL**: returns every row.
  - **DISTINCT**: returns only unique rows. **DISTINCT**, **DISTINCTROW** and **UNIQUE** are synonyms.
- *select_expressions*:
  - `*` returns all columns of the tables in the `FROM` clause; *table_name*`.*` returns all columns of one table.
  - *expression_comma_list*: column names, path expressions (*tbl_name.col_name*), variables, arithmetic and function expressions, including aggregate functions such as **AVG**, **COUNT**, **MAX**, **MIN** and **SUM**. Use `AS` to give an expression an alias; aliases can be used in `GROUP BY`, `HAVING` and `ORDER BY`. Column positions start at 1.
- *variable_comma_list*: stores the selected values in session variables (`TO :var` or `INTO :var`).
- *single_table_spec*: with class inheritance, `ONLY` reads just the named super class, `ALL` reads it and its subclasses, and `EXCEPT` excludes the listed subclasses. See [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html).

### Basic examples

Return each distinct contact title used by customers (the first five, alphabetically):

```sql
SELECT DISTINCT contact_title
FROM customer
ORDER BY contact_title
LIMIT 5;
```

| contact_title |
|---|
| Account Manager |
| Accounts Payable Clerk |
| Buyer |
| CEO |
| Category Manager |

`customer` is a vertex table, yet it is queried here like any relational table.

Give columns an alias and sort by the alias:

```sql
SELECT id AS order_no, order_date AS placed_on
FROM orders
ORDER BY placed_on DESC, order_no
LIMIT 5;
```

| order_no | placed_on |
|---:|---|
| 376 | 2025-12-31 |
| 1127 | 2025-12-31 |
| 1446 | 2025-12-31 |
| 1634 | 2025-12-31 |
| 1888 | 2025-12-31 |

Build a value from several columns:

```sql
SELECT CONCAT(name, ' (', code, ')') AS country
FROM countries
ORDER BY country
LIMIT 5;
```

| country |
|---|
| Argentina (ARG) |
| Australia (AUS) |
| Austria (AUT) |
| Belgium (BEL) |
| Brazil (BRA) |

## FROM clause

The **FROM** clause names the sources the rows are read from: tables, views, vertex and edge tables, subqueries (derived tables) and graph patterns. When no table is needed, `FROM` can be omitted.

```sql
SELECT 1 + 1 AS sum_value;
```

| sum_value |
|---:|
| 2 |

### Derived table

A subquery in the `FROM` clause creates a *derived table*: its result is treated as a table for the rest of the query. A derived table must have a correlation name (alias). Derived tables are also used to access the individual elements of a collection-typed column, each element becoming a row.


### Subquery derived table

```sql
FROM (subquery) [AS] [derived_table_name [(column_name [{, column_name } ... ])]]
```

- The number of *column_name* entries must match the number of columns returned by the *subquery*.
- *derived_table_name* can be omitted.

Average number of lines per order, computed from a derived table that first counts the lines of each order:

```sql
SELECT AVG(lines) AS avg_lines_per_order
FROM (SELECT order_id, COUNT(*)
      FROM order_items
      GROUP BY order_id) AS t(order_id, lines);
```

| avg_lines_per_order |
|---:|
| 3.841580756013746 |

A derived table can also be correlated with the outer query. The following query lists orders whose shipping cost is more than three times the average shipping cost of the same customer:

```sql
SELECT o.id, o.customer_id, o.shipping_cost
FROM orders o
WHERE o.shipping_cost > (SELECT AVG(s) * 3
                         FROM (SELECT shipping_cost
                               FROM orders
                               WHERE customer_id = o.customer_id) AS t(s))
ORDER BY o.shipping_cost DESC, o.id
LIMIT 5;
```

| id | customer_id | shipping_cost |
|---:|---:|---:|
| 1080 | 460 | 58.00 |
| 1675 | 855 | 50.57 |
| 995 | 634 | 50.52 |
| 1643 | 830 | 48.30 |
| 2884 | 877 | 41.90 |


## WHERE clause

The **WHERE** clause keeps only the rows for which *search_condition* is true. A condition that evaluates to **NULL** (unknown) does not select the row.

```sql
WHERE <search_condition>

<search_condition> ::=
    <comparison_predicate>
  | <between_predicate>
  | <exists_predicate>
  | <in_predicate>
  | <null_predicate>
  | <like_predicate>
  | <quantified_predicate>
  | <set_predicate>
  | [NOT] MATCH <graph_pattern>
```

The predicates are described in detail here:

- [Simple comparison expression](https://www.coradb.ai/manual/sql/function/comparison_op.html)
- [BETWEEN](https://www.coradb.ai/manual/sql/function/condition_op.html#between)
- [EXISTS](https://www.coradb.ai/manual/sql/function/condition_op.html#exists)
- [IN](https://www.coradb.ai/manual/sql/function/condition_op.html#in)
- [IS NULL](https://www.coradb.ai/manual/sql/function/condition_op.html#is-null)
- [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like)
- [ANY/SOME/ALL quantifiers](https://www.coradb.ai/manual/sql/function/condition_op.html#any-some-all)
- [MATCH as a predicate](https://www.coradb.ai/manual/graph/match.html#match-as-a-predicate)

Combine conditions with **AND**, **OR** and **NOT**. They are evaluated in this order:

| Priority | Operator | Meaning |
|---:|---|---|
| 1 | `()` | Expressions in parentheses are evaluated first. |
| 2 | **NOT** | Negates the result of the expression. |
| 3 | **AND** | All conditions must be true. |
| 4 | **OR** | At least one condition must be true. |

Orders placed in December 2025 that are either not shipped yet or were shipped for free:

```sql
SELECT id, order_date, shipped_date, shipping_cost
FROM orders
WHERE order_date >= DATE'2025-12-01'
  AND (shipped_date IS NULL OR shipping_cost = 0)
ORDER BY id
LIMIT 5;
```

| id | order_date | shipped_date | shipping_cost |
|---:|---|---|---:|
| 175 | 2025-12-22 | 2025-12-25 | 0.00 |
| 455 | 2025-12-30 | NULL | 12.35 |
| 547 | 2025-12-14 | 2025-12-15 | 0.00 |
| 707 | 2025-12-28 | 2026-01-03 | 0.00 |
| 782 | 2025-12-12 | 2025-12-14 | 0.00 |

## GROUP BY ... HAVING clause

**GROUP BY** groups the rows that have the same values in the listed columns or expressions, so that aggregate functions are computed per group. **HAVING** then filters the groups.

```sql
SELECT ...
GROUP BY {col_name | expr | position} [ASC | DESC], ...
         [WITH ROLLUP] [HAVING <search_condition>]
```

- *col_name* | *expr* | *position*: one or more columns, expressions, aliases or column positions, separated by commas.
- **ASC** | **DESC**: sort order of the groups; **ASC** is the default.
- *search_condition*: the `HAVING` condition can refer to grouping columns, their aliases and aggregate functions.
- **WITH ROLLUP**: adds subtotal rows for each level of grouping and a grand total row. In those rows the rolled-up columns are **NULL**.

> **Note:**
> The SQL standard does not allow a column in the select list that is neither grouped nor aggregated (a *hidden column*). CoraDB accepts such columns by default. Set the **only_full_group_by** parameter to **yes** to enforce the standard behaviour; see [Statement/type-related parameters](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters).


Orders per year:

```sql
SELECT EXTRACT(YEAR FROM order_date) AS yr, COUNT(*) AS orders
FROM orders
GROUP BY yr
ORDER BY yr;
```

| yr | orders |
|---:|---:|
| 2021 | 416 |
| 2022 | 482 |
| 2023 | 551 |
| 2024 | 675 |
| 2025 | 786 |

`WHERE` filters rows *before* grouping, `HAVING` filters groups *after* it. Customers with at least five orders in 2025, and what they paid for shipping:

```sql
SELECT customer_id, COUNT(*) AS orders, SUM(shipping_cost) AS shipping
FROM orders
WHERE order_date >= DATE'2025-01-01'
GROUP BY customer_id
HAVING COUNT(*) >= 5
ORDER BY orders DESC, customer_id
LIMIT 5;
```

| customer_id | orders | shipping |
|---:|---:|---:|
| 812 | 13 | 153.64 |
| 440 | 11 | 183.69 |
| 391 | 10 | 124.04 |
| 75 | 8 | 119.41 |
| 342 | 8 | 154.15 |

**WITH ROLLUP** adds a subtotal per year and a grand total:

```sql
SELECT EXTRACT(YEAR FROM order_date) AS yr, QUARTER(order_date) AS q, COUNT(*) AS orders
FROM orders
WHERE order_date >= DATE'2024-01-01'
GROUP BY yr, q WITH ROLLUP;
```

| yr | q | orders |
|---:|---:|---:|
| 2024 | 1 | 125 |
| 2024 | 2 | 132 |
| 2024 | 3 | 152 |
| 2024 | 4 | 266 |
| NULL | NULL | 675 |
| 2025 | 1 | 147 |
| 2025 | 2 | 172 |
| 2025 | 3 | 186 |
| 2025 | 4 | 281 |
| NULL | NULL | 786 |
| NULL | NULL | 1461 |


## ORDER BY clause

**ORDER BY** sorts the result. Without it, the order of the rows is not guaranteed.

```sql
SELECT ...
ORDER BY {col_name | expr | position} [ASC | DESC], ... [NULLS {FIRST | LAST}]
```

- *col_name* | *expr* | *position*: columns, expressions, aliases or column positions. A column that is not in the select list can also be used.
- **ASC** | **DESC**: ascending (default) or descending order.
- **NULLS FIRST** | **NULLS LAST**: where NULL values go. By default NULLs come first with `ASC` and last with `DESC`.

Most recently shipped orders, with the orders that are not shipped yet (NULL `shipped_date`) on top:

```sql
SELECT id, order_date, shipped_date
FROM orders
ORDER BY shipped_date DESC NULLS FIRST, id
LIMIT 5;
```

| id | order_date | shipped_date |
|---:|---|---|
| 455 | 2025-12-30 | NULL |
| 933 | 2025-12-30 | NULL |
| 1325 | 2025-12-30 | NULL |
| 1421 | 2025-12-27 | NULL |
| 1634 | 2025-12-31 | NULL |

> **GROUP BY uses the column, not the alias:**
> When an alias has the same name as a column, `GROUP BY name` refers to the **column**. In `SELECT a, NVL(b, 2) AS b FROM t1 GROUP BY a, b`, the rows are grouped by the column `b`, not by `NVL(b, 2)`. Use a distinct alias (or repeat the expression) to group by the expression.



## LIMIT clause

**LIMIT** restricts the number of rows returned, optionally after skipping *offset* rows.

```sql
LIMIT {[offset,] row_count | row_count [OFFSET offset]}

<offset> ::= <limit_expression>
<row_count> ::= <limit_expression>
```

- *offset*: number of rows to skip; the first row has offset 0 (default).
- *row_count*: maximum number of rows to return.
- Both can be unsigned integers, host variables (`?`) or simple expressions such as `? * ?`, so `LIMIT` works in [prepared statements](https://www.coradb.ai/manual/sql/query/prepare.html).
- `INST_NUM()` and `ROWNUM` cannot be used in the `WHERE` clause of a query with `LIMIT`, and `LIMIT` cannot be combined with `HAVING GROUPBY_NUM()`.

The 11th to 15th most recent orders (a typical "page 3" with five rows per page):

```sql
SELECT id, order_date
FROM orders
ORDER BY order_date DESC, id
LIMIT 5 OFFSET 10;   -- same as LIMIT 10, 5
```

| id | order_date |
|---:|---|
| 414 | 2025-12-29 |
| 832 | 2025-12-29 |
| 1208 | 2025-12-29 |
| 517 | 2025-12-28 |
| 707 | 2025-12-28 |

With a prepared statement:

```sql
PREPARE recent_orders FROM 'SELECT id, order_date FROM orders ORDER BY order_date DESC, id LIMIT ?, ?';
EXECUTE recent_orders USING 10, 5;
```


## Join query

A join combines rows from two or more tables (or views, derived tables and graph patterns). The *join condition* compares columns of the joined sources; only combinations that satisfy it are returned. A join with `=` is an *equi-join*, a join without a condition is a *cartesian product*, and joining a table to itself is a *self join* (use aliases to tell the two copies apart).

```sql
FROM <table_specification> [{, <table_specification>
    | { <join_table_specification> | <join_table_specification2> }} ...]

<join_table_specification> ::=
    [INNER | {LEFT | RIGHT} [OUTER]] JOIN <table_specification> ON <search_condition>

<join_table_specification2> ::=
    { CROSS JOIN | NATURAL [ LEFT | RIGHT ] JOIN } <table_specification>
```

- **[INNER] JOIN**: returns only rows that satisfy the join condition.
- **{LEFT | RIGHT} [OUTER] JOIN**: also returns the rows of the left (or right) source that have no match, with **NULL** for the other side. CoraDB does not support `FULL OUTER JOIN`.
- **CROSS JOIN**: every combination of rows, without a condition.
- **NATURAL [LEFT | RIGHT] JOIN**: joins on all columns that have the same name in both sources.

### Inner join

`INNER` can be omitted, and the inner join can also be written with a comma and a `WHERE` condition. Orders placed on the last day of 2025, with the customer's company name (the `customer` vertex table is joined like a relational table):

```sql
SELECT o.id, o.order_date, cu.company_name
FROM orders o
INNER JOIN customer cu ON cu.id = o.customer_id
WHERE o.order_date = DATE'2025-12-31'
ORDER BY o.id;
```

| id | order_date | company_name |
|---:|---|---|
| 376 | 2025-12-31 | Reyes, Farmer and West |
| 1127 | 2025-12-31 | Owens, Mathis and Romero |
| 1446 | 2025-12-31 | Harris-Jones |
| 1634 | 2025-12-31 | Anderson-Meyer |
| 1888 | 2025-12-31 | Price, Whitney and Carr |

### Outer join

An outer join keeps the rows of one side even when they have no match. Customers that never ordered appear with an order count of 0:

```sql
SELECT cu.company_name, COUNT(o.id) AS orders
FROM customer cu
LEFT OUTER JOIN orders o ON o.customer_id = cu.id
GROUP BY cu.id, cu.company_name
ORDER BY orders, cu.company_name
LIMIT 5;
```

| company_name | orders |
|---|---:|
| Adams, Pena and Hansen | 0 |
| Adams-Barnes | 0 |
| Adams-Greer | 0 |
| Adams-Obrien | 0 |
| Alexander LLC | 0 |

The tables are joined in the order they appear in the `FROM` clause, so write outer joins with the table order in mind. A `RIGHT OUTER JOIN` can always be rewritten as a `LEFT OUTER JOIN` by swapping the two tables.

**Conditions in `ON` and in `WHERE` mean different things.** In an outer join, a condition in `ON` only decides which rows match; every row of the preserved side is still returned. A condition in `WHERE` is applied *after* the join and removes rows:

```sql
-- condition in ON: all 1000 customers are kept, 2025 orders are attached when they exist
SELECT COUNT(*) AS rows_returned
FROM customer cu
LEFT OUTER JOIN orders o ON o.customer_id = cu.id AND o.order_date >= DATE'2025-01-01';

-- condition in WHERE: only rows with a 2025 order remain
SELECT COUNT(*) AS rows_returned
FROM customer cu
LEFT OUTER JOIN orders o ON o.customer_id = cu.id
WHERE o.order_date >= DATE'2025-01-01';
```

| query | rows_returned |
|---|---:|
| Condition in `ON` | 1394 |
| Condition in `WHERE` | 786 |

CoraDB also accepts the Oracle-style `(+)` notation in the `WHERE` clause. It is not ISO/ANSI SQL and can be ambiguous, so prefer `LEFT | RIGHT OUTER JOIN`. Both queries below count the 350 customers without orders:

```sql
SELECT COUNT(*) AS customers_without_orders
FROM customer cu
LEFT OUTER JOIN orders o ON o.customer_id = cu.id
WHERE o.id IS NULL;

SELECT COUNT(*) AS customers_without_orders
FROM customer cu, orders o
WHERE cu.id = o.customer_id(+) AND o.id IS NULL;
```

| customers_without_orders |
|---:|
| 350 |

Path expressions that include subqueries and sub-columns cannot be used in the join condition of an outer join.

### Cross join

A cross join returns the cartesian product of the two sources. `CROSS JOIN` can be replaced by a comma.

```sql
SELECT COUNT(*) AS combinations
FROM countries CROSS JOIN category;   -- 25 countries x 32 categories
```

| combinations |
|---:|
| 800 |

### Natural join

A natural join uses all columns with the same name as the join condition. Here both derived tables have a `customer_id` column:

```sql
SELECT c.customer_id, c.company_name, o.n AS orders
FROM (SELECT id AS customer_id, company_name FROM customer) c
NATURAL JOIN (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) o
ORDER BY o.n DESC, c.customer_id
LIMIT 3;
```

| customer_id | company_name | orders |
|---:|---|---:|
| 440 | Mayer, Carroll and Owens | 40 |
| 812 | Young and Sons | 40 |
| 444 | Kelly Ltd | 39 |

This is the same as `INNER JOIN ... ON c.customer_id = o.customer_id`. `NATURAL LEFT JOIN` and `NATURAL RIGHT JOIN` are the outer-join equivalents. With `SELECT *`, both `customer_id` columns are returned, so qualify the column in `ORDER BY`.

### Joining graph patterns and tables

A [MATCH](https://www.coradb.ai/manual/graph/match.html) pattern is a table specification too, so graph patterns can be joined with relational tables in the same `FROM` clause. London customers with the most orders:

```sql
SELECT cu.company_name, COUNT(o.id) AS orders
FROM MATCH (cu:customer)-[:resides_in]->(ci:city),
     orders o
WHERE o.customer_id = cu.id
  AND ci.name = 'London'
GROUP BY cu.company_name
ORDER BY orders DESC, cu.company_name
LIMIT 3;
```

| cu.company_name | orders |
|---|---:|
| Hicks-Marshall | 15 |
| Jordan, Smith and Bartlett | 15 |
| Hernandez, Wilson and Johnson | 10 |

`MATCH` patterns also work with `INNER`, `LEFT` and `RIGHT [OUTER] JOIN ... ON`. See [Joining MATCH patterns](https://www.coradb.ai/manual/graph/match.html#joining-match-patterns-and-tables).

## Subquery

A subquery can be used wherever an expression is allowed, for example in the select list or in the `WHERE` clause. Used as a value, it must return a single column. Subqueries are *single-row* or *multiple-row*.

### Single-row subquery

A single-row subquery returns one column of one row. If it returns no row, its value is **NULL**; if it returns more than one row, an error is raised.

```sql
SELECT o.id, o.order_date,
       (SELECT cu.company_name FROM customer cu WHERE cu.id = o.customer_id) AS customer
FROM orders o
ORDER BY o.id
LIMIT 5;
```

| id | order_date | customer |
|---:|---|---|
| 0 | 2021-11-07 | Peterson-Williams |
| 1 | 2025-10-19 | Hicks Group |
| 2 | 2022-09-05 | Doyle, Mcdonald and Lowery |
| 3 | 2023-12-27 | Washington LLC |
| 4 | 2024-09-20 | Davidson, Jefferson and Mack |

### Multiple-row subquery

A multiple-row subquery returns one column of several rows. With the `SET`, `MULTISET` or `LIST` keyword, the rows become a collection value. Use `ORDER BY` inside the subquery to control the order of a `LIST`.

```sql
SELECT c.name,
       LIST(SELECT ci.name FROM city ci WHERE ci.country_code = c.code ORDER BY ci.name) AS cities
FROM countries c
WHERE c.code IN ('AUT', 'BEL')
ORDER BY c.name;
```

| name | cities |
|---|---|
| Austria | {'Graz', 'Salzburg'} |
| Belgium | {'Bruxelles', 'Charleroi'} |

Multiple-row subqueries can be used wherever a collection value is allowed, but not where a collection *constant* is required, such as the `DEFAULT` value of a column.

## MATCH

`MATCH` queries graph patterns over vertex tables and edge tables (created with `CREATE VERTEX TABLE` and `CREATE EDGE TABLE`). It is used in the `FROM` clause, and as a predicate in `WHERE`:

```sql
SELECT ...
FROM MATCH [<path_variable> =] [ANY_SHORTEST | ALL_SHORTEST] <graph_pattern> [, <graph_pattern> ...]
```

Brands with the most followers:

```sql
SELECT b.name, COUNT(cu) AS followers
FROM MATCH (cu:customer)-[:follows]->(b:brand)
GROUP BY b.name
ORDER BY followers DESC, b.name
LIMIT 5;
```

| b.name | followers |
|---|---:|
| Nike | 209 |
| Adidas | 132 |
| Puma | 94 |
| Reebok | 83 |
| Under Armour | 76 |

The full syntax (directions, variable-length paths, shortest paths, path variables, `MATCH` predicates and joins) is described in [MATCH clause: graph queries in SELECT](https://www.coradb.ai/manual/graph/match.html); [Relational and graph in one query](https://www.coradb.ai/manual/sql/hybrid.html) shows more ways to combine patterns with tables.

## VALUES

The **VALUES** clause returns the rows written in the statement. It is a short way to write a `UNION ALL` of constant rows, and it can be used as a derived table. All rows must have the same number of values.

```sql
VALUES (expression[, ...])[, ...]
```

```sql
VALUES (1 AS id, 'standard' AS shipping), (2, 'express'), (3, 'pickup');
```

| id | shipping |
|---:|---|
| 1 | standard |
| 2 | express |
| 3 | pickup |

This is equivalent to:

```sql
SELECT 1 AS id, 'standard' AS shipping
UNION ALL SELECT 2, 'express'
UNION ALL SELECT 3, 'pickup';
```

As a derived table, joined with a real table:

```sql
SELECT t.code, c.name
FROM (VALUES ('FRA'), ('DEU'), ('ITA')) AS t(code)
INNER JOIN countries c ON c.code = t.code
ORDER BY c.name;
```

| code | name |
|---|---|
| FRA | France |
| DEU | Germany |
| ITA | Italy |

`VALUES` with several rows is also used in [INSERT](https://www.coradb.ai/manual/sql/query/insert.html).

## FOR UPDATE

**FOR UPDATE** locks the rows returned by the `SELECT` (with an exclusive `X_LOCK`) so that the transaction can update or delete them later without another transaction changing them first.

```sql
SELECT ... [FOR UPDATE [OF <spec_name_comma_list>]]

<spec_name_comma_list> ::= <spec_name> [, <spec_name>, ... ]
<spec_name> ::= table_name | view_name
```

- *spec_name_comma_list*: the tables or views of the `FROM` clause whose rows are locked. Without `OF`, all tables and views of the `FROM` clause are locked.

> **Restrictions:**
> - `FOR UPDATE` cannot be used inside a subquery (it can reference subqueries).
> - It cannot be used with `GROUP BY`, `DISTINCT` or aggregate functions.
> - It cannot reference a `UNION`.


Lock the orders that still have to be shipped, then mark them as shipped in the same transaction:

```sql
SELECT id, shipped_date
FROM orders
WHERE shipped_date IS NULL
ORDER BY id
FOR UPDATE;

UPDATE orders SET shipped_date = SYSDATE WHERE shipped_date IS NULL;
COMMIT;
```

Other forms:

```sql
SELECT * FROM orders o INNER JOIN order_items oi ON oi.order_id = o.id
WHERE o.shipped_date IS NULL
FOR UPDATE OF o;            -- lock only the orders rows

SELECT * FROM orders o
INNER JOIN (SELECT * FROM order_items WHERE quantity > 5) big ON big.order_id = o.id
WHERE o.shipped_date IS NULL
FOR UPDATE;                 -- a derived table can be referenced
```

## See also

- [MATCH clause: graph queries in SELECT](https://www.coradb.ai/manual/graph/match.html)
- [Common table expressions (WITH)](https://www.coradb.ai/manual/sql/query/cte.html)
- [Hierarchical queries](https://www.coradb.ai/manual/sql/query/hq.html)
- [UNION, DIFFERENCE, INTERSECTION](https://www.coradb.ai/manual/sql/function/stmt_set_op.html)
- [Aggregate & analytic functions](https://www.coradb.ai/manual/sql/function/analysis_fn.html)
- [Query optimization: statistics, plans and hints](https://www.coradb.ai/manual/sql/tuning.html)
