tags:

views:

132

answers:

2

Consider the need to query for a certain pattern of data within a column. The example I'll use are customers with Canadian postal codes.

ID       Postal
--       -------
442      90210  
631      T0R 4C2
447      YO31 1EB
145      F9S8S6
73       K9J 3K3

Pretend you don't have an easy out (like a state/prov or country field), or that you're running a non-conformance report. Yes, don't trust user input!

-- we want to find: three chars + space + 3 chars 'XXX XXX'
-- LIKE % is not terribly helpful
SELECT * FROM SomeTable 
WHERE  Postal LIKE  --?

We want the resultset to be

ID       Postal
--       -------
631      T0R 4C2
73       K9J 3K3

Question: how would you formulate that LIKE clause?

+2  A: 
SELECT * 
FORM SomeTable 
WHERE Postal LIKE '___ ___'

Or even better, when you want to specify exact numbers-letters, you can do this:

SELECT * 
FORM SomeTable 
WHERE Postal LIKE '[a-z][a-z][a-z] [0-9][0-9][0-9]'

It depends of the type of code you want to get.

Lukasz Lysik
+1 because you beat me to the first answer by 27 seconds, but my answer got lucky and got the check mark! :-)
Justin Grant
+3  A: 

Underscore matches one character only. Is this what you're looking for?

LIKE '___ ___'
Justin Grant