Delete-Queries
*What is Delete Query ?
The DELETE query is used to remove rows from a table. You specify which rows you want to delete using the WHERE clause. If you don’t use WHERE, you could accidentally delete all the rows in the table!

DELETE FROM table_name
WHERE condition;


  • table_name: The table from which you want to delete data.
  • WHERE: This is where you set the condition to specify which rows to delete. Always use this carefully!
*Delete a single row

Delete from CountryMaster_bkp06072025 where CountryId=1

Above query will delete the Country with id 1 from the CountryMaster_bkp06072025 table.

*Delete All Rows from a Table (Without Removing the Table)

DELETE FROM CountryMaster_bkp06072025;
If you want to delete every single row from a table (but keep the table structure intact), you can leave out the WHERE clause.

This will delete all the rows in the table. Be careful with this! If you accidentally run this on the wrong table, you could lose all the data.

*Using JOIN to Delete Data

In SQL Server, you can use a JOIN to delete records from one table based on data in another table.

Example:
If you want to delete employees from a department using a JOIN:

DELETE e
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE d.department_name = 'Marketing';


This will delete all employees in the Marketing department by using a JOIN between the employees and departments tables.

*Deleting Data and Handling References (Foreign Keys)

If you have foreign key constraints between tables (e.g., one table refers to data in another table), deleting rows can be tricky. If you try to delete a record that is referenced by another table, SQL will usually block the deletion.

Example:
If you try to delete a student who has records in the enrollments table, you might get an error. In these cases, you can either:

  • Delete from the child table first (if allowed):

DELETE FROM enrollments WHERE student_id = 1;

  • Use ON DELETE CASCADE: This automatically deletes related rows in child tables when a parent row is deleted (if configured in the database schema).