0

I have a field named names in a table. This field shows "last_name, first_name". I am trying to take that field from the names table and insert the values into a new table into 2 different columns labeled last_name and first_name. I have tried the following codes:

INSERT INTO usernames (last_name,first_name)
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',1),',',-1) as last_name,
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',2),',',-1) as first_name
FROM person;

and

INSERT INTO usernames (last_name,first_name)
SELECT IF(LOCATE(', ',name)>0
SUBSTRING(name,1,LOCATE(', ',name)-1) AS last_name,
IF(LOCATE(', ',name)>0
SUBSTRING(name,LOCATE(', ',name)+1),NULL) AS first_name
FROM person;

I'm not sure what I am doing wrong with this code. Any help Is greatly appreciated.

Thank you, Larry

1 Answer 1

1

your query is almost ok, but second SELECT is not needed. check the syntax of SELECT in documentation.

INSERT INTO usernames (last_name,first_name)
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',1),',',-1) as last_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(name,',',2),',',-1) as first_name
FROM person;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response Inna Tichman. That worked beautifully

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.