

# Creating or migrating databases in a data group

You create databases in a data group, or migrate existing ones into it, with SQL. Connect to the writer DB instance of the DB cluster through the DB cluster endpoint, as you do for any Aurora DB cluster. For more information, see [Connecting to an Amazon Aurora DB cluster](Aurora.Connecting.md).

Before you create objects in the data group, map the roles or users that will own them. For more information, see [Managing roles for data groups](aurora-data-groups-users.md).

**Topics**
+ [Creating a database in a data group](#dg-create-databases)
+ [Migrating existing databases into a data group](aurora-data-groups-migrating.md)

## Creating a database in a data group
<a name="dg-create-databases"></a>

If you create a database without naming a data group, Aurora creates it in the default data group, and it doesn't move with any data group. To create a database in a data group, name the data group when you create it:
+ Each data group has a tablespace with the same name. To create a database in the data group, name that tablespace in the `TABLESPACE` clause of `CREATE DATABASE`. To create several databases in the data group in one session, set the `aurora_datagroup` parameter first. If you also use a `TABLESPACE` clause, the clause takes precedence over the parameter.

------
#### [ Aurora PostgreSQL ]

The following example creates one database in the `tenant42` data group.

```SQL
CREATE DATABASE orders TABLESPACE tenant42;
```

The following example creates two databases in one session.

```SQL
SET aurora_datagroup = 'tenant42';
CREATE DATABASE payments;
CREATE DATABASE invoices;
RESET aurora_datagroup;
```

------

The data group must exist when you set the variable. If you set it to a name that isn't a data group, the statement fails with the error `Datagroup "{{name}}" does not exist.`

The only setting that chooses the data group for a session is `aurora_datagroup`. PostgreSQL doesn't return an error for an unknown setting name that contains a dot, such as `aurora.datagroup`. Such a setting has no effect, and `CREATE DATABASE` creates the database in the default data group. After you create databases, check which data group each one is in. For more information, see [Finding the data groups and their databases with SQL](aurora-data-groups-viewing.md#dg-list-sql).

If a statement tries to put a table in a different tablespace from its database, it fails with `cannot place relation "{{table}}" in a datagroup different from its database`. To avoid this error, omit the `TABLESPACE` clause when you create tables.

Because Aurora manages the tablespace of each data group, you can't rename the tablespace, and you shouldn't change its owner.

To migrate an existing database into a data group, use a data group migration. For more information, see [Migrating existing databases into a data group](aurora-data-groups-migrating.md).