Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Column that Represents a Concatenation of Two Other Varchar Columns

Tags:

I have an employees table and I want to add a third column valued as the concatenation of the first and last name called "FullName". How can I accomplish that without losing any data from either of the first two columns?

like image 694
Stampin Stephie Avatar asked Jul 14 '14 04:07

Stampin Stephie


People also ask

How do I concatenate two columns in SQL with spaces?

To concatenate two string type columns separated by space, we can use space function. Notice the SPACE(1) function in between FirstName and LastName. As the parameter value passed in SPACE function is 1 so there will be one blank space in between FirstName and LastName column values.

What is string concatenation in SQL?

CONCAT function is a SQL string function that provides to concatenate two or more than two character expressions into a single string.


2 Answers

Quick preface: this answer was based on the originally incorrect tag that this question was relating to SQL Server. I'm no longer aware of its validity on Oracle SQL Developer.

ALTER TABLE Employees ADD FullName AS (FirstName + ' ' + LastName) 

Although in practice I'd advise that you do that operation in your SELECT. That's somewhat personal preference, but I tend to think doing things in your end queries is a bit cleaner, more readable, and easier to maintain than storing extra, calculated columns.

Edit:

This was eventually found as the answer, and listed by the OP as a comment on this post. The following is appropriate syntax for Oracle Sql Database.

ALTER TABLE emps MODIFY (FULL_NAME VARCHAR2(50) GENERATED ALWAYS AS (first_name || ' ' || last_name) VIRTUAL);  
like image 198
Matthew Haugen Avatar answered Nov 08 '22 05:11

Matthew Haugen


If you need fullname column all time when you select from database then you can create computed column at the time of creation of your table employee.

for example:

CREATE TABLE Employee (   FirstName VARCHAR(20),   LastName VARCHAR(20),   FullName AS CONCAT(FirstName,' ',LastName) )  INSERT INTO Employee VALUES ('Rocky','Jeo')  SELECT * FROM Employee     Output:    FirstName  LastName  FullName   Rocky      Jeo       Rocky Jeo 
like image 39
mansi Avatar answered Nov 08 '22 05:11

mansi