DROP DATABASE

The DROP DATABASE statement removes a database and all its objects from a CockroachDB cluster.

Note:

This statement performs a schema change. For more information about how online schema changes work in CockroachDB, see Online Schema Changes.

Required privileges

The user must have the DROP privilege on the database and on all tables in the database.

Synopsis

DROPDATABASEIFEXISTSnameCASCADERESTRICT

Parameters

ParameterDescription
IF EXISTSDrop the database if it exists; if it does not exist, do not return an error.
nameThe name of the database you want to drop. You cannot drop a database if it is set as the current database or if sql_safe_updates = true.
CASCADE(Default) Drop all tables and views in the database as well as all objects (such as constraints and views) that depend on those tables.CASCADE does not list objects it drops, so should be used cautiously.
RESTRICTDo not drop the database if it contains any tables or views.

Viewing schema changes

This schema change statement is registered as a job. You can view long-running jobs with SHOW JOBS.

Examples

Drop a database and its objects (CASCADE)

For non-interactive sessions (e.g., client applications), DROP DATABASE applies the CASCADE option by default, which drops all tables and views in the database as well as all objects (such as constraints and views) that depend on those tables.

  1. > SHOW TABLES FROM db2;
  1. +------------+
  2. | table_name |
  3. +------------+
  4. | t1 |
  5. | v1 |
  6. +------------+
  7. (2 rows)
  1. > DROP DATABASE db2;
  1. > SHOW TABLES FROM db2;
  1. pq: database "db2" does not exist

For interactive sessions from the built-in SQL client, either the CASCADE option must be set explicitly or the —unsafe-updates flag must be set when starting the shell.

Prevent dropping a non-empty database (RESTRICT)

When a database is not empty, the RESTRICT option prevents the database from being dropped:

  1. > SHOW TABLES FROM db2;
  1. +------------+
  2. | table_name |
  3. +------------+
  4. | t1 |
  5. | v1 |
  6. +------------+
  7. (2 rows)
  1. > DROP DATABASE db2 RESTRICT;
  1. pq: database "db2" is not empty and CASCADE was not specified

See also

Was this page helpful?
YesNo