I want to add a new column called FullNameReverseOrder to a table called NameTable where the info for the FullName is in FirstName LastName order and the FullNameReverseOrder will hold the LastName FirstName order.
this is a table you can use:
create table NameTable (ID int, FullName varchar(100), age int, primary key(ID));
insert into NameTable (ID, FullName, age) values(1, 'ben thompson', 23);
add the new column called FullNameReverseOrder:
alter table NameTable add column FullNameReverseOrder varchar(100) ...no idea what to do here... after FullName;
2
Answers
After adding your new column
FullNameReverseOrder
you could useSUBSTRING_INDEX
to split on the first space to get the first name (this is an assumption that first names don’t contain spaces).The last name is then the remainder of the
FullName
string after the first name (and space).You can use
CONCAT
to join the parts again. Putting it all together:Some points to consider.
As per the question
Consider the following data examples which consider the
FullName
column has maximum three words separated by spaceQuery ,
Result,
First change the table structure by altering , I always suggest proper locinkg the table if there is a large number of transactions
To update the new added column LastName , MiddleName, FirstName use,
Select ,
Result
Now if you want the process automatic, consider creating a trigger .
Insert test value
Result
Se examplee