in sql, how do you delete on a table thats joined on another table?
- User
in sql, how do you delete on a table thats joined on another table?
- Assistant
In SQL, you can use the DELETE statement with a JOIN to delete from a table based on the joined condition with another table. Here's an example:
Let's assume we have two tables:
ordersandcustomers. We want to delete all orders related to a customer who has the first name 'John'. The tables are related through the customer_id field.DELETE o FROM orders o JOIN customers c ON o.customer_id = c.customer_id WHERE c.first_name = 'John';In this example, we are deleting rows from the
orderstable (using aliaso) where thecustomer_idmatches in bothordersandcustomerstables, and thefirst_namein thecustomerstable is 'John'. - User
can also just do "DELETE orders" instead of "DELETE o"?
- Assistant
Yes, you can use the table name directly instead of the alias:
DELETE orders FROM orders JOIN customers ON orders.customer_id = customers.customer_id WHERE customers.first_name = 'John';This query would produce the same result as the previous one. The
DELETE orderswill delete rows from theorderstable based on the join condition and the specified condition in theWHEREclause.