What is an SQL join?
An SQL join combines data from two or more linked tables in a single query, by matching the foreign key in one table with the primary key in another. At Higher, you write the join condition in the WHERE clause. Example: Show each loan's book title with the member's name. Tables: Member(memberID, name) and Loan(loanID, memberID, bookTitle). SELECT name, bookTitle FROM Member, Loan WHERE Member.memberID = Loan.memberID; Answer: The query lists each member's name next to the books they borrowed.
Higher Computing Science queries often need data from more than one table. You list the tables after FROM and match the key fields in WHERE, using the table name and a dot to say which field you mean when both tables share a field name. Extra conditions can be added with AND.
Worked example
Write a query to display each member's name with the titles of the books they have borrowed, using Member(memberID, name) and Loan(loanID, memberID, bookTitle).
- Choose the fields: SELECT name, bookTitle.
- List both tables: FROM Member, Loan.
- Join on the key fields: WHERE Member.memberID = Loan.memberID.
- End the statement with a semicolon.
Answer: SELECT name, bookTitle FROM Member, Loan WHERE Member.memberID = Loan.memberID;
Want one-to-one support?
One-to-one online tuition can help you build confidence in your subject. Find a tutor who teaches your course.
Find a TutorLearn face to face in Glasgow
Prefer in-person lessons? Visit the ExpertTutor Glasgow Southside centre.
See the centre