

# Tables and migrations

You create and change the tables in your Amplify backend database with migrations. A migration is a SQL file in your app’s `migrations/` folder that creates or changes PostgreSQL tables, views, functions, triggers or types. Each deployment applies your new migrations to the environment that it deploys to. To apply migrations to the local backend on your computer, see [Develop locally](backend-local.md).

## Create a table
<a name="backend-data-create"></a>

The following steps add a `notes` table and deploy it to the `preview` environment. Each signed-in user reads and writes their own rows in the table.

1. Run the following command to create a migration file:

   ```bash
   # --description is required, and it becomes part of the file name
   aws amplifygen3 local migration create --description "create notes"
   ```

   You should see a new file such as `migrations/20260923040000_create_notes.sql`. The command names each file with a 14-digit UTC timestamp and your description. The file holds only the comment `-- create notes`. Write your SQL in the file before you deploy it. A comment-only file passes the empty check, so the backend records it as applied, and adding SQL to it later fails with a checksum mismatch.

1. Add the following SQL to the file:

   ```sql
   create table public.notes (
     id         bigint generated always as identity primary key,
     owner_id   text not null default auth.uid()    -- the signed-in user's ID
                references auth."user"(id) on delete cascade,
     body       text not null,
     created_at timestamptz not null default now()
   );
   
   create index notes_owner_idx on public.notes (owner_id);
   
   alter table public.notes enable row level security;
   create policy "notes_select_own" on public.notes for select
     to authenticated using ((select auth.uid()) = owner_id);
   create policy "notes_insert_own" on public.notes for insert
     to authenticated with check ((select auth.uid()) = owner_id);
   create policy "notes_update_own" on public.notes for update
     to authenticated using ((select auth.uid()) = owner_id)
     with check ((select auth.uid()) = owner_id);
   create policy "notes_delete_own" on public.notes for delete
     to authenticated using ((select auth.uid()) = owner_id);
   
   grant select, insert, update, delete on public.notes to authenticated;
   ```

   Each migration that creates a table needs a `grant` to the roles that use the table, row-level security (RLS) turned on, and RLS policies. The data API serves the table after the grant, and returns only the rows allowed by the RLS policies that you configured. For more information, see [Secure your data](backend-rls.md).

1. Commit the file, and run the following command to deploy to `preview`:

   ```bash
   aws amplifygen3 deploy --env preview
   ```

   If you deploy your app from Git, push the commit instead. The deployment from that push applies the migration.

1. Run the following command to check that the migration is applied:

   ```bash
   aws amplifygen3 migration list --env preview
   ```

   You should see the file with the status `applied`.

### Columns and schemas
<a name="backend-data-columns"></a>

Use the following conventions when you create tables:
+  **User IDs** – Store user IDs in a `text` column, because `auth.uid()` returns `text`. The column can reference the user table, `auth."user"(id)`. Add `on delete cascade` to delete a user’s rows when the user is deleted.
+  **Schemas** – The data API serves the tables in the `public` schema. PostgreSQL creates a table in `public` when you don’t name a schema. To keep a table out of the data API, create it in your own schema, such as `private`. Don’t change the backend’s `amplify` and `auth` schemas.

## Change a table
<a name="backend-data-change"></a>

To change a table, create a new migration with `aws amplifygen3 local migration create`, and write the change in it. An ORM can write the SQL for you. For more information, see [Connect to your database](backend-database-connect.md). If you edit an applied file, the next deployment fails with `checksum_mismatch`. Name the new file so that it sorts after every file that an environment has applied. Otherwise, the deployment fails with `out of order`.

To add a required column to a table that has rows, give it a constant default:

```sql
alter table public.notes add column title text not null default '';
```

A migration that adds a `not null` column without a default works on an empty table, and fails the deployment on a table with rows. You can also add the column as nullable, update the rows, then set `not null`, in one migration. Don’t use `default auth.uid()` for the new column. No user is signed in while a migration runs, so `auth.uid()` returns null, and the existing rows get null.

## Deploy your migrations
<a name="backend-data-deploy"></a>

 `aws amplifygen3 deploy` applies your pending migrations in name order, each in its own transaction, before it builds your website. Without `--env`, it deploys to `preview`.

