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
);
profilesto be created whenever there is anINSERTonusers?handleexists inprofileswhen i create the new user.