Tutorialspoint

1 Answer
Ankith Reddy

To delete all rows except a single specific row, try the below syntax −

delete from yourTableName where yourColumnName!=yourValue;

Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Subject varchar(100)
   );
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----+---------+
| Id | Subject |
+----+---------+
| 1  | MySQL   |
| 2  | MongoDB |
| 3  | Java    |
+----+---------+
3 rows in set (0.00 sec)

Here is the query to delete all rows except a single specific ow −

mysql> delete from DemoTable where Subject!='MongoDB';
Query OK, 2 rows affected (0.19 sec)

Let us check all records from the table once again −

mysql> select *from DemoTable;

Output

+----+---------+
| Id | Subject |
+----+---------+
| 2  | MongoDB |
+----+---------+
1 row in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.