SQL Queries for Mere Mortals: Thinking in Sets

• Print
This chapter is from the book

What Is a Set, Anyway?

If you were a teenager any time from the mid-1960s onward, you might have studied set theory in a mathematics course. (Remember New Math?) If you were introduced to set algebra, you probably wondered why any of it would ever be useful.

Now you're trying to learn about relational databases and this quirky language called SQL to build applications, solve problems, or just get answers to your questions. Were you paying attention in algebra class? If so, solving problems—particularly complex ones—in SQL will be much easier.

Actually, you've been working with sets from the beginning of this book. In Chapter 1, What Is Relational?, you learned about the basic structure of a relational database—tables containing records that are made up of one or more fields. (Remember that in SQL, records are known as rows, and fields are known as columns.) Each table in your database is a set of information about one subject. In Chapter 2, Ensuring Your Database Structure Is Sound, you learned how to verify that the structure of your database is sound. Each table should contain the set of information related to one and only one subject or action.

In Chapter 4, Creating a Simple Query, you learned how to build a basic SELECT statement in SQL to retrieve a result set of information that contains specific columns from a single table and how to sort those result sets. In Chapter 5, Getting More Than Simple Columns, you learned how to glean a new set of information from a table by writing expressions that operate on one or more columns. In Chapter 6, Filtering Your Data, you learned how to restrict further the set of information you retrieve from your tables by adding a filter (WHERE clause) to your query.

As you can see, a set can be as little as the data from one column from one row in one table. Actually, you can construct a request in SQL that returns no rows—an empty set. Sometimes it's useful to discover that something does not exist. A set can also be multiple columns (including columns you create with expressions) from multiple rows fetched from multiple tables. Each row in a result set is a member of the set. The values in the columns are specific attributes of each member—data items that describe the member of the set. In the next several chapters, we'll show how to ask for information from multiple sets of data and link these sets together to get answers to more complex questions. First, however, you need to understand more about sets and the logical ways to combine them.