tags:

views:

331

answers:

4

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts with the letter "A":

SELECT * FROM books WHERE title ILIKE "A%"

That's fine for letters, but how do I list all items starting with any number? For what it's worth this is on a Postgres DB.

+4  A: 

That will select (by a regex) every book which has a title starting with a number, is that what you want?

SELECT * FROM books WHERE title ~ '^[0-9]'

if you want integers which start with specific digits, you could use:

SELECT * FROM books WHERE CAST(price AS TEXT) LIKE '123%'

or use (if all your numbers have the same number of digits (a constraint would be useful then))

SELECT * FROM books WHERE price BETWEEN 123000 AND 123999;
Johannes Weiß
Option 1 is what I wanted, thanks very much.
Wayne Koorts
+2  A: 

PostgreSQL supports regular expressions matching.

So, your example would look like

SELECT * FROM books WHERE title ~ '^\d+ ?'

This will match a title starting with one or more digits and an optional space

Vinko Vrsalovic
Great link, thanks.
Wayne Koorts
+1  A: 

Assuming that you're looking for "numbers that start with 7" rather than "strings that start with 7," maybe something like

select * from books where convert(char(32), book_id) like '7%'

Or whatever the Postgres equivalent of convert is.

Corey Porter
Nice tip for type conversion, thanks.
Wayne Koorts
A: 

Which one of those is indexable ?

This one is definitely btree-indexable :

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ascii.

peufeu