Matching against multiple possible values

Question

How can you retrieve the details of facilities with ID 1 and 5? Try to do it without using the OR operator.

Expected Results

facidnamemembercostguestcostinitialoutlaymonthlymaintenance
1Tennis Court 25258000200
5Massage Room 2358040003000

Your Answer

Your Results

Loading database...

Answers and Discussion

select *
	from cd.facilities 
	where 
		facid in (1,5);

The obvious answer to this question is to use a WHERE clause that looks like where facid = 1 or facid = 5. An alternative that is easier with large numbers of possible matches is the IN operator. The IN operator takes a list of possible values, and matches them against (in this case) the facid. If one of the values matches, the where clause is true for that row, and the row is returned.

The IN operator is a good early demonstrator of the elegance of the relational model. The argument it takes is not just a list of values - it's actually a table with a single column. Since queries also return tables, if you create a query that returns a single column, you can feed those results into an IN operator. To give a toy example:

select * 
	from cd.facilities
	where
		facid in (
			select facid from cd.facilities
			);
This example is functionally equivalent to just selecting all the facilities, but shows you how to feed the results of one query into another. The inner query is called a subquery.