DROP DATABASE 是一个 DDL 命令,用于删除(永久删除)一个数据库。
DROP DATABASE 命令在所有 PostgreSQL 版本中都存在。
变更历史
- PostgreSQL 13
- 现在可以添加
FORCE选项来删除一个数据库,即使有其他用户连接(提交 1379fd53)
- 现在可以添加
- PostgreSQL 8.2
- 添加了
IF EXISTS子句(提交 5b352d8e)
- 添加了
示例
DROP DATABASE 的基本执行示例
postgres=# DROP DATABASE foo; DROP DATABASE
尝试删除一个不存在的数据库
postgres=# DROP DATABASE bar; ERROR: database "bar" does not exist
安全地尝试删除一个可能不存在的数据库
postgres=# DROP DATABASE IF EXISTS bar; NOTICE: database "bar" does not exist, skipping
尝试删除当前数据库
postgres=# DROP DATABASE postgres; ERROR: cannot drop the currently open database
尝试删除另一个当前正在使用的数据库
postgres=# DROP DATABASE foo; ERROR: database "foo" is being accessed by other users DETAIL: There are 2 other sessions using the database.
(请注意,PostgreSQL 可能需要几秒钟的延迟才能确定无法删除该数据库。)
强制删除另一个当前正在使用的数据库(PostgreSQL 13 及更高版本)
postgres=# DROP DATABASE foo WITH (FORCE); DROP DATABASE
无法删除任何模板数据库
postgres=# DROP DATABASE template0; ERROR: cannot drop a template database postgres=# DROP DATABASE template1 WITH (FORCE); ERROR: cannot drop a template database
参考资料
- PostgreSQL 文档: DROP DATABASE
