Home > Software engineering >  How do i get the first name from the customer_name column
How do i get the first name from the customer_name column

Time:07-10

enter image description here

 select substring(custmer_name, 1, instr(custmer_name, ' ')) as first_name from sales.customers;

This solution is giving me the answer but It doesn't work with the last name

CodePudding user response:

Please test this: I used locate function to define the position of ' '.

SELECT 
LEFT(customer_name, LOCATE(' ',customer_name)-1) as first_name,
RIGHT(customer_name, LENGTH(customer_name)-LOCATE(' ',customer_name)) as last_name
FROM customer;

Result set: Click to see image

CodePudding user response:

Use SUBSTRING_INDEX() it takes 3 parameter:

  1. Column name
  2. Delimiter
  3. Occurrence count

You can find more explanation in this article

Query

SELECT
  SUBSTRING_INDEX(customer_name,' ', 1) as first_name, 
  SUBSTRING_INDEX(customer_name,' ', -1) as last_name FROM customer;
  • Related