Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting records from a table without primary key

Tags:

sql

oracle

I need to delete some specific record from database table but table itself does not have primary key. So condition depends on other table. So what is the correct way to do that?

  delete from table_1 
    where exists 
         (select distinct tb.* 
          from table_1 tb, table_2 tb_2, table_3 tb_3
          where tb1.col = tb2.col
          and tb3.col = tb2.col
          and tb3.col_2= 10)

is that correct way to do that? Lets say table_1 has 4 columns and first two columns should be the criteria to remove.

like image 467
user1474111 Avatar asked Oct 30 '22 03:10

user1474111


1 Answers

If the select version of your query returns the results you want to delete, then you're good. A couple things though..

Use the ANSI compliant explicit join syntax instead of the comma delineated, implicit syntax (which is long since depreciated). The explicit syntax looks better and is easier to read, anyway.

Correlate your EXISTS back to the main table. And you don't need a distinct, it will return positive whether there is 1 matching row or 10 billion.

SELECT *
FROM table_1 tb_1
WHERE EXISTS (SELECT *
              FROM table_2 tb_2
              JOIN table_3 tb_3 ON tb_2.col = tb_3.col
              WHERE tb_1.col = tb_2.col
              AND tb_3.col_2 = 10)
like image 60
Aaron Dietz Avatar answered Nov 15 '22 09:11

Aaron Dietz