Consider two tables: Authors and Books. Each author can write many books. The tables are:
Authors(id, name) Books(id, author_id, title)
What is the output of this query?
SELECT Authors.name, Books.title FROM Authors JOIN Books ON Authors.id = Books.author_id WHERE Authors.id = 1 ORDER BY Books.id;
CREATE TABLE Authors (id INT PRIMARY KEY, name VARCHAR(50)); CREATE TABLE Books (id INT PRIMARY KEY, author_id INT, title VARCHAR(100)); INSERT INTO Authors VALUES (1, 'Alice'), (2, 'Bob'); INSERT INTO Books VALUES (1, 1, 'Book A1'), (2, 1, 'Book A2'), (3, 2, 'Book B1');
Remember that JOIN matches rows where the foreign key matches the primary key.
The JOIN matches all books where author_id equals the author's id. For author 1 (Alice), there are two books, so two rows are returned.
In a one-to-many relationship between Customers and Orders, which table should contain the foreign key?
Think about which side 'belongs to' the other.
In one-to-many, the 'many' side (Orders) holds the foreign key referencing the 'one' side (Customers).
Which of the following SQL statements correctly creates a foreign key constraint for a one-to-many relationship where Orders.customer_id references Customers.id?
Check the syntax for adding foreign keys in SQL.
Option B uses the correct syntax: ALTER TABLE table_name ADD FOREIGN KEY (column) REFERENCES other_table(column);
You have large tables Authors and Books with a one-to-many relationship. Which indexing strategy improves the performance of this query?
SELECT Authors.name, Books.title FROM Authors JOIN Books ON Authors.id = Books.author_id WHERE Authors.name LIKE 'A%';
Indexes on columns used in JOIN and WHERE clauses help performance.
Indexing Books.author_id speeds up the JOIN. Indexing Authors.name speeds up the WHERE filter.
Given these tables:
Customers(id, name) Orders(id, customer_id, amount)
You run this query:
SELECT Customers.name, Orders.amount FROM Customers LEFT JOIN Orders ON Customers.id = Orders.customer_id WHERE Orders.amount > 100;
Why might some customers with no orders appear missing from the result?
Think about how WHERE affects LEFT JOIN results.
The WHERE clause Orders.amount > 100 excludes rows where Orders.amount is NULL (no matching order), so customers without orders are removed from the result.