How to Search Special Characters in Table Column? – Interview Question of the Week #172

Question: How to Search Special Characters in Table Column?

Answer: This is a very interesting question and lets us discuss the same today. However, before you try out the solution in this blog post, I would suggest you check with other members in your team and see if they know the answer of this question. The reason, I am asking is whenever I ask this question in the interview, I have so far seen 99% of people not knowing the solution.

How to Search Special Characters in Table Column? -  Interview Question of the Week #172 specialchars-800x305

Let us first create a small dataset.

CREATE TABLE TestTable (Col1 VARCHAR(100))
GO
INSERT INTO TestTable
VALUES ('[blog.]SQLAuthority.com')
GO
SELECT *
FROM TestTable
GO

Now you can see in the resulset there is a record with the words [blog.]SQLAuthority.com – what we need to do over here is to write a search condition on the column col1 to look for the column [blog.]. Remember the goal is to search for every row where there is [blog.] word. Let us see how we can do the same.

The natural instinct of many is usually to write the following T-SQL which does not work.

SELECT *
FROM TestTable
WHERE Col1 LIKE ‘%\[blog.]%’
GO

Well, now let us see the answer which works.

SELECT *
FROM TestTable
WHERE Col1 LIKE '%$[blog.]%' ESCAPE '$'
GO

If you run the above command it will return us all the row which contains [blog.] words. Even though I have asked many, I have yet to receive a good answer to this question. I think not many people know the keyword ESCAPE. You can replace $ with any other special character and write that into ESCAPE word and it script will search for the words right after the specified escape words.

For example instead of $ you can also use ! .

SELECT *
FROM TestTable
WHERE Col1 LIKE '%![blog.]%' ESCAPE '!'
GO

How to Search Special Characters in Table Column? -  Interview Question of the Week #172 specialchars1

Did you know the keyword ESCAPE before you read in this blog post?

Reference: Pinal Dave (https://blog.sqlauthority.com)

SQL Function, SQL Scripts, SQL Server
Previous Post
How to List All the SQL Server Jobs When Agent is Disabled? – Interview Question of the Week #171
Next Post
How to Find Last Full Backup Time and Size for Database? – Interview Question of the Week #173

Related Posts

7 Comments. Leave new

Leave a Reply