

# Read data

Your AWS Amplify app reads the rows of your tables through the Amplify backend data API, with the client SDK or with HTTP requests. Reads use PostgREST-compatible queries. A read returns the rows allowed by the grants and row-level security (RLS) policies that you configured. To insert, update, upsert or delete rows, see [Write data](backend-data-api-write.md).

## Before you begin
<a name="_before_you_begin"></a>

You need the following:
+ A table with a grant and a `select` policy for the role that reads it, added in a migration. The examples use a `notes` table with the columns `id`, `owner_id`, `body` and `created_at`. For more information about grants and policies, see [Secure your data](backend-rls.md).
+ The client SDK, `@aws-amplifygen3/backend-client-js`, in your app. For more information about installing it, see the [client SDK README](https://github.com/aws-amplifygen3/amplifygen3/blob/main/packages/client-sdk/js/README.md) on GitHub.

Create a client with the backend URL and the publishable key:

```typescript
import { createClient } from '@aws-amplifygen3/backend-client-js'

const backend = createClient(backendUrl, publishableKey)
```

The client sends its calls as a visitor until a user signs in. After that, it sends the user’s token with every call. For more information about roles, see [API keys and roles](backend-keys.md). To read every user’s rows, call the data API from server code, and sign each call with AWS credentials. For more information, see [Call the backend with full access](backend-server-code.md#backend-server-code-full-access).

Every call returns an object with `data`, `error`, `count`, `status`, `statusText` and `success`. Check `error`. When the RLS policies that you configured match no rows, `data` is `[]` and `error` is `null`.

## Select rows
<a name="_select_rows"></a>

Pass `select` the columns to return, or `'*'` for every column:

```typescript
const { data, error } = await backend.from('notes').select('id, body')
if (error) throw error
```

To read one row, add `.single()`. It returns the error `PGRST116` when zero rows or several rows match. When the row might not exist, use `.maybeSingle()`:

```typescript
const { data: note, error } = await backend.from('notes').select('*').eq('id', 1).maybeSingle()
```

## Filter rows
<a name="_filter_rows"></a>

Add filters after `select`. A row must match every filter that you chain. In an HTTP request, each filter is a query parameter:


| SDK method | HTTP parameter | Returns rows where | 
| --- | --- | --- | 
|  `.eq('id', 1)`  |  `id=eq.1`  |  `id` is 1 | 
|  `.neq('status', 'done')`  |  `status=neq.done`  |  `status` is anything but `done`  | 
|  `.gt`, `.gte`, `.lt`, `.lte`  |  `id=gt.10`, `gte.`, `lt.`, `lte.`  | The value is above, at least, below or at most the one given | 
|  `.in('id', [1, 2])`  |  `id=in.(1,2)`  |  `id` is 1 or 2 | 
|  `.is('archived_at', null)`  |  `archived_at=is.null`  |  `archived_at` is the value given: null, `true` or `false`  | 
|  `.like('body', '%cat%')`, `.ilike`  |  `body=like.*cat*`, `ilike.`  |  `body` matches the pattern (`ilike` ignores case) | 
|  `.contains('tags', ['a', 'b'])`  |  `tags=cs.{a,b}`  | The array or `jsonb` value contains the one given, such as `.contains('meta', { color: 'red' })`  | 
|  `.containedBy('tags', ['a', 'b'])`  |  `tags=cd.{a,b}`  | The array holds nothing but `a` and `b`  | 
|  `.overlaps('tags', ['a', 'b'])`  |  `tags=ov.{a,b}`  | The array holds `a` or `b`  | 
|  `.textSearch('body', 'cat dog', { type: 'websearch' })`  |  `body=wfts.cat dog`  |  `body` matches the search terms | 
|  `.not('archived_at', 'is', null)`  |  `archived_at=not.is.null`  | The filter doesn’t match | 
|  `.or('status.eq.open,id.gt.10')`  |  `or=(status.eq.open,id.gt.10)`  | Either filter matches | 

 `%` matches any characters in a pattern. Write `*` for `%` in an HTTP request. To read or filter on a field of a `json` or `jsonb` column, use `->` for a JSON value or `->>` for text, such as `select('id, meta->>color')` or `.eq('meta->>color', 'red')`. Without a `type`, `.textSearch` uses `to_tsquery` syntax. The types `plain`, `phrase` and `websearch` use `plainto_tsquery`, `phraseto_tsquery` and `websearch_to_tsquery`, and the `config` option names the text search configuration, such as `english`. The SDK’s query builder follows `postgrest-js` 2.x and supports the same filters. For more information about the operators, see [PostgREST operators](https://docs.postgrest.org/en/stable/references/api/tables_views.html#operators) on the PostgREST website.

## Count rows
<a name="_count_rows"></a>

To count rows without reading them, pass `count` and `head`:

```typescript
const { count, error } = await backend.from('notes').select('*', { count: 'exact', head: true })
```

The count includes only the rows that the caller can read. An exact count reads every one of those rows, so it’s slow on a large table. A request for a planned or estimated count gets `400` and the code `COUNT_NOT_SUPPORTED`. To count over HTTP, send `Prefer: count=exact`, and read the total from the `Content-Range` response header, such as `0-49/6001`.

## Sort and page through rows
<a name="sort-and-page-through-rows"></a>

Sort the rows with `.order`, and read one page at a time with `.range`:

```typescript
const { data, error } = await backend
  .from('notes')
  .select('id, body, created_at')
  .order('created_at', { ascending: false }) // nullsFirst: true puts null values first
  .range(0, 49) // rows 1 to 50; .range(50, 99) reads the next 50
```

The same page over HTTP is `order=created_at.desc&limit=50&offset=0`. Use `limit` and `offset`, because the data API doesn’t page by the `Range` header. To read only the first 10 rows, use `.limit(10)`. Sort every paged read, so that each page starts where the previous one ended.

The database reads and skips every row before the offset. To read pages with a large offset, sort by `id` from highest to lowest with `.order('id', { ascending: false })`, and filter each page with `.lt('id', lastId)`, where `lastId` is the last `id` on the previous page.

## Read more than 1,000 rows
<a name="_read_more_than_1000_rows"></a>

One read returns at most 1,000 rows, for every role and every backend, and you can’t change the limit. A `select` with no limit or a larger one succeeds and returns 1,000 rows. When a read returns exactly 1,000 rows, more rows might exist.

The `Content-Range` response header has the range of rows returned, such as `0-999/*`. To find out whether more rows exist, ask for an exact count. The header then also has the total, such as `0-999/6001`, and the status is `206 Partial Content`.

To read every row, page through them with `.range`. `.range(1000, 1999)` returns rows 1,001 to 2,000. For more information, see [Sort and page through rows](#sort-and-page-through-rows).

## Read related tables
<a name="_read_related_tables"></a>

To read rows with their related rows in one request, name the related table in `select`. The data API joins the two tables on a foreign key. In the following example, `items.list_id` references `lists.id`:

```typescript
const { data, error } = await backend.from('lists').select('id, name, items(id, body)')
```

The same read over HTTP is `GET /rest/lists?select=id,name,items(id,body)`. The data API reads `items` as the same caller, so `items` needs its own grant and `select` policy. A read on `items` with `select('id, body, lists(name)')` returns each item’s list as an object, or `null`.

A read returns at most 1,000 items for each list, and the response headers don’t show whether items were left out. To read more, query the related table on its own and page through it.

### Filter, sort and limit related rows
<a name="_filter_sort_and_limit_related_rows"></a>

A filter on a related table filters only the related rows. The following read returns every list, including lists with no open items, and each list holds only its open items:

```typescript
const { data, error } = await backend.from('lists').select('id, name, items(id, body)').eq('items.done', false)
```

To return only the lists that have an open item, add `!inner` after the table name: `items!inner(id, body)`. The HTTP form is `select=id,name,items!inner(id,body)&items.done=eq.false`.

To sort or limit the related rows, pass `referencedTable`:

```typescript
const { data, error } = await backend
  .from('lists')
  .select('id, name, items(id, body, created_at)')
  .order('created_at', { referencedTable: 'items', ascending: false }) // HTTP: items.order=created_at.desc
  .limit(5, { referencedTable: 'items' }) // HTTP: items.limit=5
```

### Choose a foreign key
<a name="_choose_a_foreign_key"></a>

When two foreign keys join the same tables, the read fails with `PGRST201`. For example, `sender_id` and `recipient_id` on `messages` both reference `profiles`. Name the foreign key column after `!`, and give each embedded table its own name:

```typescript
const { data, error } = await backend
  .from('messages')
  .select('id, body, sender:profiles!sender_id(name), recipient:profiles!recipient_id(name)')
```

## Read data over HTTP
<a name="_read_data_over_http"></a>

To read data without the SDK, send a `GET` request to `/rest/<table>`, with the filters as query parameters. Run the following command to read the 20 newest notes:

```bash
curl -s "$API/rest/notes?select=id,body&order=created_at.desc&limit=20" \
  -H "apikey: $KEY" -H "Authorization: Bearer $JWT"
```

For more information about the backend URL, the publishable key, user tokens and headers, see [Call the data API over HTTP](backend-data-api-http.md).

## Read errors
<a name="_read_errors"></a>


| Error | Cause | Fix | 
| --- | --- | --- | 
|  `[]` with no error | The `select` policies that you configured match no rows for the caller | Change the policies in a new migration | 
|  `42501` (`401` signed out, `403` signed in) | The table has no grant for the caller’s role | In a new migration, grant `select` on the table to the caller’s role | 
|  `PGRST205` (`404`) | The table doesn’t exist, or its migration isn’t applied | Apply the migration | 
|  `42703` (`400`) | A column in `select` or a filter doesn’t exist | Fix the column name | 
|  `PGRST116` (`406`) |  `.single()` matched zero rows or several rows | Use `.maybeSingle()`, or filter to one row | 
|  `PGRST201`  | Two foreign keys join the embedded tables | Name the foreign key after `!`  | 
|  `COUNT_NOT_SUPPORTED` (`400`) | The read asked for a planned or estimated count | Use `count: 'exact'`  | 

For more information about other error codes, see [Data API errors](backend-data-api-errors.md).