Delete rows from multiple tables in a database - sql

I want to delete some records from a table based on criteria in another table. How do you delete from one of those tables without removing the records in both table?
I am looking to delete a table which are joined with other tables and the query looks something like this.
DELETE DeletingFromTable
FROM DeletingFromTable
INNER JOIN CriteriaTable ON DeletingFromTable.field_id = CriteriaTable.id
WHERE CriteriaTable.criteria = "value" ;

This should work:
DELETE DeleteFromTable FROM DeleteFromTable AS DT
JOIN CriteriaFromTable AS CT ON DT.SomeId = CT.SomeId
WHERE CT.SomeId=[value]

Your question is not 100% clear on what your issue is, but this query will drop tables 1,2 and 3 at the same time:
DROP TABLE table1,table2,table3

You can only delete data from one table at a time.
To delete from multiple table
Write multiple queries separated by semicolon and execute it at onces like
delete from table1;
delete from table2;
delete from table3;
Or you can write the procedure to do this task.
Please check this thread as well
Drop multiple tables in one shot in mysql

You can use:
DELETE FROM TableName
Which will remove all the data, but if you have any seeded columns, these will not be reset. If you want to DELETE data and reset the seeding of PK's, then use TRUNCATE...
TRUNCATE TABLE TableName
But, you need to consider whether you have other tables that have referential integrity, if this is the case, see this post here SQL Server: How to ignore referential integrity until COMMIT?
EDIT:
Your comment above...
delete query like this DELETE FROM table_name WHERE
some_column=some_value;
...suggests you are looking to delete specific rows?

You can just write a query to DROP the tables like so:
DROP TABLE [TABLE_1]
DROP TABLE [TABLE_2]
DROP TABLE [TABLE_3]
Depending on the tables and any constraints you may have between them, you will need to DROP the tables in the correct order.
If you right click any table (depending on SQL version), you should be able to 'View Dependencies'. If the 3 tables you are planning to DROP are only dependant on each other, you need to DROP the tables with no child dependencies first to avoid it failing.
For example, if you try to delete a parent table where it's primary key is referenced in a child table as a foreign key, the DROP will fail because of this. So deleting the child table with the foreign key first will allow you to subsequently DROP the parent table.
If however, the tables have other dependencies outside the tables you are deleting, you will need to remove the dependencies before this will work.

Related

Delete multiple rows of data from multiple tables in SQL

I need help of making a SQL query, when I delete the main category it should delete all the data of my subcategory and all the products related to that subcategory. Basically deleting data from 3 tables.
Can it be done in one query?
Cant give you code sample without a Database reference. But if all the tables have the same Primary key you can try using INNER JOIN.
DELETE table1, table2, table3
FROM table1
INNER JOIN table2 ON table2.key = table1.key
INNER JOIN table3 ON table3.key = table1.key
WHERE table1.key = value;
key value should be common accross all tables. Something like a "ID".
Instead of solving it via Sql, you could use foreign keys with the ON DELETE CASCADE setting enabled.
If you database type/version supports it.
F.e. ANSI SQL:2003, MySSQL, Oracle, PostgreSQL, MS SQL Server, SQLite
That way, when you delete from the main table. Then the records in the other table that reference to those deleted records, will automatically be deleted also.
For example in MS Sql Server:
ALTER TABLE SubCategory
ADD CONSTRAINT FK_SubCategory_MainCategoryID_Cascade
FOREIGN KEY (MainCategoryID)
REFERENCES MainCategory(ID) ON DELETE CASCADE;
ALTER TABLE Products
ADD CONSTRAINT FK_Products_SubCategoryID_Cascade
FOREIGN KEY (SubCategoryID)
REFERENCES SubCategory(ID) ON DELETE CASCADE;
It's a way to automatically maintain the referential integrity between them.
After that a delete from the MainCategory table will delete the related records from the SubCategory table. And also the Products that are related to the deleted SubCategory records.
And here is a db<>fiddle example for SQLite to demonstrate.
P.S. Personally I would prefere an ON DELETE SET NULL or an ON DELETE SET DEFAULT n, or even using triggers. Sure, that would require an extra cleanup of the unreferenced records afterwards, f.e. via a scheduled script. But it just feels less detrimental. Because then it's easier to fix when someone accidently deleted a MainCategory that shouldn't have been deleted.

