T-SQL: How to Search for % in String (% and LIKE)

In one of my web projects (ASP.NET and SQL Server) I have a screen with top 50 customers. To facilitate the client, I put few textboxes and give them the chance to filter the customers, until they reach the one that they need. In another case I use a textbox with auto complete to allow the client to add existing customer to a group. I needed to search for a group with “%” in its name. As you know in T-SQL, the LIKE operator uses % as a wildcard and when we search for %, the LIKE operator returns everything.

I was searching for an answer how to search for % and I couldn’t find one in 20 minutes. I decided that this is very simple and waisting 20 minutes is too much. That’s why I got a solution in 5 minutes.

Create and populate the test table


SELECT 'A toy with 10 % rebate' AS Column1
INTO #Table1
UNION ALL SELECT 'Street Address'
UNION ALL SELECT 'Customer with 14% abscense'
UNION ALL SELECT 'Another Unknown Address';

FROM #Table1;

The straight forward using of % doesn’t work and the query below returns all the rows in the table

DECLARE @Pattern NVARCHAR(128) = N'%'

FROM #Table1
WHERE Column1 LIKE N'%'

By replacing % with “\%” and add the left slash like escape character fixes the query
DECLARE @Pattern NVARCHAR(128) = N'%' -- '' --> All Values

FROM #Table1
WHERE Column1 LIKE N'%' + REPLACE(@Pattern, '%', '\%') + N'%' ESCAPE '\';

In my project, empty textbox means “no filter”, so the above solution is perfectly acceptable.

Warning: LIKE is an expensive operator. In this case I use it to filter “structure” or “dimension” table (Customer). If we need to filter a “data” or “fact” table, we would consider another approach.

Keep it simple :-)

About Peter Lalovsky

I am Microsoft SQL Server certified professional, creating with T-SQL, SSRS, SSIS, ASP.NET/C#, Azure, Python, PowerShell and more on a daily basis since year 2006. In 2016 i wrote a book for beginner and intermediate T-SQL programmers which you can download here. This blog is something like my personal programming documentation. When i am not in front of a computer, i am around my paper car – Trabant 601.

Leave a comment

Your email address will not be published.