Mysql – Using Regex in theSQL query

MySQLregex

I have a database column with multiple names separated by line breaks like this:

jones, sue
jones, mark

I want to generate a query that keeps the first line and discards the rest, no matter how many lines there are…

I though I was getting close with this:

SELECT 
    name1 
FROM 
    email 
WHERE 
    name1  REGEXP '.*(\r\n)?'

but not quite…

Best Answer

SELECT SUBSTRING_INDEX(col, "\r\n", 1) ...

Test case:

mysql> SELECT SUBSTRING_INDEX("jones, sue\r\njones, mark", "\r\n", 1);
+---------------------------------------------------------+
| SUBSTRING_INDEX("jones, sue\r\njones, mark", "\r\n", 1) |
+---------------------------------------------------------+
| jones, sue                                              |
+---------------------------------------------------------+