
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete Specific Rows in a Table with MySQL
To delete only specific rows, use MySQL NOT IN(). Let us first create a table −
mysql> create table DemoTable1830 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) )AUTO_INCREMENT=101; Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1830(StudentName) values('Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('David'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('Mike'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('Sam'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('Bob'); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1830;
This will produce the following output −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 102 | David | | 103 | Mike | | 104 | Sam | | 105 | Bob | +-----------+-------------+ 5 rows in set (0.00 sec)
Here is the query to delete only specific rows −
mysql> delete from DemoTable1830 where StudentId NOT IN('101','103','105'); Query OK, 2 rows affected (0.00 sec)
Let us check the table records once again:
mysql> select * from DemoTable1830;
This will produce the following output −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 103 | Mike | | 105 | Bob | +-----------+-------------+ 3 rows in set (0.00 sec)
Advertisements