Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract characters to the right of a delimited value in a SELECT statement

I need to extract all the characters to the right of a hyphen as part of a select statement. There will be other columns in the select. In the below query, the right three characters are selected from the second column. How would I extract an indefinite number of characters to the right of a delimiter – in my case a hyphen? Can I use the right function? Do I need to use another function?

Select column1, right(column2,3) as extracted, column3
From myTable

I am using SQL Server 2008.

like image 872
user2525015 Avatar asked Sep 25 '13 13:09

user2525015


People also ask

How do I get substring from right in SQL?

SQL Server RIGHT() Function The RIGHT() function extracts a number of characters from a string (starting from right).

How do I extract a character from a string in SQL?

The SUBSTRING() function extracts some characters from a string.

How can you retrieve a portion of any column value by using a select query?

How can you retrieve a portion of any column value by using a select query in MySQL? SUBSTR() function is used to retrieve the portion of any column.


2 Answers

This question has a database specific answer.

If using SQL Server:

SELECT column1
     , RIGHT(column2,CHARINDEX('-',REVERSE(column2))-1) as extracted
     , column3 
FROM myTable

You can add a CASE statement or use NULLIF() in case the hyphen isn't always present:

SELECT column1
     , CASE WHEN column2 LIKE '%-%' THEN RIGHT(column2,CHARINDEX('-',REVERSE(column2))-1) 
           END as extracted
     , column3 
FROM myTable

Or:

SELECT column1
     , RIGHT(column2,NULLIF(CHARINDEX('-',REVERSE(column2)),0)-1) as extracted
     , column3 
FROM myTable

If using MySQL just change CHARINDEX() to LOCATE(). I believe Oracle it's INSTR() and the first two parameters are switched, first it's the string you're searching in, then the string you're searching for.

like image 149
Hart CO Avatar answered Sep 23 '22 23:09

Hart CO


How about:

SUBSTRING(column2, CHARINDEX('-',column2)+1, 8000)

(Replace 8000 with the definition of the column.)

Of course if the column might not always contain a hyphen, then you can say:

SUBSTRING(column2, COALESCE(NULLIF(CHARINDEX('-',column2)+1,1),1),8000)

If the column does not contain a hyphen, you'll get the whole column. If you want to exclude those from the result, you can add a WHERE clause:

WHERE CHARINDEX('-', column2) > 0

Or you can use a CASE expression like Goat CO's answer.

like image 30
Aaron Bertrand Avatar answered Sep 20 '22 23:09

Aaron Bertrand