Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting alpha and numeric parts from a column

I have a table tab1 with a column col1 that has compound alpha-then-numeric values, like this:

abc123
xy45
def6
z9

I need to extract the values as separate columns in a query, with the numeric part in a column of integer datatype.

If the two values had a consistent start and end positions, the job could be done with substring(), as you can see the start of the numeric part varies.

Is there an elegant way to tackle this, or must it be done with a series of unions of each possible start point using a regex match to separate the cases, or rolled up in a huge case statement?

like image 248
Bohemian Avatar asked Jan 03 '14 07:01

Bohemian


People also ask

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.

How do I select only numeric values in a column in SQL?

In SQL Server, we can use the ISNUMERIC() function to return numeric values from a column. We can alternatively run a separate query to return all values that contain numeric data.


1 Answers

Yes, it is:

SELECT
  @col:=col1 AS col, 
  @num:=REVERSE(CAST(REVERSE(@col) AS UNSIGNED)) AS num,
  SUBSTRING_INDEX(@col, @num, 1) AS word
FROM
  tab1

-will work only if your column contain letters and then numbers (like you've described). That's why double REVERSE() is needed (otherwise CAST() will have no effect). Check this demo.

like image 76
Alma Do Avatar answered Oct 05 '22 01:10

Alma Do