Deleting rows from multiple tables

I created a query that will delete rows from three tables that has 'Employee'.
When I execute it, it only deletes rows from one table tblEmployeeType. I tried adding Alias of other tables beside DELETE but SQL does not support it. Is there any alternative way of deleting rows from multiple tables? or I forgot some codes on my query or should I just separate delete queries? Thank you.
DELETE a
FROM tblEmployeeType a INNER JOIN
tbl_Selected_AccessType b
ON a.EmpTypeName = b.UserType INNER JOIN
tbl_AccessType_AllFunction c
ON a.EmpTypeName = c.UserType
WHERE a.EmpTypeName = 'Employee'`
INSERT and UPDATE statements can only directly affect one table at a time. If you have foreign keys configured with ON DELETE CASCADE then child records will be deleted along with the parent record. Regardless of using cascade, you should have foreign keys on the table so that your DELETE doesn't leave orphaned child records with broken referential integrity.
Another way to achieve affecting other tables in an INSERT or UPDATE is by using a trigger on the table. This can be desirable when you want to do checks before blindly deleting child records.

Deleting a Row in Table- Best way to also delete all rows it affects?

I have created a very simple SQL script (see below) that deletes rows in my table if a column name is a certain value.
DELETE FROM table_name
WHERE some_column=some_value;
However, this table also enters data to other tables in my Database: For example it's ID (Primary Key).
How can I also delete the rows in the other tables?
I would recommend a stored procedure in the database to do your delete. Not only can you do the delete in the proper constraint order but you have the added benefit of not having to grant delete permission on the table - only execute permission on the proc.
Like said #Gordon,
Add a foreign key to your table_name and ask for cascade_on_delete
or
DELETE table1, table2 FROM table1 INNER JOIN table2 ON table1.column=table2.column AND table1.column = someValue
...Not sure about the correct synthax but that will work.

sql server linked tables

suppose I have three tables (table1, table2, table3) linked to a master table tableM.
I have primary key ID in the tableM and foreign key ID in other tables.
suppose I insert a row in tableM, will other tables get inserted a row automatically? Or do I have to write a sp by my own?
Thanks for any advice!
Rows do not get inserted automatically. You have to insert a row into your master table first, and then insert rows into your FK tables afterwards to avoid a FK constraint error.
No, rows are not inserted automatically. Additionally, the INSERT statement could not possibly include columns from these child tables, so even if a row were inserted automatically it could not include data.
You will need to either write a stored procedure (recommended if these child rows are required by the business logic) or simply insert into tables as necessary.

Oracle delete query taking long time to delete the records from the table

Query:
Delete from test_table; (i am using this delete command in Procedure to perform daily)
This table contains 2 column name like scenario_id, item_id, these 2 column are composite primary key. So Each scenario_id will have 2 millions item_id, How to delete this table quicky.
The fastest way to delete the table might be DROP TABLE test_table command, and recreate the table using CREATE TABLE... command. DROP TABLE... will drop the table immediately. Well, actually it will move the table into recyclebin. You should PURGE RECYCLEBIN if want to completely remove the table.
Other way to delete the data in the table is to use TRUNCATE TABLE.... This is a little slower than DROP TABLE..., however, much faster than DELETE FROM.... Since there's no way to rollback the data after you truncate the table, you should be careful when you use TRUNCATE TABLE.
Check if there are any Foreign keys pointing onto this table. If they are, there MUST be indexes on these referring columns. Otherwise maintenance of the referential integrity will take ages
(Transactional) Delete on Oracle is slow by nature. Simple because of deleted data must be copied into UNDO tablespace, REDO logs and also archived REDO logs. This is the way how Oracle protects your data.
If our are deleting more than 50% of data, it is much faster when you simply create new table as select * from old_table where ... and then drop the new old one and rename new to old.
You can achieve similar goal by exchanging partitions in the partitioned table.
Or you can simply drop table's partitions if your table is partitioned wisely