1

I want to create a table ex. Person. Where Person has name and last_name. I want to add a third field called full_name which is the combination of name and last name.

CREATE TABLE person(
   id BIGINT,
   name VARCHAR(50),
   last_name VARCHAR(50),
   full_name VARCHAR(100) *COMBINE(name,last_name)
)

I'm aware that I can create a function like explained here Combine two columns and add into one new column like this

CREATE FUNCTION combined(rec person)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.name || $1.last_name;
$$; 

SELECT *, person.combined FROM person;

But I would like to declare it in the table as another field, is it possible?

2 Answers2

2

You can add a computed column:

alter table person add column full_name text generated always as
    (name || last_name) stored;

Here is a db<>fiddle.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

In Postgres 12:

CREATE TABLE person ( 
     id BIGINT DEFAULT nextval('id_sequence') CONSTRAINT pk_id_person 
             PRIMARY KEY, 
     first_name VARCHAR(50), 
     last_name VARCHAR(50) NOT null, 
     full_name VARCHAR(100) GENERATED ALWAYS AS ( first_name || last_name ) stored ); 

Older Postgres:

Create a table without full name. And add a view that combines the field like this:

CREATE VIEW person_view AS
SELECT id, first_name, last_name, (first_name || last_name) as full_name
FROM person;