views:

42

answers:

2

I have to create an SQL Query to get all rows starting with a specific character, except if the parameter passed to the (PHP) function is 0, in that case it should get every row that does not start with A - Z (like #0-9.,$ etc).

What is the easiest and fastest way to get those rows?

DB: MySQL 5.1
Column: title

+2  A: 
SELECT  *
FROM    mytable
WHERE   title NOT RLIKE '^[A-Z]'
Quassnoi
+1  A: 
SELECT *
FROM myTable
WHERE theColumn RLIKE '^[^A-Z]'

Explanation:
With RLIKE predicate, a bracketed pattern stands for any one character listed within the bracket (allowing for the use of a dash to indicate ranges, as here, A-Z is "A through Z").
Note the two ^ characters; they have a very distinct meaning:
The first one stands for "beginning of string"
The other ^ character, within the brackets indicates that the pattern should match any character which is not listed thereafter in the bracketed list.
See the mySQL documentation on pattern matching for more details.

The could also be alternatively written as follow

...
WHERE theColumn NOT RLIKE '^[A-Z]'

A word of caution: Independently of the bracketed syntax, the patterns shown above both use a "front end wildcard", which can only be processed by way of a table/index scan (or for the least a partial scan) and this can be relatively inefficient with bigger tables.

mjv
In regular expressions, `%` is not a wildcard
Quassnoi
@Quassnoi: good catch. I mixed LIKE and RLIKE syntax... All fixed, now.
mjv