We need to write SQL queries to manage a hardware store database that includes tools, departments, customers, and their purchases. The tests require us to:
-- First create the departments table as it will be referenced by tools
CREATE TABLE departments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(100) NOT NULL
);
-- Create tools table with department foreign key
CREATE TABLE tools (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
department_id INTEGER,
FOREIGN KEY (department_id) REFERENCES departments(id)
);
-- Create customers table
CREATE TABLE customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
phone_number BIGINT
);
-- Create purchases table to track tool purchases
CREATE TABLE purchases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tool_id INTEGER NOT NULL,
customer_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
FOREIGN KEY (tool_id) REFERENCES tools(id),
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
);
-- Insert customers
INSERT INTO customers (first_name, last_name, phone) VALUES
('John', 'Smith', '111-111-1111'),
('Jane', 'Doe', '222-222-2222');
-- Insert tools
INSERT INTO tools (name, price, department) VALUES
('Snow shovel', 16.50, 'Home & Garden'),
('Work light', 29.99, 'Electrical'),
('Wheelbarrow', 89.99, 'Home & Garden'),
('Pipe Wrench', 18.99, 'Plumbing'),
('Pipe Cutter', 36.36, 'Plumbing'),
('Rake', 15.45, 'Home & Garden'),
('Women\'s Gloves', 8.39, 'Home & Garden'),
('Men\'s Gloves', 8.39, 'Home & Garden');
SELECT t.name, t.price, p.quantity
FROM tools t
JOIN purchases p ON p.tool_id = t.id
WHERE t.name LIKE 'Pipe%'
ORDER BY t.name, p.quantity;
This query satisfies the test by:
SELECT name, price
FROM tools
WHERE price BETWEEN 14.67 AND 20.09
ORDER BY name;
This query matches the test requirements by:
SELECT c.first_name, c.last_name, c.phone_number
FROM customers c
JOIN purchases p ON p.customer_id = c.id
JOIN tools t ON t.id = p.tool_id
WHERE t.name = 'Pipe Cutter'
ORDER BY p.id DESC
LIMIT 1;
This query finds the last customer who bought a Pipe Cutter by:
DELETE FROM customers
WHERE first_name = 'John'
AND last_name = 'Smith';
The cascade delete works because:
SELECT first_name, last_name
FROM customers
ORDER BY last_name, first_name;
SELECT t.name, p.quantity
FROM tools t
JOIN purchases p ON p.tool_id = t.id
ORDER BY t.name, p.quantity;
DELETE FROM departments
WHERE name = 'Plumbing';
SELECT name
FROM departments
ORDER BY name;
SELECT name
FROM tools
ORDER BY name;
To verify these solutions:
These queries represent common operations in retail systems:
To reinforce your understanding, try modifying these queries to: