Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting query sql with % as value character

Tags:

url

sql

php

mysql

Hello i'm having a table in a database like this:

╔══════════════════════════════════════════╗
║              v3_url_alias                ║
╠════╦═══════════════╦═════════════════════╣
║ id ║    query      ║       keyword       ║
╠════╬═══════════════╬═════════════════════╣
║  1 ║ product_id=20 ║   540-65R38-K_028   ║
║  2 ║ product_id=21 ║ 18.00R33-EM_DT-150% ║
╚════╩═══════════════╩═════════════════════╝

I'm using this table to make my urls friendly but as many know a % sign ain't a valid url character therefore making my browser getting a bad request. I have a lot of entries in this table (1700 or so) and need a query to grab all the ones with % in the column keyword.

So I've tried doing that in MySQL and came up with this query:

SELECT * FROM v3_url_alias WHERE keyword LIKE '%%%';

This was returning all of my keywords as % is used as a wildcard.

My question how to retrieve every keyword containing a % character with SQL?

like image 521
Baklap4 Avatar asked Oct 27 '15 11:10

Baklap4


2 Answers

Use an escape character!

MySQL has backslash (\) as default escape character:

SELECT * FROM v3_url_alias WHERE keyword LIKE '%\%%';

The ANSI SQL way is to use an ESCAPE clause to specify escape character, e.g.:

SELECT * FROM v3_url_alias WHERE keyword LIKE '%#%%' escape '#';

(This works with MySQL too, at least as long as \ isn't specified.)

like image 171
jarlh Avatar answered Sep 19 '22 01:09

jarlh


Use square brackets.

SELECT * 
FROM v3_url_alias 
WHERE keyword LIKE '%[%]%'
like image 35
Matt Avatar answered Sep 18 '22 01:09

Matt