postreqsql: inserting into 2 tables linked by foreign key so serial id is shared - postgresql

Hello I'm trying to learn the very basics of Postgresql
How can I insert data (name, lastname) into both tables at the same time so that the serial id connects it(is the same). And then delete one entry in both tables that are connected.
My tables I'm trying to figure that out with:
CREATE TABLE user
(
"userid" serial NOT NULL,
name character varying(30),
PRIMARY KEY ("userid")
);
CREATE TABLE public.passwords
(
"userid" integer NOT NULL,
lastname character varying(30),
CONSTRAINT "user_userid" FOREIGN KEY ("userid")
REFERENCES public.user ("userid") MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
NOT VALID
);

You can to insert in both tables sequentially with one query, using the serial generated by the first insert in the second insert as follows:
with u as (insert into users (name) values ('foo') returning userid)
insert into passwords (userid, lastname) select userid, 'bar' from u;

Related

PostgreSQL - Common autoincrement with inherited tables

I'm currently trying the inheritance system with PostgreSQL but I have a problem with the auto-increment index in my child tables.
I have three tables: "Currency", "Crypto" and "Stable"
CREATE TABLE IF NOT EXISTS public.currency
(
id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name VARCHAR(30) UNIQUE NOT NULL,
symbol VARCHAR(10) UNIQUE NOT NULL,
);
CREATE TABLE IF NOT EXISTS public.stable (id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY) INHERITS (public.currency);
CREATE TABLE IF NOT EXISTS public.crypto (id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY) INHERITS (public.currency);
I insered my data like this:
INSERT INTO public.stable (name, symbol) VALUES ('Euro', '€'), ('Dollar', '$'), ('Tether', 'USDT');
INSERT INTO public.crypto (name, symbol) VALUES ('Bitcoin', 'BTC'), ('Ethereum', 'ETH'), ('Litcoin', 'LTC');
But this is my problem: I would like to have a unique identifier that increments itself through my parent table "Currency".
When I select, I have (take a look in my id: 1,2,3,1,2,3):
But, Is it possible to have something like this instead (1,2,3,4,5,6):
Is it a problem in my primary key?
Thank you
We can try to use create sequence to set row numbers for sharing between multiple tables.
define a new sequence generator
create sequence n_id;
Then we can use this sequence as below, sharing this sequence for those three tables.
create sequence n_id;
CREATE TABLE IF NOT EXISTS currency
(
id INT default nextval('n_id') PRIMARY KEY,
name VARCHAR(30) UNIQUE NOT NULL,
symbol VARCHAR(10) UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS stable (id INT default nextval('n_id') PRIMARY KEY) INHERITS (currency);
CREATE TABLE IF NOT EXISTS crypto (id INT default nextval('n_id') PRIMARY KEY) INHERITS (currency);
sqlfiddle

JPA - Double relation and foreign key of non-primary key

I have two tables
Employees
Tasks
Employees table have One to Many relation with Task table.
SQL given below.
CREATE TABLE EMPLOYEES (
employe_id uuid not null primary key,
employe_name varchar not null,
current_task varchar not null
);
CREATE TABLE TASKS (
task_id uuid not null primary key,
employe_id uuid not null,
task_name not null
foreign key (employe_id) references employees(employe_id)
);
We ever I insert new record in tasks table, or create new employee record.
I need to add task_name in tasks table to current_task.
Is there any JPA/Hibernate way to do this?

How to write query in postgresql? (relationship many-to-many)

I'm still a newbie.
I created db like this :
DROP DATABASE IF EXISTS image_store_db;
CREATE DATABASE image_store_db;
\c image_store_db;
CREATE TABLE categories_images (
categories_images_id SERIAL PRIMARY KEY,
title VARCHAR NOT NULL,
image_url VARCHAR NOT NULL,
design_url VARCHAR NOT NULL
);
CREATE TABLE images (
images_id SERIAL PRIMARY KEY,
title VARCHAR NOT NULL,
rating REAL NOT NULL,
image_url VARCHAR NOT NULL,
desc_short TEXT NOT NULL,
desc_full TEXT NOT NULL
);
CREATE TABLE ref_categories_images (
categories_images_id integer REFERENCES categories_images (categories_images_id) ON UPDATE CASCADE,
images_id integer REFERENCES images (images_id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT ref_categories_images_pkey PRIMARY KEY (images_id, categories_images_id)
);
INSERT INTO categories_images(title, image_url, design_url)
VALUES ('SIMPLE TITLE TEST', '/TEST_URL.PNG', '/TEST_URL.PNG');
INSERT INTO images(title, rating, image_url, desc_short, desc_full)
VALUES ('SIMPLE TITLE TEST', 4.5, '/TEST_URL.PNG', 'TEST_SHORT', 'TEST_FULL');
Pls, help. Teach me, how write a query : insert (for image in category) and select (image from category id) and etc ...
pls ...
My answer assumes that categories_images is the table of categories and images is the table of images. The table and attribute names seem to suggest that the concept of many-to-many join is not all clear to you yet; I would have called the three tables category, image and category_image_map.
For INSERT: if your problem are the serial primary keys, use INSERT ... RETURNING.
You can insert into all three tables in a single statement:
WITH im(im_id) AS (
INSERT INTO categories_images ...
RETURNING categories_images_id
),
cat(cat_id) AS (
INSERT INTO images ...
RETURNING images_id
)
INSERT INTO ref_categories_images (categories_images_id, images_id)
VALUES ((SELECT cat_id FROM cat), (SELECT im_id FROM im));
For the query, you just join the three tables:
SELECT ...
FROM categories_images c
JOIN ref_categories_images r
ON r.categories_images_id = c.categories_images_id
JOIN images i
ON r.images_id = i.images_id
and add a WHERE clause for your condition, for example
WHERE c.categories_images_id = 42
or
WHERE i.image_title = 'Mona Lisa'

How to insert a primary/foreign key row in PostgreSQL

I'm populating a database in PostgreSQL for a Newspaper Online. Now my doubt lies on how to insert a value into a table which only attribute is both a primary and a foreign key.
In this context, the admin is the first person to ever register an account. So idAdmin = idA = 1:
CREATE TABLE AUTENTICADO (
idA serial NOT NULL ,
login VARCHAR(45) NOT NULL,
password VARCHAR(45) NOT NULL,
email VARCHAR(40) NOT NULL,
PRIMARY KEY (idA) );
CREATE TABLE ADMIN (
idAdmin INT NOT NULL REFERENCES AUTENTICADO (idA),
PRIMARY KEY (idAdmin) );
It would be logical to insert values into 'ADMIN' as I tried below, although it is obviously not possible considering 'idAdmin' is a primary key (and a foreign key).
INSERT INTO AUTENTICADO VALUES ('john','adadfsfsdfs', 'john#random.com')
INSERT INTO ADMIN VALUES (1)
Is there a way to register that the first user to create an account (idA = 1) is the admin (idAdmin = idA = 1) ?
although it is obviously not possible considering 'idAdmin' is a
primary key (and a foreign key).
So what?
If you fix the first query to list the columns and use a returning clause to get the auto-generated value for the SERIAL ID, it just works:
INSERT INTO AUTENTICADO(login,password,email)
VALUES ('john','adadfsfsdfs', 'john#random.com')
returning idA;
Result:
ida
-----
1
(1 row)
Second query:
insert into admin values(1);
select * from admin;
Result:
idadmin
---------
1

PostgreSQL foreign key not existing, issue of inheritance?

I am struggling with foreign keys in my DB, possibly it has something to do with inheritance?
So here's the basic setup:
-- table address
CREATE TABLE address
(
pk_address serial NOT NULL,
fk_gadmid_0 integer NOT NULL, -- this table already exists, no problem here
street character varying(100),
zip character varying(10),
city character varying(50),
public boolean,
CONSTRAINT address_primarykey PRIMARY KEY (pk_address),
CONSTRAINT gadmid_0_primarykey FOREIGN KEY (fk_gadmid_0)
REFERENCES adm0 (gadmid_0) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE address OWNER TO postgres;
-- table stakeholder (parent)
CREATE TABLE stakeholder
(
pk_stakeholder integer DEFAULT nextval('common_stakeholder_seq') NOT NULL,
fk_stakeholder_type integer NOT NULL, -- this table also exists, no problem here
name character varying(255) NOT NULL,
CONSTRAINT stakeholder_primarykey PRIMARY KEY (pk_stakeholder),
CONSTRAINT stakeholder_fk_stakeholder_type FOREIGN KEY (fk_stakeholder_type)
REFERENCES stakeholder_type (pk_stakeholder_type) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE stakeholder OWNER TO postgres;
-- table individual (child of stakeholder)
CREATE TABLE individual
(
firstname character varying(50),
fk_title integer, -- this table also exists, no problem here
email1 character varying (100),
email2 character varying (100),
phone1 character varying (50),
phone2 character varying (50),
CONSTRAINT individual_primarykey PRIMARY KEY (pk_stakeholder),
CONSTRAINT title_foreignkey FOREIGN KEY (fk_title)
REFERENCES title (pk_title) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
) INHERITS (stakeholder)
WITH (
OIDS=FALSE
);
ALTER TABLE individual OWNER TO postgres;
-- link between stakeholder and address
CREATE TABLE l_stakeholder_address
(
pk_l_stakeholder_address serial NOT NULL,
fk_stakeholder integer NOT NULL REFERENCES stakeholder,
fk_address integer NOT NULL REFERENCES address,
CONSTRAINT l_stakeholder_address_primarykey PRIMARY KEY (pk_l_stakeholder_address),
CONSTRAINT l_stakeholder_address_fk_stakeholder FOREIGN KEY (fk_stakeholder)
REFERENCES stakeholder (pk_stakeholder) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION,
CONSTRAINT l_stakeholder_address_fk_address FOREIGN KEY (fk_address)
REFERENCES address (pk_address) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE l_stakeholder_address OWNER TO postgres;
So far, no problem. Then I tried to add some values:
INSERT INTO individual (pk_stakeholder, fk_stakeholder_type, name, firstname, fk_title, email1, email2, phone1, phone2)
VALUES (1, 8, 'Lastname', 'Firstname', 1, 'me#you.com', '', '', '');
INSERT INTO address (pk_address, fk_gadmid_0, street, zip, city, public)
VALUES (1, 126, 'Address', '', 'City', FALSE);
INSERT INTO l_stakeholder_address (pk_l_stakeholder_address, fk_stakeholder, fk_address)
VALUES (DEFAULT, 1, 1);
And finally I end up having an error (SQL state 23503) saying that the key (fk_stakeholder)=(1) is not existing in table "stakeholder".
The first 2 inserts are fine, I can see them in the databases:
stakeholder:
pk_stakeholder | ...
----------------------
1 | ...
address:
pk_address | ...
--------------------
1 | ...
What am I doing wrong? I must admit that I am rather new to PostgreSQL (using 8.4) but I'm not even sure if that is an issue of PG at all, maybe I'm just lacking some basic database design understandings ...
Either way, by now I tried pretty much everything I could think of, I also tried to make the FK deferrable as in PostgreSQL : Transaction and foreign key problem but somehow that doesn't work either.
You can work around it using additional table individual_pks (individual_pk integer primary key) with all primary keys from both parent and child, which will be maintained using triggers (very simple — insert to individual_pks on insert, delete from it on delete, update it on update, if it changes individual_pk).
Then you point foreign keys to this additional table instead of a child. There'll be some small performance hit, but only when adding/deleting rows.
Or forget inheritance and do it the old way - simply one table with some nullable columns.
Your analysis is exactly right: It's because of the inheritance. When checking the foreign key, child tables are not considered.
In general, inheritance and foreign keys don't mix well in PostgreSQL. A major problem is that you can't have unique constraints across tables.
Reference