Imagine you have two tables: Orders and Customers. The Orders table has a column customer_id that links to the id column in Customers. What is the main purpose of this foreign key?
Think about how foreign keys help keep data consistent between tables.
The foreign key customer_id in Orders ensures that each order references a valid customer in the Customers table. This maintains data integrity by preventing orders from linking to non-existent customers.
Given these tables:
Customers(id, name)
Orders(id, customer_id, product)
What will this query return?
SELECT Customers.name, Orders.product
FROM Orders
JOIN Customers ON Orders.customer_id = Customers.id;
Think about what a JOIN does when matching keys between tables.
The JOIN matches each order to its customer using the foreign key. The result shows customer names alongside their ordered products.
Which option correctly defines a foreign key constraint in SQL?
CREATE TABLE Orders ( id INT PRIMARY KEY, customer_id INT, FOREIGN KEY (customer_id) REFERENCES Customers(id) );
Check the parentheses and semicolon placement in foreign key syntax.
The correct syntax requires parentheses around the foreign key column and no semicolon inside the table definition line. The semicolon ends the whole statement.
You have a large Orders table linked to Customers by a foreign key. Which action will best improve join query speed?
Think about how databases find matching rows quickly.
Indexing the foreign key column helps the database quickly find matching rows during joins, improving performance.
Given these tables:
CREATE TABLE Customers (id INT PRIMARY KEY, name TEXT);
CREATE TABLE Orders (id INT PRIMARY KEY, customer_id INT, FOREIGN KEY (customer_id) REFERENCES Customers(id));
What error occurs when running this?
INSERT INTO Orders (id, customer_id) VALUES (1, 999);
Consider what happens if you insert a foreign key value not present in the referenced table.
The foreign key constraint prevents inserting a customer_id that does not exist in Customers, causing a violation error.