PostgreSQL – How to Drop a Sequence

You can drop a sequence using the DROP SEQUENCE command. Here’s the basic syntax to drop a sequence:

DROP SEQUENCE [ IF EXISTS ] sequence_name [, ...] [ CASCADE | RESTRICT ];
  • sequence_name: This is the name of the sequence you want to drop.
  • IF EXISTS (optional): If you include this option, PostgreSQL will not raise an error if the specified sequence does not exist.
  • CASCADE (optional): If you include this option, PostgreSQL will automatically drop any dependent objects, such as columns with default values based on the sequence. Be cautious when using CASCADE, as it can remove objects you didn’t intend to delete.
  • RESTRICT (optional): This option prevents the sequence from being dropped if there are any dependent objects. It’s the default behavior if you don’t specify CASCADE.

Here are some examples of using the DROP SEQUENCE command:

Drop a sequence without checking for dependencies:

DROP SEQUENCE my_sequence;

Drop a sequence with IF EXISTS, so it doesn’t raise an error if the sequence doesn’t exist:

DROP SEQUENCE IF EXISTS my_sequence;

Drop a sequence and automatically remove dependent objects (be cautious with CASCADE):

DROP SEQUENCE my_sequence CASCADE;

Drop a sequence and prevent it from being deleted if there are dependent objects:

DROP SEQUENCE my_sequence RESTRICT;

Dropping a sequence is a irreversible action, and you should be careful, especially when using CASCADE, as it can lead to data loss.

Similar Posts