pg_total_relation_size不是预期的

时间:2016-02-17 07:42:26

标签: postgresql

我刚刚清除了表格,但仍然pg_total_relation_size返回大约100 kB

DELETE FROM points;   
SELECT pg_size_pretty(pg_total_relation_size('"public"."points"'));

我有刷新东西吗?

1 个答案:

答案 0 :(得分:0)

不,通常你不需要做任何事情。删除后可以使用该空间,但表不会缩小。如果您确实需要回收空间,例如,如果您已经使用大型测试表填充了硬盘驱动器,那么您可以使用VACUUM命令执行此操作。 VACUUM FULL会尽可能缩小所有表格。

删除行时,Postgresql不会缩小/压缩表。这比数据库重组表要便宜得多。数据库将定期运行autovacuum以回收空间。

Craig Ringer在similar answer中更好地解释了这一点。

以下是一些测试示例代码:

--#### Initialize test: Insert 99999 rows with test data
DROP SCHEMA testschema CASCADE;
CREATE SCHEMA testschema;

CREATE TABLE testschema.points (
   data text DEFAULT 'asjklfaskljgkljasklgjaskldjgklasjdgklasjdgkljasdghaskldvhajklnsefawegwafeawgfawegfadg'
);    

INSERT INTO testschema.points SELECT generate_series(1,99999);

SELECT pg_size_pretty(pg_total_relation_size('"testschema"."points"'));
--Output: 3567 kB


--##### Delete: Space is not released to the OS yet.
DELETE FROM testschema.points;

SELECT pg_size_pretty(pg_total_relation_size('"testschema"."points"'));
--Output: 3567 kB


--#### Vacuum: Table is compacted and space is released to the OS.
VACUUM FULL testschema.points;

SELECT pg_size_pretty(pg_total_relation_size('"testschema"."points"'));
-- Output: 8192 bytes