How to delete row in sql
How to delete row in sql
I make no qualms about how much I enjoy working with SQL both in my professional and personal projects.
Its straightforwardness and simplicity appeal to my desire to have well-defined boundaries in terms of what the language will and will not let me «get away with» regarding syntax.
SQL is structured with a clear and concise manner of operation in which the user’s input dictates the data returned. Hence my comment about having well-defined boundaries on syntax.
While I celebrate its resiliency (SQL was created in 1974 with an initial release of 1986) within the development community, I also know that when working with data it can feel like even the fundamentals are stressful and frightening.
I’m here to (hopefully) shed some light on one of those fundamentals of working with data: deleting an entire row of data.
Although we’re not going to go over the process for establishing a table in SQL or populating that table with data/updating that data, I’ve linked those other articles in case you’d like to learn more or just need a refresher.
SQL Delete Row Overview
Here is the table, aptly named Cute_Doggos, that we’ll be using as our example to start removing data from:
Name | Color | Breed | Age | Weight | Height | Fav_Food | Fav_Toy | Dislikes | Allergies |
daisy | red | standard dachshund | 1 yr | 14 | 6 | salmon flavored kibble | squeeky ball | birds flying over the yard | cats, baths, cleanliness |
winston | black/tan | rottweiler | 3 yrs | 41 | 17 | literally anything | rope tug | staying off the couch | listening, behaving, not slobbering on everything |
sammie | light honey | golden retriever | 9 yrs | 46 | 19 | beef flavored kibble | her bed | rambutcious puppies | none known |
penelope | gray and white | husky | 9 months | 16 | 12 | old shoes | outside | kennel | none known |
As you may have guessed, this is fictitious data from a table I’ve concocted out of thin air 🙂 However, I hope it illustrates the data well enough for our purposes.
As with most aspects of technical nature, it never hurts to check the official documentation as well. If you wish to do that, Microsoft has some great in-depth information on the SQL Delete statement.
DELETE FROM name_of_table
***With this syntax you will delete all rows of data within the entire table.***
So for our example table above, the query would look like the following:
DELETE FROM Cute_Doggos
That may be your intended purpose and the longer you write SQL the more cases you’ll find to use the delete statement in this capacity.
I have used this statement many times to clear a table after it was filled with test data. This approach allows us to keep the column names, data types, indexes, and overall table structure in tact without deleting the actual table.
As a side note, if your intended purpose is to delete all of the rows within a table, the faster approach would be to use the TRUNCATE TABLE statement as it uses far fewer system resources.
Example Delete Queries
The vast majority of the time when you use the delete functionality you’ll want to be a bit more targeted with your approach. For that, we’ll add a condition and the syntax will look like so:
DELETE FROM name_of_table WHERE conditions_exist
Using our table above of dogs, our query would look like this:
DELETE FROM Cute_Doggos WHERE dbo.Cute_Doggos.Height > 18
This would remove all entries from our table that match our condition of the Height being greater than 18. And if you’re using Microsoft SQL Server Manager, you’ll get a return statement like so:
If you’d like to see the rows of data that were deleted (for logging purposes, visual indications to users, and so on), we can use the OUTPUT statement to do just that.
Our table would now look like this:
Name | Color | Breed | Age | Weight | Height | Fav_Food | Fav_Toy | Dislikes | Allergies |
daisy | red | standard dachshund | 1 yr | 14 | 6 | salmon flavored kibble | squeeky ball | birds flying over the yard | cats, baths, cleanliness |
winston | black/tan | rottweiler | 3 yrs | 41 | 17 | literally anything | rope tug | staying off the couch | listening, behaving, not slobbering on everything |
penelope | gray and white | husky | 9 months | 16 | 12 | old shoes | outside | kennel | none known |
The condition we set is wholly our choice, and if that’s too narrow for your needs there are other options.
Let’s say you don’t care about the specific records you remove, only that you need to remove a certain number of records in the table.
DELETE TOP 2 FROM Cute_Doggos
You might be thinking that this query would remove the very first two records in your table – and you’re not too far off. The only problem is because SQL stores records in a random order, this syntax will remove 2 RANDOM records from the table.
If you’re looking to remove a percentage of the records, SQL can do that as well:
DELETE TOP 25 PERCENT FROM Cute_Doggos
Again, this query will delete RANDOM records. In our example, since we have 4 records, this query would delete 1 random record (4 * 0.25 = 1).
As a final side note, when using the TOP keyword, we cannot use an ORDER BY clause because of the randomness of record storage.
Wrapping up
Now that you’ve seen the DELETE statement in action, you’re ready to go out into the wild and cull all of the data from all of the tables! Maybe don’t do this as it will make for a long weekend of restoring off of backups 🙂
At any rate, now you’re ready to start putting it to good use.
If you found this article helpful check out my blog (I’m currently rebuilding it in Gatsby/WordPress so stay tuned for an article about that) where I frequently post articles about web development, life, and learning.
While you’re there why not sign up for my newsletter? You can do that at the top right of the main blog page. I like to send out interesting articles (mine and others), resources, and tools for developers every now and then.
If you have questions about this article or just in general let me know – come say hi on Twitter or any of my other social media accounts which you can find below the newsletter sign up on the main page of my blog or on my profile here at freeCodeCamp 🙂
Have an awesome day! Happy learning and happy coding, friend.
Self guided, community taught developer looking to share knowledge, experience, and cute animal pictures with the world! Check out my blog at https://jonathansexton.me/blog
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
How to Delete a Row in SQL – Example Query
In SQL, you can delete a row in a table by using the DELETE query and the WHERE clause.
In the article, I will walk you through how to use the DELETE query and WHERE clause to delete rows. I will also show you how to delete multiple rows from a table at once.
How to use the DELETE query in SQL
This is the basic syntax for using the the DELETE query:
We want to delete the row with the id of 8 which is Loki’s row.
The first line of the DELETE query would look like this:
In the second line, we are going to specify which row by using the id=8 after the WHERE clause.
Here is the complete syntax to delete Loki’s row:
This is what the new cats table looks like:
We can see that our DELETE query worked because Loki’s information is no longer there.
How to Delete multiple rows from a table in SQL
If we wanted to delete the rows with just the male cats, then we can use the gender=»M» condition.
Our new cats table would look like this:
Now the cats table is only showing the female cats.
How to delete multiple rows using the BETWEEN operator with the AND operator in SQL
If we wanted to delete a number of rows within a range, we can use the AND operator with the BETWEEN operator.
In this example, we want to delete rows with id s of 4-7 inclusive.
Here is the syntax for that:
This is the result from that DELETE query:
We can see that rows 1-3 and 8-10 are left in our table. The id s of 4-7 have been successfully deleted.
How to delete multiple rows using the IN operator in SQL
We can specify which names to delete from the cats table using the IN operator.
In this example, I want to delete the names of Lucy, Stella, Max and Tiger from our original cats table here:
We need to specify the column and use the IN operator to list the names we want deleted.
This is what the new result would look like:
Our DELETE query was successful, because those four cats are no longer present in the table.
How to delete all records in the table in SQL
If you want to delete all of the information from your table, then you would use this syntax:
In order to delete all of the cats from our cats table, then we would use this code.
Conclusion
In this article, we learned about the different ways to delete information from a SQL table.
This is the basic syntax for using the DELETE query:
If you want to delete one row from the table, then you have to specify a condition.
There are a few ways to delete multiple rows in a table.
If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator.
Another way to delete multiple rows is to use the IN operator.
If you want to delete all records from the table then you can use this syntax.
I hope you enjoyed this article and best of luck on your SQL journey.
SQL DELETE Statement
The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!
Demo Database
Below is a selection from the «Customers» table in the Northwind sample database:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
SQL DELETE Example
The following SQL statement deletes the customer «Alfreds Futterkiste» from the «Customers» table:
Example
The «Customers» table will now look like this:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la ConstituciГіn 2222 | MГ©xico D.F. | 05021 | Mexico |
3 | Antonio Moreno TaquerГa | Antonio Moreno | Mataderos 2312 | MГ©xico D.F. | 05023 | Mexico |
4 |
Delete All Records
It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
The following SQL statement deletes all rows in the «Customers» table, without deleting the table:
How to delete row in sql
DELETE is a DML statement that removes rows from a table.
Single-Table Syntax
The DELETE statement deletes rows from tbl_name and returns the number of deleted rows. To check the number of deleted rows, call the ROW_COUNT() function described in Section 12.16, “Information Functions”.
Main Clauses
The conditions in the optional WHERE clause identify which rows to delete. With no WHERE clause, all rows are deleted.
where_condition is an expression that evaluates to true for each row to be deleted. It is specified as described in Section 13.2.10, “SELECT Statement”.
If the ORDER BY clause is specified, the rows are deleted in the order that is specified. The LIMIT clause places a limit on the number of rows that can be deleted. These clauses apply to single-table deletes, but not multi-table deletes.
Multiple-Table Syntax
Privileges
You need the DELETE privilege on a table to delete rows from it. You need only the SELECT privilege for any columns that are only read, such as those named in the WHERE clause.
Performance
The speed of delete operations may also be affected by factors discussed in Section 8.2.5.3, “Optimizing DELETE Statements”.
To ensure that a given DELETE statement does not take too much time, the MySQL-specific LIMIT row_count clause for DELETE specifies the maximum number of rows to be deleted. If the number of rows to delete is larger than the limit, repeat the DELETE statement until the number of affected rows is less than the LIMIT value.
Subqueries
You cannot delete from a table and select from the same table in a subquery.
Partitioned Table Support
The PARTITION clause can also be used in multiple-table DELETE statements. You can use up to one such option per table named in the FROM option.
For more information and examples, see Section 24.5, “Partition Selection”.
Auto-Increment Columns
For MyISAM tables, you can specify an AUTO_INCREMENT secondary column in a multiple-column key. In this case, reuse of values deleted from the top of the sequence occurs even for MyISAM tables. See Section 3.6.9, “Using AUTO_INCREMENT”.
Modifiers
The DELETE statement supports the following modifiers:
For MyISAM tables, if you use the QUICK modifier, the storage engine does not merge index leaves during delete, which may speed up some kinds of delete operations.
The IGNORE modifier causes MySQL to ignore ignorable errors during the process of deleting rows. (Errors encountered during the parsing stage are processed in the usual manner.) Errors that are ignored due to the use of IGNORE are returned as warnings. For more information, see The Effect of IGNORE on Statement Execution.
Order of Deletion
ORDER BY also helps to delete rows in an order required to avoid referential integrity violations.
InnoDB Tables
If you are deleting many rows from a large table, you may exceed the lock table size for an InnoDB table. To avoid this problem, or simply to minimize the time that the table remains locked, the following strategy (which does not use DELETE at all) might be helpful:
Select the rows not to be deleted into an empty table that has the same structure as the original table:
Use RENAME TABLE to atomically move the original table out of the way and rename the copy to the original name:
Drop the original table:
No other sessions can access the tables involved while RENAME TABLE executes, so the rename operation is not subject to concurrency problems. See Section 13.1.36, “RENAME TABLE Statement”.
MyISAM Tables
The QUICK modifier affects whether index leaves are merged for delete operations. DELETE QUICK is most useful for applications where index values for deleted rows are replaced by similar index values from rows inserted later. In this case, the holes left by deleted values are reused.
DELETE QUICK is not useful when deleted values lead to underfilled index blocks spanning a range of index values for which new inserts occur again. In this case, use of QUICK can lead to wasted space in the index that remains unreclaimed. Here is an example of such a scenario:
Create a table that contains an indexed AUTO_INCREMENT column.
Insert many rows into the table. Each insert results in an index value that is added to the high end of the index.
Multi-Table Deletes
For the first multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted. For the second multiple-table syntax, only matching rows from the tables listed in the FROM clause (before the USING clause) are deleted. The effect is that you can delete rows from many tables at the same time and have additional tables that are used only for searching:
If you use a multiple-table DELETE statement involving InnoDB tables for which there are foreign key constraints, the MySQL optimizer might process tables in an order that differs from that of their parent/child relationship. In this case, the statement fails and rolls back. Instead, you should delete from a single table and rely on the ON DELETE capabilities that InnoDB provides to cause the other tables to be modified accordingly.
If you declare an alias for a table, you must use the alias when referring to the table:
Table aliases in a multiple-table DELETE should be declared only in the table_references part of the statement. Elsewhere, alias references are permitted but not alias declarations.
Table aliases are also supported for single-table DELETE statements beginning with MySQL 8.0.16. (Bug #89410,Bug #27455809)
SQL DELETE ROW
By Priya Pedamkar
Introduction to SQL DELETE ROW
DELETE statement in standard query language (SQL) is used to remove one or more rows from the database table. It is a Data Manipulation Language(DML) statement. That means it does not delete data records permanently. We can always perform a rollback operation to undo a DELETE transaction. With DELETE statements we can use WHERE clause for filtering specific rows. There are a few other statements like DROP and TRUNCATE table in SQL which are also used to remove data from the database.
Syntax
Let us now discuss the syntax and parameters used for deleting rows in SQL:
Hadoop, Data Science, Statistics & others
DELETE FROM table_name WHERE condition;
Parameters
The parameters used in this syntax are as follows :
Table_name: This is the name of the table from which you want to delete one or more rows.
Condition: It is a conditional expression used in the WHERE clause to filter one or more rows for removal.
Differences between DELETE TABLE, TRUNCATE TABLE statement and DROP TABLE statements
let us see differences:
DELETE TABLE | TRUNCATE TABLE | DROP TABLE |
DELETE statement that removes one or more data rows from the table. | The SQL statement that removes all the data rows from the table. | The SQL statement that removes all the records in the table and also destroys the table at the same time. |
It is a Data Manipulation Language(DML) statement. | It is a Data Definition Language(DDL) statement. | It is a Data Definition Language(DDL) statement. |
Since it’s a DML command, we can use a WHERE clause. | We cannot use a WHERE clause. | We cannot use a WHERE clause. |
We can perform a rollback operation to undo a DELETE table statement. | We cannot perform a rollback operation to undo a TRUNCATE table statement. | We cannot perform a rollback operation to undo a DROP table statement. |
Table rows are not deleted permanently. | Table rows are deleted permanently. | Table and all its relationships, index, privileges, etc are deleted permanently. |
Examples to Implement SQL DELETE ROW
Having discussed the syntax and parameters used in the DELETE statement, let’s go ahead and try some examples to understand the concept in great detail.
In order to understand the fore come thing examples, consider the following dummy table called “daily_sales”. This table contains details such as products sold, a salesperson who sold it, date of sale, amount, etc. pertaining to daily sales in a departmental store. For illustration purposes, look at the image below.
Code:
SELECT * FROM public.daily_sales
Output:
Example #1
Suppose departmental store’s Delhi (DL) store has been closed permanently and we have to remove all the records pertaining to it from our daily sales table.
Code:
DELETE FROM daily_sales
WHERE store_state = ‘DL’;
Output:
Explanation: In order to remove details of the Delhi store, we have used a WHERE clause in our DELETE statement to filter rows where store_state is DL. As we can see in the image above, the SQL query we just wrote has successfully removed all rows where store_state is DL.
For the curious ones who are wondering if we have deleted the correct rows or not, we can check it using a simple SELECT statement.