I am new to SQL queries and trying to understand it a little better. Is this SQL query valid regarding the picture below The question I was given was:
“For each book authored (or co-authored) by “Stephen King”, retrieve the title and the number of copies owned by the librarybranch whose name is “Central”
x
SELECT Title
FROM BOOK
WHERE BookID =
(
SELECT BookID
FROM BOOK_AUTHORS
WHERE AuthorName = 'Stephen King'
)
AND
BookID =
(
SELECT BookID, No_Of_Copies
FROM BOOK_COPIES
WHERE BranchID =
(
SELECT BranchID
FROM LIBRARY_BRANCH
WHERE BranchName = 'Central'
)
)
Advertisement
Answer
Please use below query, but the right approach is to use joins instead of multiple sub queries
Joins
SELECT B.Title
FROM BOOK B
inner join BOOK_AUTHORS BA
on (B.bookid = ba.bookid)
inner join BOOK_COPIES BC
on (B.bookid = BC.bookid)
inner join LIBRARY_BRANCH LB
on (BC.branchid = LB.branchid)
where B.AuthorName = 'Stephen King'
and LB.BranchName = 'Central';
Subquery
SELECT Title
FROM BOOK
WHERE BookID in
(
SELECT BookID
FROM BOOK_AUTHORS
WHERE AuthorName = 'Stephen King'
)
AND
BookID in
(
SELECT BookID
FROM BOOK_COPIES
WHERE BranchID in
(
SELECT BranchID
FROM LIBRARY_BRANCH
WHERE BranchName = 'Central'
)
);