How to write a query for PostgreSQL? - 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;

Related

Can these two queries be optimised into a single one?

Given the tables:
create table entries
(
id integer generated always as identity
constraint entries_pk
primary key,
name text not null,
description text,
type integer not null
);
create table tasks
(
id integer generated always as identity
constraint tasks_pk
primary key,
channel_id bigint not null,
type integer not null,
is_active boolean default true not null
);
I currently have two separate queries. First:
SELECT id FROM tasks WHERE is_active = true;
Then, once per result from the last query:
SELECT t.channel_id, e.name, e.description
FROM tasks t
JOIN entries e ON t.type = e.type
WHERE t.id = :task_id
ORDER BY random()
LIMIT 1;
In other words I want a single random entry for each active task.
Can this be accomplished in a single query while retaining the limit per task?
Sure; use DISTINCT ON:
SELECT DISTINCT ON (t.id)
t.id, t.channel_id, e.name, e.description
FROM tasks t
JOIN entries e USING (type)
ORDER BY t.id, random();

Passing UUID of one table to another table as a Foreign key value in 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;

how to retrieve data from multiple tables (postgresql)

I have 4 different tables that are linked to each other in the following way (I only kept the essential columns in each table to emphasise the relationships between them):
create TABLE public.country (
country_code varchar(2) NOT NULL PRIMARY KEY,
country_name text NOT NULL,
);
create table public.address
(
id integer generated always as identity primary key,
country_code text not null,
CONSTRAINT FK_address_2 FOREIGN KEY (country_code) REFERENCES public.country (country_code)
);
create table public.client_order
(
id integer generated always as identity primary key,
address_id integer null,
CONSTRAINT FK_client_order_1 FOREIGN KEY (address_id) REFERENCES public.address (id)
);
create table public.client_order_line
(
id integer generated always as identity primary key,
client_order_id integer not null,
product_id integer not null,
client_order_status_id integer not null default 0,
quantity integer not null,
CONSTRAINT FK_client_order_line_0 FOREIGN KEY (client_order_id) REFERENCES public.client_order (id)
);
I want to get the data in the following way: for each client order line to show the product_id, quantity and country_name(corresponding to that client order line).
I tried this so far:
SELECT country_name FROM public.country WHERE country_code = (
SELECT country_code FROM public.address WHERE id = (
SELECT address_id FROM public.client_order WHERE id= 5
)
)
to get the country name given a client_order_id from client_order_line table. I don't know how to change this to get all the information mentioned above, from client_order_line table which looks like this:
id client_order_id. product_id. status. quantity
1 1 122 0 1000
2 2 122 0 3000
3 2 125 0 3000
4 3 445 0 2000
Thanks a lot!
You need a few join-s.
select col.client_order_id,
col.product_id,
col.client_order_status_id as status,
col.quantity,
c.country_name
from client_order_line col
left join client_order co on col.client_order_id = co.id
left join address a on co.address_id = a.id
left join country c on a.country_code = c.country_code
order by col.client_order_id;
Alternatively you can use your select query as a scalar subquery expression.

Postgresql not choosing rows grouping

I have query. There is a construction like this example: (online demo)
You will see the in result created_at field. I have to use query the created_at field. So I have to use it in select created_at. I don't want to use it created_at field in select. Because, there are millions of records in the deposits table. How can i escape this problem?
(Note: I have many table to query, like "deposits" table. this is just a short example.)
create table payment_methods
(
payment_method_id bigserial not null
constraint payment_methods_pkey
primary key
);
create table currencies_of_payment_methods
(
copm_id bigserial not null
constraint currencies_of_payment_methods_pkey
primary key,
payment_method_id integer not null
);
create table deposits
(
deposit_id bigserial not null
constraint deposits_pkey
primary key,
amount numeric(18,2) not null,
copm_id integer not null,
created_at timestamp(0)
);
INSERT INTO payment_methods (payment_method_id) VALUES (1);
INSERT INTO payment_methods (payment_method_id) VALUES (2);
INSERT INTO currencies_of_payment_methods (copm_id, payment_method_id) VALUES (1, 1);
INSERT INTO deposits (amount, copm_id, created_at) VALUES (100, 1, '2020-09-10 08:49:37');
INSERT INTO deposits (amount, copm_id, created_at) VALUES (200, 1, '2020-09-10 08:49:37');
INSERT INTO deposits (amount, copm_id, created_at) VALUES (40, 1, '2020-09-10 08:49:37');
Query:
SELECT payment_methods.payment_method_id,
deposit_copm_id.deposit_copm_id,
manuel_deposit_amount.manuel_deposit_amount,
manuel_deposit_amount.created_at
FROM payment_methods
CROSS JOIN lateral
(
SELECT currencies_of_payment_methods.copm_id AS deposit_copm_id
FROM currencies_of_payment_methods
WHERE currencies_of_payment_methods.payment_method_id = payment_methods.payment_method_id) deposit_copm_id
CROSS JOIN lateral
(
SELECT sum(deposits.amount) AS manuel_deposit_amount,
array_agg(deposits.created_at) AS created_at
FROM deposits
WHERE deposits.copm_id = deposit_copm_id.deposit_copm_id) manuel_deposit_amount
WHERE payment_methods.payment_method_id = 1

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'