DROP TABLE

The DROP TABLE statement removes a table and all its indexes from a database.

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 specified table(s). If CASCADE is used, the user must have the privileges required to drop each dependent object as well.

Synopsis

DROPTABLEIFEXISTStable_name,CASCADERESTRICT

Parameters

ParameterDescription
IF EXISTSDrop the table if it exists; if it does not exist, do not return an error.
tablenameA comma-separated list of table names. To find table names, use SHOW TABLES.
CASCADEDrop all objects (such as constraints and views) that depend on the table.CASCADE does not list objects it drops, so should be used cautiously.
RESTRICT(Default)_ Do not drop the table if any objects (such as constraints and views) depend on it.

Viewing schema changes

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

Examples

Remove a table (no dependencies)

In this example, other objects do not depend on the table being dropped.

  1. > SHOW TABLES FROM bank;
  1. +--------------------+
  2. | table_name |
  3. +--------------------+
  4. | accounts |
  5. | branches |
  6. | user_accounts_view |
  7. +--------------------+
  8. (3 rows)
  1. > DROP TABLE bank.branches;
  1. DROP TABLE
  1. > SHOW TABLES FROM bank;
  1. +--------------------+
  2. | table_name |
  3. +--------------------+
  4. | accounts |
  5. | user_accounts_view |
  6. +--------------------+
  7. (2 rows)

Remove a table and dependent objects with CASCADE

In this example, a view depends on the table being dropped. Therefore, it's only possible to drop the table while simultaneously dropping the dependent view using CASCADE.

Warning:
CASCADE drops all dependent objects without listing them, which can lead to inadvertent and difficult-to-recover losses. To avoid potential harm, we recommend dropping objects individually in most cases.

  1. > SHOW TABLES FROM bank;
  1. +--------------------+
  2. | table_name |
  3. +--------------------+
  4. | accounts |
  5. | user_accounts_view |
  6. +--------------------+
  7. (2 rows)
  1. > DROP TABLE bank.accounts;
  1. pq: cannot drop table "accounts" because view "user_accounts_view" depends on it
  1. > DROP TABLE bank.accounts CASCADE;
  1. DROP TABLE
  1. > SHOW TABLES FROM bank;
  1. +------------+
  2. | table_name |
  3. +------------+
  4. +------------+
  5. (0 rows)

See also

Was this page helpful?
YesNo