SQL LIKE condition for validating an integer?

I use a set of SQL LIKE conditions to go through the alphabet and a list of all elements starting with the corresponding letter, for example. to get all books where the name begins with the letter "A":

SELECT * FROM books WHERE title ILIKE "A%" 

This is good for letters, but how do I list all the elements, starting with any number? What is it worth in DB Postgres.

+41
sql postgresql
Nov 05 '09 at 23:06
source share
7 answers

What will choose (by regular expression) every book that has a title starting with a number, is that what you want?

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

If you want integers to start with specific digits, you can use:

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

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

 SELECT * FROM books WHERE price BETWEEN 123000 AND 123999; 
+89
Nov 05 '09 at 23:09
source share

PostgreSQL supports regular expressions matching .

So your example will look like

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

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

+12
Nov 05 '09 at 23:11
source share

Assuming you are looking for "numbers starting with 7" and not "lines starting with 7", maybe something like

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

Or regardless of the equivalent of Postgres conversion.

+1
Nov 05 '09 at 23:11
source share

Which index can I index?

This is definitely btree-indexable:

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

Note that ':' appears after "9" in ASCII.

0
Nov 07 '09 at 16:38
source share

In PostreSQL, you can use the SIMILAR TO operator ( more ):

 -- only digits select * from books where title similar to '^[0-9]*$'; -- start with digit select * from books where title similar to '^[0-9]%$'; 
0
Dec 16 '15 at 12:11
source share

If you want to search as a string, you can use the text as follows:

 SELECT * FROM books WHERE price::TEXT LIKE '123%' 
0
Nov 10 '16 at 21:55
source share

I'm late to the party here, but if you are dealing with integers of a fixed length, you can just do an integer comparison:

 SELECT * FROM books WHERE price > 89999 AND price < 90100; 
0
Nov 08 '17 at 21:53 on
source share



All Articles