Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot drop table users because other objects depend on it

Tags:

sql

postgresql

I want to drop my tables in my database. But, when I use, for example, DROP TABLE if exists users; I receive this message:

cannot drop table users because other objects depend on it

I found the solution is to drop all tables. But, anyway, how to solve this problem without total data removal?

like image 790
Vyacheslav Avatar asked Feb 11 '16 11:02

Vyacheslav


People also ask

Can we drop a table that has dependent view on it?

However, to drop a table that is referenced by a view or a foreign-key constraint of another table, CASCADE must be specified. ( CASCADE will remove a dependent view entirely, but in the foreign-key case it will only remove the foreign-key constraint, not the other table entirely.)

What is the keyword needed to drop a table when there are other tables relying on it?

Use the cascade option: DROP TABLE if exists users cascade; this will drop any foreign key that is referencing the users table or any view using it.

Does dropping table drop primary key?

If a primary key exists, it is dropped. The user need not drop the primary key before dropping the table. If the primary key of the table is referenced by a constraint belonging to another table, then the table is not dropped and an error is signaled.

Does dropping table automatically drop index?

Note: If a table is dropped, all associated indexes are dropped automatically.


2 Answers

Use the cascade option:

DROP TABLE if exists users cascade; 

this will drop any foreign key that is referencing the users table or any view using it.

It will not drop other tables (or delete rows from them).

like image 92
a_horse_with_no_name Avatar answered Sep 21 '22 06:09

a_horse_with_no_name


If it was really necessary to drop that specific table with or without recreating it, then first find the object(s) that depends on it.

CREATE OR REPLACE VIEW admin.v_view_dependency AS  SELECT DISTINCT srcobj.oid AS src_oid   , srcnsp.nspname AS src_schemaname   , srcobj.relname AS src_objectname   , tgtobj.oid AS dependent_viewoid   , tgtnsp.nspname AS dependant_schemaname   , tgtobj.relname AS dependant_objectname FROM pg_class srcobj   JOIN pg_depend srcdep ON srcobj.oid = srcdep.refobjid   JOIN pg_depend tgtdep ON srcdep.objid = tgtdep.objid   JOIN pg_class tgtobj ON tgtdep.refobjid = tgtobj.oid AND srcobj.oid <> tgtobj.oid   LEFT JOIN pg_namespace srcnsp ON srcobj.relnamespace = srcnsp.oid   LEFT JOIN pg_namespace tgtnsp ON tgtobj.relnamespace = tgtnsp.oid WHERE tgtdep.deptype = 'i'::"char" AND tgtobj.relkind = 'v'::"char"; 

Then,

select top 99 * from admin.v_view_dependency where src_objectname like '%the_table_name_it_complaint_about%'; 

The result set will show you the dependant object in the field "dependant_objectname".

like image 24
dat789 Avatar answered Sep 19 '22 06:09

dat789