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

# Query Data

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

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:

* <InternalLink version="cockroachcloud" path="quickstart">Create a CockroachDB Standard cluster</InternalLink> or <InternalLink version="cockroachcloud" path="quickstart?filters=local">start a local cluster</InternalLink>.
* <InternalLink path="install-client-drivers">Install a Driver or ORM Framework</InternalLink>.
* <InternalLink path="connect-to-the-database">Connect to the database</InternalLink>.
* <InternalLink path="insert-data">Insert data</InternalLink> that you now want to run queries against.

<Note>
  When running under the default <InternalLink path="demo-serializable">`SERIALIZABLE`</InternalLink> isolation level, your application should <InternalLink path="query-behavior-troubleshooting#transaction-retry-errors">use a retry loop to handle transaction retry errors</InternalLink> that can occur under <InternalLink path="performance-best-practices-overview#understanding-and-avoiding-transaction-contention">contention</InternalLink>.
</Note>

## 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 <InternalLink path="cockroach-sql">`cockroach sql`</InternalLink> 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:

* <InternalLink path="build-a-go-app-with-cockroachdb">Build a Go App with CockroachDB</InternalLink> (pgx)
* <InternalLink path="build-a-go-app-with-cockroachdb">Build a Go App with CockroachDB and GORM</InternalLink>

```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:

* <InternalLink path="build-a-java-app-with-cockroachdb">Build a Java App with CockroachDB</InternalLink> (JDBC)
* <InternalLink path="build-a-java-app-with-cockroachdb-hibernate">Build a Java App with CockroachDB and Hibernate</InternalLink>

```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:

* <InternalLink path="build-a-python-app-with-cockroachdb-psycopg3">Build a Python App with CockroachDB</InternalLink> (psycopg3)
* <InternalLink path="build-a-python-app-with-cockroachdb-sqlalchemy">Build a Python App with CockroachDB and SQLAlchemy</InternalLink>
* <InternalLink path="build-a-python-app-with-cockroachdb-django">Build a Python App with CockroachDB and Django</InternalLink>
* <InternalLink path="build-a-python-app-with-cockroachdb-asyncpg">Build a Python App with CockroachDB and asyncpg</InternalLink>

## 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 <InternalLink path="order-by">`ORDER BY`</InternalLink> 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 <InternalLink path="limit-offset">`LIMIT`/`OFFSET`</InternalLink> 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]
* <InternalLink path="select-clause">`SELECT`</InternalLink>
* [Joins][joins]
* [Paginate through limited results][paginate]
* <InternalLink path="performance-best-practices-overview#transaction-contention">Transaction Contention</InternalLink>

Other common tasks:

* <InternalLink path="connect-to-the-database">Connect to the Database</InternalLink>
* <InternalLink path="insert-data">Insert Data</InternalLink>
* <InternalLink path="update-data">Update Data</InternalLink>
* <InternalLink path="delete-data">Delete Data</InternalLink>
* <InternalLink path="run-multi-statement-transactions">Run Multi-Statement Transactions</InternalLink>
* <InternalLink path="query-behavior-troubleshooting">Troubleshoot SQL Statements</InternalLink>
* [Optimize Statement Performance][fast]
* <InternalLink path="example-apps">Example Apps</InternalLink>

[selection]: /docs/v25.1/selection-queries

[manual]: /docs/v25.1/manual-deployment

[orchestrated]: orchestration.html

[fast]: /docs/v25.1/make-queries-fast

[paginate]: /docs/v25.1/pagination

[joins]: /docs/v25.1/joins
