简体   繁体   中英

How can I delete a set of records from sql table

I have a table with the name column containing values like 'arthur_01', 'arthur_02', 'arthur_03'...'arthur_10' and many other values.

Is there a way to delete all the 'arthur_0x' in one query? I know that the BETWEEN operator takes a range, but is there a way for it to take in a range where half the string is numeric?

You need the LIKE operator: http://www.w3schools.com/sql/sql_like.asp

DELETE FROM table WHERE column LIKE 'arthur_0%';

This solution makes somse assumptions about what data is beyond 'arthur_0.....'. Otherwise you may need RDBS specific functions.

There are different approaches to this and unfortunately most of them are vendor specific.

One approach is to extract the character of interest and compare to target value

DELETE FROM table1
 WHERE SUBSTRING(column_name, 9, 1) = x;

or for a range of values

DELETE FROM table1
 WHERE SUBSTRING(column_name, 9, 1) BETWEEN x AND y

Here is SQLFiddle demo (MySQL)
Here is SQLFiddle demo (SQL Server)

Note: the drawback of this approach is that the optimizer won't be able to use any indices you might have on this column.


Another approach is to leverage pattern matching, but it's not implemented the same way in different RDBMSes.

In SQL Server for example you can do

DELETE FROM table1
 WHERE column_name LIKE 'arthur_0[345]%';

Which will effectively delete any rows with values in column_name that start with arthur_03 or arthur_04 or arthur_05 .

Here is SQLFiddle demo

Same thing in MySQL might look like

DELETE FROM table1
 WHERE column_name RLIKE '^arthur_0[345]';

Here is SQLFiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM