Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop sequence and cascade

Tags:

I would like to drop the sequence used in table and the table itself in one statement using CASCADE, but I'm getting NOTICE and table is not dropped. For example:

CREATE SEQUENCE seq1; CREATE TABLE t1 (f1 INT NOT NULL DEFAULT nextval('seq1')); 

And then when I do:

DROP SEQUENCE seq1 CASCADE; 

I get following message, and the table is not dropped:

NOTICE:  drop cascades to default for table t1 column f1 

I'm definitely doing something wrong but these are my very first steps in PostgreSQL.

like image 749
Chris Koston Avatar asked Apr 03 '12 21:04

Chris Koston


People also ask

What is drop sequence?

Description. DROP SEQUENCE removes sequence number generators. A sequence can only be dropped by its owner or a superuser.

What is drop cascade?

The default drop option is CASCADE, which means that dropping a unique/primary key with foreign key references drops all the referencing foreign keys together with the unique/primary key.

How do you use drop cascade?

DROP TABLE department CASCADE; If a table is referenced by a view or a foreign key constraint, then use the CASCADE parameter to remove the dependent objects such as views, procedures, but in the case of the foreign key, it will just remove a foreign key constraint from a child table, not the child table itself.

Does drop table drop sequence?

With the way you've specified this, dropping the table will not drop the sequence, although you can make the sequence depend on the column with which it is used, and therefore have it drop automatically if you drop the table.


2 Answers

You have a misconception about dependencies. The table never is a depending object of an associated sequence and is never dropped by a

DROP SEQUENCE ... CASCADE; 

Only a DEFAULT value drawing from the sequence "depends" on the sequence and is set to NULL if the sequence is deleted with CASCADE.

It is the other way round: if the sequence is owned by a table column it is dropped with a

DROP TABLE f1 CASCADE; 

For a sequence to be owned by a table column you can either use the serial type as Milen already suggested. Or you can ALTER an existing sequence:

ALTER SEQUENCE seq1 OWNED BY t1.f1; 
like image 127
Erwin Brandstetter Avatar answered Oct 14 '22 18:10

Erwin Brandstetter


I don't know why are you creating a sequence manually - maybe you have justification, or maybe it's due to habits working with another DBMS.

But if you don't have a special need for it, use the SERIAL pseudo-type and when you drop the table the sequence(s) behind the SERIAL column(s) will be dropped too.

like image 40
Milen A. Radev Avatar answered Oct 14 '22 18:10

Milen A. Radev