Passing UUID of one table to another table as a Foreign key value in PostgreSQL - postgresql

I have table Employee in Postgres:
drop table if exists employee;
create table employee (
id uuid default uuid_generate_v4 () primary key,
first_name varchar not null,
last_name varchar not null
);
And another table salary :
drop table if exists salary;
create table salary (
check_id uuid default uuid_generate_v4 () primary key,
salary int not null,
employee_id uuid references employee (id)
);
employee_id is the foreign key to id in the Employee table, but I don't understand how to insert a value inside employee_id since UUID is unique.
I am inserting values into Employee table:
insert into employee (first_name, last_name, email, code) values ( 'jonh', 'smith', 'jonh#example.com', '1');
And then if I try insert values into salary table:
insert into salary (salary ) values ('1000');
Then select command will return employee_id value empty.
But if I make it default uuid_generate_v4 (), then result is: Key (employee_id)=(c4ccd745-02ba-4a0e-8586-32e3c6a2b84a) is not present in table "employee".
I understand that because employee_id is a foreign key it should match with uuid in employee, but since uuid is mostly unique, how can I make it work?

You have to use the uuid that was inserted into the employee table. You can do this with a CTE in a single statement:
WITH new_employee AS (
INSERT INTO employee (first_name, last_name, email, code)
VALUES ('jonh', 'smith', 'jonh#example.com', '1')
RETURNING id
)
INSERT INTO salary (salary, employee_id)
SELECT 1000, id
FROM new_employee;

Related

How to write a query for PostgreSQL?

How to write a query for PostgreSQL that will list the tables used by the selected materialized view ?
And explain how this query works.
CREATE TABLE films (
id integer PRIMARY KEY,
title varchar(40) NOT NULL,
release_date date,
lenght interval hour to minute,
distributor_id integer
);
CREATE TABLE distributors (
id integer PRIMARY KEY,
name varchar(40) NOT NULL
);
CREATE MATERIALIZED VIEW films_ext AS
SELECT
f.id,
f.title,
f.release_date,
f.lenght,
d.name as distributor
from films f
INNER JOIN distributors d
ON f.distributor_id = d.id;

Add constraint to table postgresql based on other tables

I have these three tables in postgres database:
create table staff (
e_id int primary key,
first_name text,
last_name text,
job text,
branch_name text);
create table temp_staff (
t_id int primary key,
t_first_name text,
t_last_name text,
t_job text );
create table replacements(
e_id int ,
t_id int,
from_date date,
until_date date,
primary key(e_id, t_id, from_date) );
Now I want to add a constraint to the replacements table so you can insert a replacement with e_id and t_id only if e_id exists in the staff table and t_id exists in the temp_staff table.
I tried this:
alter table replacements
add constraint check_existence
check(exists (select 1 from staff where e_id = e_id) and exists (select 1 from temp_staff where t_id = t_id));
And got the error:
ERROR: cannot use subquery in check constraint
Thanks in advance for any help.

Hello I'm pretty new to PostgreSQL so I trying to create a one to one relationship between the tables account and bank_account

I tried using a foreign key, but it still shows them as being separate and not connected is there something I'm missing here, my goal was to originally link the persons name to the account_balance.
CREATE TABLE accounts (
id SERIAL,
first_name VARCHAR(50),
last_name VARCHAR (50),
username VARCHAR (50),
password VARCHAR (500),
account_Type VARCHAR (10),
bday VARCHAR (50),
PRIMARY KEY(id)
);
CREATE TABLE bank_account(
id SERIAL,
account_number INTEGER PRIMARY KEY,
account_balance INTEGER,
CONSTRAINT bank_users
FOREIGN KEY (id)
REFERENCES accounts(id)
ON DELETE CASCADE
);
INSERT INTO accounts (
first_name,
last_name,
username,
password,
account_Type,
bday)
VALUES ('bob', 'john', 'bob#gmail.com', crypt('bob1',gen_salt('bf')),'Manager', '01/01/1985'),
('Tom', 'lin', 'tom#gmail.com', 'tom1', 'Manager', '5/23/1990');
INSERT INTO bank_account(
account_number,
account_balance)
VALUES ('1234', '50000'),('4332', '100000');

Using an id returned from an insert in a with statement in postgresql

Say that you have the following table structure, that you like wikipedia have the identity and state of a page stored in different tables:
create table endUsers (
uuid UUID primary key,
created timestamptz default now()
);
create table endUserRevisions (
id bigserial primary key,
endUser UUID not null references endUsers,
modified timestamptz default now(),
modifiedBy UUID not null references portalUsers,
name text not null,
company text not null,
email text not null
);
alter table endUsers add column
latestRevision bigint not null references endUserRevisions;
And that you then want to insert a completely new user into this database like:
with lastID as (
insert into endUserRevisions (endUser, name, company, email)
values ('08e7882c-7596-43d1-b4cc-69f855210d72', 'a', 'b', 'c') returning id)
insert into endUsers (uuid, latestRevision)
values ('08e7882c-7596-43d1-b4cc-69f855210d72', lastID);
-- or
with revision as (
insert into endUserRevisions (endUser, name, company, email)
values ('08e7882c-7596-43d1-b4cc-69f855210d72', 'a', 'b', 'c') returning *)
insert into endUsers (uuid, latestRevision)
values ('08e7882c-7596-43d1-b4cc-69f855210d72', revision.id);
Both these variants fail with either
column "lastid" does not exist
or
missing FROM-clause entry for table "last"
The reason why the fail is because each subquery is accessable to the surrounding context as a table, not as a plain value. In other words it must be accessed using a select statement like:
with revision as (
insert into endUserRevisions (endUser, name, company, email)
values ('08e7882c-7596-43d1-b4cc-79f855210d76', 'a', 'b', 'c') returning id)
insert into endUsers (uuid, latestRevision)
values ('08e7882c-7596-43d1-b4cc-79f855210d76', (select id from revision));
-- or
with revision as (
insert into endUserRevisions (endUser, name, company, email)
values ('08e7882c-7596-43d1-b4cc-79f855210d74', 'a', 'b', 'c') returning id)
insert into endUsers (uuid, latestRevision)
select '08e7882c-7596-43d1-b4cc-79f855210d74', revision.id from revision;

How to auto increment id when copy the column into another table using PostgreSQL?

insert into usertable (employeenumber) select empno from usertemp
And this is the error
ERROR: null value in column "id" violates not-null constraint
Just create your table using serial, that will create the sequence and the default value
CREATE TABLE usertable (
id serial,
employeenumber integer
);
Insert should be the same
insert into usertable (employeenumber) select empno from usertemp