Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple rows in a PostgreSQL database based on string id?

So I have the following table:

qliu=# select id from api_member;
 id  
-----
 242
 236
 246
 251
 253
 9
 21
 185
 49
 188

I want to be able to delete rows with a range of ids with something like the following command:

delete from api_member where id between '0' and '10';

But it deletes nothing. Also if you were wondering

delete from api_member where id between 0 and 10;

I get the following error:

ERROR:  operator does not exist: character varying >= integer
LINE 1: delete from api_member where id between 0 and 10;
                                        ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
like image 557
Wang-Zhao-Liu Q Avatar asked Jan 11 '23 03:01

Wang-Zhao-Liu Q


1 Answers

This is because your column's id is of type varchar, not an integer. You can solve this by casting it to integer, like this:

delete from api_member
where CAST(id as integer) between 0 and 10;

If the number of rows is large, this operation may be too slow. Consider changing the type of the id column to a numeric type.

like image 179
Sergey Kalinichenko Avatar answered Jan 17 '23 08:01

Sergey Kalinichenko