Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

meaning of %%% in sql query?

Tags:

sql

I am familiar with this kind of query:

select * from tableA where foo like '%bar%'

But today I run into three adjacent percentage signs in some legacy code, like this:

select * from tableA where foo like '%%%'

This query seems to work, both on mssql and oracle, when foo is of string type (varchar, etc.) but it fails when foo is numeric.

Any idea what it means?

EDIT: sorry about the typo in original question, the query uses the LIKE operator.

like image 841
Yoni Avatar asked Feb 28 '23 17:02

Yoni


2 Answers

Turns out in mysql it matches everthing:

mysql> create database foo;
Query OK, 1 row affected (0.06 sec)

mysql> use foo;
Database changed

mysql> create table foo ( bar char(20) );
Query OK, 0 rows affected (0.06 sec)

mysql> desc foo;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| bar   | char(20) | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> insert into foo values ('endwith%');
Query OK, 1 row affected (0.05 sec)

mysql> insert into foo values ('%startwith');
Query OK, 1 row affected (0.00 sec)

mysql> insert into foo values ('cont%ins');
Query OK, 1 row affected (0.00 sec)

mysql> insert into foo values ('doesnotcontain');
Query OK, 1 row affected (0.00 sec)

mysql> select * from foo where bar like '%%%';
+----------------+
| bar            |
+----------------+
| endwith%       |
| %startwith     |
| cont%ins       |
| doesnotcontain |
+----------------+
4 rows in set (0.00 sec)
like image 181
Robert Gowland Avatar answered Mar 07 '23 21:03

Robert Gowland


If you're trying to find any value with a percent in it you need to use ESCAPE:

e.g.

SELECT * 
FROM SomeTable
WHERE foo LIKE '%|%%' ESCAPE '|'

If foo is numeric (in datatype), then you will get an error if you try to compare a numeric value in the column with a string.

like image 26
AdaTheDev Avatar answered Mar 07 '23 20:03

AdaTheDev