Informatics Practices · Ch 1 — Querying and SQL Functions
Using Two Relations in a Query
Using Two Relations in a Query
We have so far written every query using only one table — a single relation. But real databases store related data across multiple tables. To answer meaningful questions, you often need to pull information from two tables together. This section introduces that idea: using two relations in a single query.
The textbook does not yet give examples or syntax for joins, subqueries, or set operations. It simply sets the stage. The key point is that from this point onward, you will learn to combine data from two tables — for instance, linking a Student table with a Marks table, or an Orders table with a Customer table — so that your queries can answer questions like "Which students scored above 90?" or "What are the names of customers who placed orders in January?"
The core concept is that two relations are connected through a common column (often a primary key in one table and a foreign key in the other). When you write a query using two relations, you specify how the rows from the two tables are related — this is called a join condition. Without a join condition, the database will pair every row of the first table with every row of the second table, producing a Cartesian product (also called a cross join), which is almost never what you want.
A common mistake is to forget the join condition. If you list two table names in the FROM clause without a WHERE clause that links them, you will get a Cartesian product — every possible combination of rows — which can be huge and meaningless. …