> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Query Data

This page has instructions for making SQL [selection queries](https://docs.cockroachlabs.com/docs/v24.3/selection-queries.md) against CockroachDB from various programming languages.

## Before you begin

Before reading this page, do the following:

* [Create a CockroachDB Standard cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/quickstart.md) or [start a local cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/quickstart.md?filters=local).
* [Install a Driver or ORM Framework](https://docs.cockroachlabs.com/docs/v24.3/install-client-drivers.md).
* [Connect to the database](https://docs.cockroachlabs.com/docs/v24.3/connect-to-the-database.md).
* [Insert data](https://docs.cockroachlabs.com/docs/v24.3/insert-data.md) that you now want to run queries against.

> [!NOTE]
>
> When running under the default [`SERIALIZABLE`](https://docs.cockroachlabs.com/docs/v24.3/demo-serializable) isolation level, your application should [use a retry loop to handle transaction retry errors](https://docs.cockroachlabs.com/docs/v24.3/query-behavior-troubleshooting.md#transaction-retry-errors) that can occur under [contention](https://docs.cockroachlabs.com/docs/v24.3/performance-best-practices-overview.md#understanding-and-avoiding-transaction-contention).

## Simple selects

> [tab] SQL
>
> ```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT id, balance from accounts;
> ```
>
> For more information about how to use the built-in SQL client, see the [`cockroach sql`](https://docs.cockroachlabs.com/docs/v24.3/cockroach-sql) reference docs.

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> // 'db' is an open database connection
>
> rows, err := db.Query("SELECT id, balance FROM accounts")
> if err != nil {
>     log.Fatal(err)
> }
> defer rows.Close()
> fmt.Println("Initial balances:")
> for rows.Next() {
>     var id, balance int
>     if err := rows.Scan(&id, &balance); err != nil {
>         log.Fatal(err)
>     }
>     fmt.Printf("%d %d\n", id, balance)
> }
> ```
>
> For complete examples, see:
>
> * [Build a Go App with CockroachDB](https://docs.cockroachlabs.com/docs/v24.3/build-a-go-app-with-cockroachdb.md) (pgx)
> * [Build a Go App with CockroachDB and GORM](https://docs.cockroachlabs.com/docs/v24.3/build-a-go-app-with-cockroachdb.md)

> [tab] Java
>
> ```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> // ds is an org.postgresql.ds.PGSimpleDataSource
>
> try (Connection connection = ds.getConnection()) {
>     Statement stmt = connection.createStatement();
>     ResultSet rs = stmt.executeQuery("SELECT id, balance FROM accounts");
>
>     while (rs.next()) {
>         int id = rs.getInt(1);
>         int bal = rs.getInt(2);
>         System.out.printf("ID: %10s\nBalance: %5s\n", id, bal);
>     }
>     rs.close();
>
> } catch (SQLException e) {
>     System.out.printf("sql state = [%s]\ncause = [%s]\nmessage = [%s]\n",
>                       e.getSQLState(), e.getCause(), e.getMessage());
> }
> ```
>
> For complete examples, see:
>
> * [Build a Java App with CockroachDB](https://docs.cockroachlabs.com/docs/v24.3/build-a-java-app-with-cockroachdb.md) (JDBC)
> * [Build a Java App with CockroachDB and Hibernate](https://docs.cockroachlabs.com/docs/v24.3/build-a-java-app-with-cockroachdb-hibernate.md)

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> # conn is a psycopg2 connection
>
> with conn.cursor() as cur:
>     cur.execute("SELECT id, balance FROM accounts")
>     rows = cur.fetchall()
>     for row in rows:
>         print([str(cell) for cell in row])
> ```
>
> For complete examples, see:
>
> * [Build a Python App with CockroachDB](https://docs.cockroachlabs.com/docs/v24.3/build-a-python-app-with-cockroachdb-psycopg3.md) (psycopg3)
> * [Build a Python App with CockroachDB and SQLAlchemy](https://docs.cockroachlabs.com/docs/v24.3/build-a-python-app-with-cockroachdb-sqlalchemy.md)
> * [Build a Python App with CockroachDB and Django](https://docs.cockroachlabs.com/docs/v24.3/build-a-python-app-with-cockroachdb-django.md)
> * [Build a Python App with CockroachDB and asyncpg](https://docs.cockroachlabs.com/docs/v24.3/build-a-python-app-with-cockroachdb-asyncpg.md)

## Order results

To order the results of a query, use an `ORDER BY` clause.

For example:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT * FROM bank ORDER BY balance;
```

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
  id | balance |                                               payload
-----+---------+-------------------------------------------------------------------------------------------------------
   0 |    -500 | initial-dTqnRurXztAPkykhZWvsCmeJkMwRNcJAvTlNbgUEYfagEQJaHmfPsquKZUBOGwpAjPtATpGXFJkrtQCEJODSlmQctvyh
   1 |    -499 | initial-PCLGABqTvrtRNyhAyOhQdyLfVtCmRykQJSsdwqUFABkPOMQayVEhiAwzZKHpJUiNmVaWYZnReMKfONZvRKbTETaIDccE
   2 |    -498 | initial-VNfyUJHfCmMeAUoTgoSVvnByDyvpHNPHDfVoNWdXBFQpwMOBgNVtNijyTjmecvFqyeLHlDbIBRrbCzSeiHWSLmWbhIvh
   3 |    -497 | initial-llflzsVuQYUlfwlyoaqjdwKUNgNFVgvlnINeOUUVyfxyvmOiAelxqkTBfpBBziYVHgQLLEuCazSXmURnXBlCCfsOqeji
   4 |    -496 | initial-rmGzVVucMqbYnBaccWilErbWvcatqBsWSXvrbxYUUEhmOnccXzvqcsGuMVJNBjmzKErJzEzzfCzNTmLQqhkrDUxdgqDD
(5 rows)
```

For reference documentation and more examples, see the [`ORDER BY`](https://docs.cockroachlabs.com/docs/v24.3/order-by) syntax page.

## Limit results

To limit the results of a query, use a `LIMIT` clause.

For example:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT * FROM bank LIMIT 5;
```

```text theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
  id | balance |                                               payload
-----+---------+-------------------------------------------------------------------------------------------------------
   0 |       0 | initial-dTqnRurXztAPkykhZWvsCmeJkMwRNcJAvTlNbgUEYfagEQJaHmfPsquKZUBOGwpAjPtATpGXFJkrtQCEJODSlmQctvyh
   1 |       0 | initial-PCLGABqTvrtRNyhAyOhQdyLfVtCmRykQJSsdwqUFABkPOMQayVEhiAwzZKHpJUiNmVaWYZnReMKfONZvRKbTETaIDccE
   2 |       0 | initial-VNfyUJHfCmMeAUoTgoSVvnByDyvpHNPHDfVoNWdXBFQpwMOBgNVtNijyTjmecvFqyeLHlDbIBRrbCzSeiHWSLmWbhIvh
   3 |       0 | initial-llflzsVuQYUlfwlyoaqjdwKUNgNFVgvlnINeOUUVyfxyvmOiAelxqkTBfpBBziYVHgQLLEuCazSXmURnXBlCCfsOqeji
   4 |       0 | initial-rmGzVVucMqbYnBaccWilErbWvcatqBsWSXvrbxYUUEhmOnccXzvqcsGuMVJNBjmzKErJzEzzfCzNTmLQqhkrDUxdgqDD
(5 rows)
```

For reference documentation and more examples, see the [`LIMIT`/`OFFSET`](https://docs.cockroachlabs.com/docs/v24.3/limit-offset) syntax page.

## Joins

The syntax for a [selection query](https://docs.cockroachlabs.com/docs/v24.3/selection-queries.md) with a two-way [join](https://docs.cockroachlabs.com/docs/v24.3/joins.md) is shown below.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
SELECT
    a.col1, b.col1
FROM
    some_table AS a
    JOIN
    some_other_table AS b
    ON
    a.id = b.id
WHERE
    a.col2 > 100 AND a.col3 > now()
ORDER BY
    a.col2 DESC
LIMIT
    25;
```

Join performance can be a big factor in your application's performance. For more information about how to make sure your SQL performs well, see [Optimize Statement Performance](https://docs.cockroachlabs.com/docs/v24.3/make-queries-fast.md).

## See also

Reference information related to this task:

* [Selection queries](https://docs.cockroachlabs.com/docs/v24.3/selection-queries.md)
* [`SELECT`](https://docs.cockroachlabs.com/docs/v24.3/select-clause)
* [Joins](https://docs.cockroachlabs.com/docs/v24.3/joins.md)
* [Paginate through limited results](https://docs.cockroachlabs.com/docs/v24.3/pagination.md)
* [Transaction Contention](https://docs.cockroachlabs.com/docs/v24.3/performance-best-practices-overview.md#transaction-contention)

Other common tasks:

* [Connect to the Database](https://docs.cockroachlabs.com/docs/v24.3/connect-to-the-database.md)
* [Insert Data](https://docs.cockroachlabs.com/docs/v24.3/insert-data.md)
* [Update Data](https://docs.cockroachlabs.com/docs/v24.3/update-data.md)
* [Delete Data](https://docs.cockroachlabs.com/docs/v24.3/delete-data.md)
* [Run Multi-Statement Transactions](https://docs.cockroachlabs.com/docs/v24.3/run-multi-statement-transactions)
* [Troubleshoot SQL Statements](https://docs.cockroachlabs.com/docs/v24.3/query-behavior-troubleshooting.md)
* [Optimize Statement Performance](https://docs.cockroachlabs.com/docs/v24.3/make-queries-fast.md)
* [Example Apps](https://docs.cockroachlabs.com/docs/v24.3/example-apps)
