> ## 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][selection] 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.2/install-client-drivers).
* [Connect to the database](https://docs.cockroachlabs.com/docs/v24.2/connect-to-the-database).
* [Insert data](https://docs.cockroachlabs.com/docs/v24.2/insert-data) that you now want to run queries against.

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

## Simple selects

```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.2/cockroach-sql) reference docs.

```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.2/build-a-go-app-with-cockroachdb) (pgx)
* [Build a Go App with CockroachDB and GORM](https://docs.cockroachlabs.com/docs/v24.2/build-a-go-app-with-cockroachdb)

```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.2/build-a-java-app-with-cockroachdb) (JDBC)
* [Build a Java App with CockroachDB and Hibernate](https://docs.cockroachlabs.com/docs/v24.2/build-a-java-app-with-cockroachdb-hibernate)

```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.2/build-a-python-app-with-cockroachdb-psycopg3) (psycopg3)
* [Build a Python App with CockroachDB and SQLAlchemy](https://docs.cockroachlabs.com/docs/v24.2/build-a-python-app-with-cockroachdb-sqlalchemy)
* [Build a Python App with CockroachDB and Django](https://docs.cockroachlabs.com/docs/v24.2/build-a-python-app-with-cockroachdb-django)
* [Build a Python App with CockroachDB and asyncpg](https://docs.cockroachlabs.com/docs/v24.2/build-a-python-app-with-cockroachdb-asyncpg)

## 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;
```

```
  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.2/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;
```

```
  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.2/limit-offset) syntax page.

## Joins

The syntax for a [selection query][selection] with a two-way [join][joins] 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][fast].

## See also

Reference information related to this task:

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

Other common tasks:

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

[selection]: https://docs.cockroachlabs.com/docs/v24.2/selection-queries

[manual]: https://docs.cockroachlabs.com/docs/v24.2/manual-deployment

[orchestrated]: orchestration.html

[fast]: https://docs.cockroachlabs.com/docs/v24.2/make-queries-fast

[paginate]: https://docs.cockroachlabs.com/docs/v24.2/pagination

[joins]: https://docs.cockroachlabs.com/docs/v24.2/joins
