2

Is it possible to write an SQL statement which finds all rows which match a specific arrangement of letters/numbers?

i.e. SELECT myCol FROM myTable WHERE myCol='<letter><letter><number>'

Should return 12X and 34Y but not 123X or 34YY

I am using MySQL.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
Urbycoz
  • 7,247
  • 20
  • 70
  • 108
  • As a follow-on to this question, let's try without using REGEX: http://stackoverflow.com/questions/5064711/sql-match-on-letter-and-number-arrangement-without-using-regular-expressions – Urbycoz Feb 21 '11 at 10:53

4 Answers4

3

I haven't got MySQL on this machine to test but I think

SELECT myCol 
FROM myTable 
WHERE myCol REGEXP '^[0-9][0-9][A-Z]$'

Should do it. ^ is an anchor for start of string, $ for end of string and the rest should be self explanatory.

Looks like you could also use REGEXP '^[[:digit:]][[:digit:]][[:alpha:]]$' but completely untested and just going off the docs.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
1

For sql server, you can use with PATINDEX. For mysql, you have REGEXP.

EDIT : Damien_The_Unbeliever pointed out I was wrong and that PATINDEX does not support regular expressions. That's correct but after some googling I found that you can use regular expressions in sql server because it hosts CLR.

Sem Vanmeenen
  • 2,111
  • 11
  • 13
  • Describing the patterns you can pass to `PATINDEX` as regular expressions seems a little over-generous. Even it's own documentation only claims that you can pass wildcards. – Damien_The_Unbeliever Feb 18 '11 at 14:23
  • @Damien Correct. I edited the post. I didn't check on it because I was certain it supported regex. Shows again how wrong you can be. – Sem Vanmeenen Feb 18 '11 at 14:28
1

Many database management systems support regular expressions. So, in PostgreSQL 9.x for example, you can do this . . .

create table mytable (
  mycol varchar(10) primary key
);

insert into mytable values 
('12X'),
('34Y'),
('123X'),
('34YY');

And then

select * 
from mytable
where mycol ~ ('^[0-9][0-9][A-Z]$');
Mike Sherrill 'Cat Recall'
  • 91,602
  • 17
  • 122
  • 185
1

And Oracle's version.. here it is:

SELECT myCol
  FROM myTable
 WHERE REGEXP_LIKE(myCol, '^\d{2}[A-Z]$')
Chandu
  • 81,493
  • 19
  • 133
  • 134