The SET DATABASE statement sets the default database for the current session. When connected to the default database, you don’t need to reference it explicitly in statements.

In some cases, client drivers can drop and restart the connection to the server. When this happens, any session configurations made with SET statements are lost. It is therefore more reliable to set the database in the client's connection string. For examples in different languages, see the Build an App with CockroachDB tutorials.

Synopsis

SET DATABASE TO = database_name

Required Privileges

No privileges are required to set the default database.

Examples

$ cockroach sql --database=db1
# Welcome to the cockroach SQL interface.
# All statements must be terminated by a semicolon.
# To exit: CTRL + D.
> CREATE TABLE t3 (a INT PRIMARY KEY, b STRING(20)); 
> SHOW TABLES;
+-------+
| Table |
+-------+
| t1    |
| t2    |
| t3    |
+-------+
(3 rows)

Set the default database via SET DATABASE

$ cockroach sql
# Welcome to the cockroach SQL interface.
# All statements must be terminated by a semicolon.
# To exit: CTRL + D.
> SET DATABASE = db1;
> CREATE TABLE t3 (a INT PRIMARY KEY, b STRING(20)); 
> SHOW TABLES;
+-------+
| Table |
+-------+
| t1    |
| t2    |
| t3    |
+-------+
(3 rows)

Use a non-default database

$ cockroach sql --database=db1
# Welcome to the cockroach SQL interface.
# All statements must be terminated by a semicolon.
# To exit: CTRL + D.
> CREATE TABLE db2.t1 (a SERIAL PRIMARY KEY, b DECIMAL); 
> SHOW TABLES FROM db2;
+-------+
| Table |
+-------+
| t1    |
+-------+
(1 row)

See Also



Yes No