你好,我想删除所有数据在我的postgresql表,但不是表本身。 我怎么能这样做呢?
对于小表,DELETE通常更快,需要较少的主动锁定(对并发加载很重要):
DELETE FROM tbl;
没有WHERE条件。
对于中等或更大的表,使用TRUNCATE,就像@Greg post:
TRUNCATE tbl;
很难确定“小”和“大”之间的界限,因为这取决于许多变量。您必须在安装过程中进行测试。
PostgreSQL数据库中表的内容可以通过几种方式删除。
使用sql删除表内容:
删除一个表的内容:
TRUNCATE table_name;
DELETE FROM table_name;
删除所有命名表的内容:
TRUNCATE table_a, table_b, …, table_z;
删除命名表和引用它们的表的内容(我将在后面的回答中详细解释):
TRUNCATE table_a, table_b CASCADE;
使用pgAdmin删除表内容:
删除一个表的内容:
Right click on the table -> Truncate
删除表和引用它的表的内容:
Right click on the table -> Truncate Cascaded
delete和truncate的区别:
从文档中可以看到:
DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html
使用从其他表引用的表:
当你的数据库有多个表时,这些表可能有关系。 作为一个例子,有三个表:
create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);
create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
还有一些准备好的表格数据:
insert into customers values (1, 'John', 'Smith');
insert into orders values
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);
insert into loyalty_cards values (100, 'A123456789', 1);
表orders引用表customers,表loyalty_cards引用表customers。当你尝试TRUNCATE / DELETE FROM被其他表引用的表(其他表对命名表有外键约束)时,你会得到一个错误。要从所有三个表中删除内容,您必须为所有这些表命名(顺序不重要)
TRUNCATE customers, loyalty_cards, orders;
或者只是使用CASCADE关键字引用的表(可以命名多个表,而不仅仅是一个表)
TRUNCATE customers CASCADE;
pgAdmin也是如此。右键单击客户表并选择截断级联。
我发现了一个非常简单和快速的方法,每个人都可能使用像DBeaver这样的工具: 你只需要选择所有你想要截断的表(SHIFT +单击或CTRL +单击),然后右键单击
如果你有外键,在设置面板上也选择CASCADE选项。开始,这就是一切!
推荐文章
- PostgreSQL可以索引数组列吗?
- PostgreSQL:角色不允许登录
- 如何查找Postgres / PostgreSQL表及其索引的磁盘大小
- 是使用各有一个模式的多个数据库更好,还是使用一个数据库有多个模式更好?
- 如果字符串包含
- 对于PostgreSQL表来说,多大才算太大?
- 将一列的多个结果行连接为一列,按另一列分组
- 使用pgadmin连接到heroku数据库
- 在PostgreSQL中快速发现表的行数
- 更改varchar列的大小为较低的长度
- 如何首次配置postgresql ?
- 数据库性能调优有哪些资源?
- 如何在PostgreSQL中自动更新时间戳
- 当使用JDBC连接到postgres时,是否可以指定模式?
- SQL:从时间戳日期减去1天