Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql delete all rows (where col != this or col != that or col != otherthing)

Tags:

mysql

I am having trouble writing a query. Lets say I have a table full car makes and models, but I want to get rid of all of rows that are not associated with a list of models, I have written this...

DELETE FROM `cars` WHERE 
`make` != 'Ford' OR
`make` != 'Toyota' OR
`make` != 'Cadillac'

However it is removing all of the rows. How do I write this so that I keep Ford, Toyota and Cadiillac, but delete Pontiac, Datsun and Renault?

Thank you for your help on this!

like image 763
superUntitled Avatar asked Apr 01 '11 19:04

superUntitled


People also ask

How do I delete a specific row in MySQL?

To delete rows in a MySQL table, use the DELETE FROM statement: DELETE FROM products WHERE product_id=1; The WHERE clause is optional, but you'll usually want it, unless you really want to delete every row from the table.

How do I delete multiple rows in MySQL workbench?

Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.

How do I delete all records in MySQL workbench?

Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) . BTW you can use TRUNCATE TABLE tablename; to delete all the records .


2 Answers

Easier to read:

DELETE FROM `cars` WHERE `make` NOT IN ('Ford', 'Toyota', 'Cadillac')
like image 151
Thiago Belem Avatar answered Oct 09 '22 17:10

Thiago Belem


DELETE FROM cars
WHERE make <> 'Ford'
AND make <> 'Toyota'
AND make <> 'Cadillac'

Your query was removing all rows because:

  1. You were first removing all rows that were not Ford (leaves only Ford)
  2. You were then removing all rows that were not Toyota (leaves nothing)
like image 4
Joe Phillips Avatar answered Oct 09 '22 17:10

Joe Phillips