Monday, October 28, 2013

What is Cascade and Restrict in DROP table SQL?

RESTRICT specifies that table should not be dropped if any dependencies (i.e. triggers, stored procedure, primary key, foreign key etc) exist. Therefore, if there are dependencies then error is generated and the object is not dropped.


CASCADE specifies that even if there dependencies go ahead with the drop. That means drop the dependencies first and then the main object. So if the table has stored procedures and keys (primary and secondary keys) they are dropped first and then the table is finally dropped.

The DROP statement for Postgres

DROP TABLE table_name [CASCADE | RESTRICT];

SQL DROP TABLE statements allow whole tables to be removed from a database. Both the table data and the table structure itself will be removed. DROP TABLE statements are simply composed of a table name.
DROP TABLE table_name;

The optional CASCADE or RESTRICT suffix defines what happens if the named table is used by other objects in the database. For example foreign key references or views may exist on the named table. If RESTRICT is specified then attempting to delete a table with such references will disallow execution of the statement. If CASCADE is specified, then execution will be allowed, but referencing objects will be dropped as well (tables, views, etc.).
DROP TABLE table_name CASCADE;

To drop a view:
DROP VIEW view_name;

SQL DROP VIEW statements allow views to be removed from a database. DROP VIEW statements are composed of a view name.
DROP VIEW view_name RESTRICT;

As with the DROP TABLE statement, DROP VIEW allows the optional CASCADE or RESTRICT keyword to be suffixed to the statement. The restrict example above would result in the statement not executing if other objects in the database referenced the view in question.

4 comments:

  1. How to update 0 to 1 and 1to 0 in a single linequery

    way-1:update [Table] set col1 = case when col1=0 then 1 when col1=1 then 0 end

    way- 2: UPDATE [Table] set col1 = 1-col1

    ReplyDelete
  2. Diff between New and Override keyword?

    The override modifier extends the base class method, and the new modifier hides it.

    ReplyDelete
  3. why use override and Virtual keyword?

    Many times you will have dependencies in sub-classes, or may have to implement things differently.

    ReplyDelete
  4. why use override and Virtual keyword?

    If the base class wants derived classes to be able to modify that particular behavior they make the method virtual. If they don't, they leave it sealed. It is up to them whether they want to allow it or not. As to why the feature exists, it's to support polymorphism.

    ReplyDelete