**Important**  
 **Important:** Rolling back your website doesn’t roll back your database. The database keeps the migrations that a deployment applied, even when the build fails or you roll back.

**Warning**  
 **Warning:** A deployment applies destructive SQL without a confirmation prompt. A migration with `drop table`, `drop column`, `truncate` or a column type change deletes or rewrites the affected data in the environment that you deploy to, including `production`.

## Check which migrations are applied
<a name="backend-data-check"></a>

The backend records each applied file by name and checksum in the `amplify.migrations` table, and applies each file once.

To compare your `migrations/` folder with a deployed environment, run the following command. Without `--env`, it uses `preview`.

```bash
aws amplifygen3 migration list --env production
```

 `migration list` compares file names. It fails on a misnamed `.sql` file. It doesn’t flag an edited or misordered file, and an applied file that is missing locally still shows `applied`. The next deployment fails on an edited, misordered or missing file with one of the [Migration errors](#migration-errors).

## When a migration fails
<a name="backend-data-failed"></a>

The backend rolls back a file that fails, and doesn’t record it. The files before it stay applied, and the files after it don’t run. Fix the same file and deploy again. Keep `COMMIT` out of migrations. When the file fails, the statements before a `COMMIT` stay applied, and the next deployment runs them again.

The deployment stops with `MIGRATION_FAILED`, and your website keeps serving the previous deployment. To find and fix the cause:

1. Run the following command to see the file, the PostgreSQL error and its SQLSTATE, and the line when PostgreSQL reports one. An error in the SQL text, such as a syntax error, has a line. An error raised while a statement runs, such as `23502`, has none, and the output says that the failing line is not known.

   ```bash
   aws amplifygen3 deployment get --id <deployment-id> --env preview
   ```

1. Run the following command to read the full error in the database log. If log delivery is off, run the `aws amplifygen3 logs-config edit` command that `logs get` prints.

   ```bash
   aws amplifygen3 logs get --log-type database --deployment-id <deployment-id> --env preview
   ```

   Database logs are on by default for an app with a backend. A deployment’s database lines can take up to 2 minutes after the deployment ends to arrive. Until then, `logs get` prints `No database lines for deployment <id> yet`, and `--follow` waits for them.

1. If the error says that the migration failed because of an internal database error, run `aws amplifygen3 deploy` again without changes. Otherwise, fix the file and deploy again.

## Undo a schema change
<a name="backend-data-undo"></a>

To undo a change, write a new migration that reverses it. To keep a bad change out of `production`:
+  **Test in `preview` first** – Deploy each schema change to `preview` before you deploy it to `production`.
+  **Keep the schema compatible with the deployed code** – Add a column before your code reads it, and drop it once no deployed code uses it.
+  **Save a copy before a destructive migration** – Run `aws amplifygen3 db dump --env production --output-file before.sql`.

To restore `production` to an earlier time, see [Backups and restore](backend-backups.md).

## Migration errors
<a name="migration-errors"></a>


| Error | Cause | Fix | 
| --- | --- | --- | 
|  `migration '<id>' does not follow the migration file name rule <14-digit timestamp>_<description>.sql`  | A `.sql` file in `migrations/` lacks a timestamp name | Create files with `local migration create`  | 
|  `migration '<id>' already applied with a different checksum`  | An applied file was edited | Undo the edit, and write a new migration | 
|  `migration '<id>' is out of order`  | A new file sorts before an applied one, often after a Git merge | If no environment has applied the file, rename it to a later timestamp | 
|  `already-applied migration '<id>' is missing from the submitted stack`  | An applied file was renamed or deleted | Restore it under its applied name. Its SQL is in the `ddl` column of `amplify.migrations`  | 
|  `23502` (`contains null values`) | A table with rows gets a new `not null` column with no default | Add a constant default, or backfill in the same migration | 
|  `permission denied for table user`  | The migration changes `auth."user"`, such as with a trigger | Write the user’s row from your app | 

For more information about promoting and rolling back a deployment, see [Promote a deployment](deploy-your-app-promote.md).