0

I am using postgreSQL and I would like to automatically insert the value of username from table users in the profiles table as handle when i create a new user.

Is this possible by means of an SQL statement?

For clearifing:

First i add a new user:

insert into users (email, user_name, first_name, last_name, active, created_at) values ('[email protected]', 'johndoe', 'John', 'Doe', true, '2018-03-16T17:39:54Z');

After that i create a profile for this user:

insert into profiles (user_id, handle, name, city) VALUES (2, 'johndoe', 'John Doe', 'Tawala');

With this step, the value of user_name should be automatically written to the handle column in the profiles table without doing so manually. Are there solutions like a function in SQL?

Here are my tables:

CREATE TABLE IF NOT EXISTS users (
  id serial UNIQUE NOT NULL,
  email varchar(255) NOT NULL,
  user_name varchar(255) NOT NULL,
  first_name varchar(255) NOT NULL,
  last_name varchar(255) NOT NULL,
  active bool DEFAULT TRUE,
  created_at DATE
);

CREATE TABLE IF NOT EXISTS profiles (
  id serial UNIQUE NOT NULL,
  user_id serial NOT NULL,
  handle varchar(255) NOT NULL,
  name varchar(255) NOT NULL,
  city varchar(255) NULL,
  FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON 
  UPDATE CASCADE
);
4
  • Do you want a new row in profiles to be created whenever there is an INSERT on users? Commented Feb 28, 2019 at 11:33
  • @LaurenzAlbe The row handle exists in profiles when i create the new user. Commented Feb 28, 2019 at 11:35
  • Then I don't understand your question. Can you clarify that. Commented Feb 28, 2019 at 11:47
  • I will write it in the questions. give me a moment Commented Feb 28, 2019 at 11:48

1 Answer 1

1

Yes, you may combine them using a WITH clause INSERT

with ins1
AS
(
  insert into users (email, user_name, first_name, last_name, active, created_at) 
   values ('[email protected]', 'johndoe', 'John', 'Doe', true, '2018-03-16T17:39:54Z')
       returning id as ret_user_id, user_name as ret_user_name 
 )      
  insert into profiles (user_id, handle, name, city) 
     select ret_user_id, ret_user_name ,'John Doe', 'Tawala' 
from ins1; --takes from the returning output.

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that helps me doing what i want ;)

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.