Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CREATE TABLE WITH NO DATA is very slow

Tags:

postgresql

I'm running this SQL command on PostgreSQL 11:

CREATE TABLE IF NOT EXISTS my_temp_table AS TABLE my_enormous_table WITH NO DATA;

It takes 5 minutes to make the new table.

The EXPLAIN ... is:

Seq Scan on my_enormous_table  (cost=0.00..35999196.34 rows=143407234 width=3278)

Moving to a query like CREATE TABLE ... (SELECT * FROM my_enormous_table WHERE FALSE); is orders of magnitude faster - there is no seq scan, and the outcome is the same.

Any ideas what could be causing this issue?

like image 598
PANDA Stack Avatar asked Feb 22 '26 06:02

PANDA Stack


1 Answers

WITH NO DATA still executes the query, it just ignores the result.

The better way to do that would be to avoid CREATE TABLE ... AS:

CREATE TABLE my_temp_table (LIKE my_enormous_table);

That also allows you to use the INCLUDING clause to copy default values, storage parameters, constraints and other things from the original table:

CREATE TABLE my_temp_table (LIKE my_enormous_table
                            INCLUDING CONSTRAINTS INCLUDING DEFAULTS);
like image 56
Laurenz Albe Avatar answered Feb 24 '26 20:02

Laurenz Albe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!