Intern — Senior
SQL query to retrieve jobs without attached materials
livecode
Task condition
The task provides two related tables — works and materials. You need to write a query that returns only those records from works for which there are no rows in the materials table.
CREATE TABLE works
(
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE materials
(
id SERIAL PRIMARY KEY,
name VARCHAR(255),
quantity INTEGER,
work_id BIGINT,
FOREIGN KEY (work_id) REFERENCES works(id) ON DELETE CASCADE
);
INSERT INTO works(id, name)
VALUES (1, 'work 1'),
(2, 'work 2'),
(3, 'work 3');
INSERT INTO materials(id, name, quantity, work_id)
VALUES (1, 'mat 1', 10, 1),
(2, 'mat 2', 20, 2),
(3, 'mat 2', 15, 2),
(4, 'mat 4', 30, 2);
The required query, when executed on the provided data, should return only 'work 3' because it has no related records in materials.
Hint: You can use LEFT JOIN ... ON ... WHERE materials.id IS NULL or NOT EXISTS/NOT IN.