Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch rows where first character is not alphanumeric

I am adding a few new features to a small project i'm working on and one of them is alpha pagination which looks like

# 0-9 A B C D E ... X Y Z

I can easily fetch items by their first letter using something like

SELECT * FROM ... WHERE name LIKE 'A%' ...

Grouping everything that starts with a number and all other characters is a little more difficult, I assume it would have to use MySQLs REGEXP.

Just to be clear, I need help creating two queries which will fetch all rows where

  • the first character of a column is numeric
  • the first character of a column is not alphanumeric
like image 917
DanCake Avatar asked Jun 26 '09 22:06

DanCake


People also ask

How do I exclude an alpha character in SQL?

In SQL Server, we can use NOT LIKE with a list of alphanumeric characters that we want to exclude from the result: SELECT c1 FROM t1 WHERE c1 NOT LIKE '%[a-zA-Z0-9]%'; That returns rows that only contain non-alphanumeric characters.

How do I fetch alphanumeric values in SQL?

Using LIKE clause Val LIKE '%[A-Z]%', it ensures that string should contain alphanumeric characters. Val LIKE '%[0-9]%', it ensures that string should contain numeric characters. Lets see the output of T-SQL, you can see it returns only alphanumeric string only.

Which data type is used to store alphanumeric values in SQL?

You can use these SQL data types to store alphanumeric data: CHAR and NCHAR data types store fixed-length character literals.


1 Answers

First character is numeric:

SELECT * FROM ... WHERE name REGEXP '^[0-9]';

First character is not alphanumeric:

SELECT * FROM ... WHERE name REGEXP '^[^0-9A-Za-z]';

(Note that this is distinct from NOT REGEXP ^[0-9A-Za-z], because you seem to only want to match when there is in fact a first character.)

You can probably substitute [^[:alnum:]] for [^0-9A-Za-z], but I haven't tested it. You can certainly substitute [[:digit:]] for [0-9], but it's longer. :-)

Also see the MySQL REGEXP Reference.

like image 135
molf Avatar answered Sep 22 '22 10:09

molf