How to split a string in Mysql?

Asked

Viewed 45 times

1

My Mysql database contains a table t_usuario with a column nome, where there is a record with the name Gustavo Henrique Almeida Martins.

How can I make a SELECT to return only the name Gustavo?

id_usuario name
1 Gustavo Henrique Almeida Martins

2 answers

3


You can use the function SUBSTRING_INDEX.

The first parameter is the value you want to divide, the second is by which character the string will be divided and the third is which of the cut values you want.

SELECT
   SUBSTRING_INDEX(NOME, ' ', 1) AS PrimeiroNome
FROM USUARIOS

See working on SQL Fiddle

  • Here it worked. Thanks!

  • @Gustavomartins For nothing. For the record: you can accept the answer that helped you most by marking the V on her left side.

  • Who voted against could take advantage and tell me what the problem is? = D

1

I believe it will help:

SELECT
    SUBSTRING_INDEX(SUBSTRING_INDEX(nomecompleto, ' ', 1), ' ', -1)  AS primeironome
    ,TRIM( SUBSTR(nomecompleto, LOCATE(' ', nomecompleto)) ) AS sobrenome 
FROM
    suatabela

SQL Fiddle

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.