Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL LIKE condition to check for integer?

Tags:

sql

postgresql

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.

like image 449
Wayne Koorts Avatar asked Nov 05 '09 23:11

Wayne Koorts


People also ask

Can we use like for integer in SQL?

LIKE is a string operator and has nothing to do with integers. You can kludge this sort of stuff by casting your integers as strings.

How do you check if a number is an integer in SQL?

Syntax to check if the value is an integer. select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$'; The query wherein we have used regular expression. This will output only the integer value.

How use like operator for numbers in SQL?

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator. The percent sign represents zero, one or multiple characters. The underscore represents a single number or character.

What is Ilike SQL?

The keyword ILIKE can be used instead of LIKE to make the match case insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension. The operator ~~ is equivalent to LIKE , and ~~* corresponds to ILIKE .


1 Answers

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; 
like image 171
Johannes Weiss Avatar answered Sep 22 '22 17:09

Johannes Weiss