Im trying to pull bunch of records from MySQL with condition whether the column value contains 0. If I convert to string and check with contains (%0%), it takes more time to execute.. Is there any short way to check on Integer column? Thank you..
2 Answers
You can probably run a regex on the integer column. Something like below.
SELECT fieldname FROM tablename WHERE fieldname REGEX '[0]';
About the performance, I believe that LIKE is faster than REGEX. But since your LIKE involves string conversion, this would have some difference in execution time
2 Comments
@SriniK You can use either POSITION() or LOCATE() in conjunction with CONVERT() to convert the column value into a string and then find if the string "0" exists within the string. Both of these functions return a positive number greater than 0 indicating the index of the substring within your string and they return a 0 if the string isn't found.
Here's how to create a simple test table to illustrate:
CREATE TABLE `testTable` (`id` INTEGER NOT NULL AUTO_INCREMENT, `someNum` INTEGER, PRIMARY KEY(`id`));
INSERT INTO `testTable` (`someNum`)
VALUES
(1),
(10),
(11),
(100),
(111),
(222),
(210);
And here are two queries illustrating both POSITION() and LOCATE():
SELECT `id`,
`someNum`,
POSITION('0' IN CONVERT(`someNum`, CHAR))
FROM `testTable`
WHERE POSITION('0' IN CONVERT(`someNum`, CHAR)) > 0
;
SELECT `id`,
`someNum`,
LOCATE('0', CONVERT(`someNum`, CHAR))
FROM `testTable`
WHERE LOCATE('0', CONVERT(`someNum`, CHAR)) > 0
;
I have mocked this up on dbfiddle here so you can get a better look at it.
If this doesn't get you what you need or if you don't understand something please leave a comment with details and I'll do what I can to help further. Good luck.
REGEXP '^[1-9]{6}$'.012345which will be stored as 12354 will matchNOT LIKE '%0%'check.