Home > Articles > Data > SQL

Practical SQL: Selecting Data from the Database

  • Print
  • + Share This
This sample chapter from The Practical SQL Handbook: Using SQL Variants focuses on the SELECT statement and some of the many things it can do. This chapter covers the SELECT, FROM, and WHERE clauses, search conditions, and expressions.
From the author of

SELECT Overview and Syntax

In many ways, the SELECT statement is the real heart of SQL. It lets you find and view your data in a variety of ways. You use it to answer questions based on your data: how many, where, what kind of, even what if. Once you become comfortable with its sometimes dauntingly complex syntax, you'll be amazed at what the SELECT statement can do.

Because SELECT is so important, five chapters focus on it:

  • This chapter begins with the bare bones: the SELECT, FROM, and WHERE clauses, search conditions, and expressions.

  • Chapter 5 delves into some SELECT refinements: ORDER BY, the DISTINCT keyword, and aggregates.

  • Chapter 6 covers the GROUP BY clause, the HAVING clause, and making reports from grouped data. Chapter 6 also summarizes the issues regarding null values in database management.

  • Chapter 7 introduces multiple-table queries with a comprehensive discussion of joining tables.

  • Chapter 8 moves on to nested queries, also known as subqueries.

Queries in this chapter use single tables so that you can focus on manipulating the syntax in a simple environment. Following is an example of a SELECT query—don't worry about the syntax yet:

SQL
select address
from publishers
where pub_id = '0877'
address                 
========================================
2 2nd Ave.
[1 row]

Basic SELECT Syntax

Discovering the structure of the SELECT statement begins with this skeleton:

  • The SELECT clause identifies the columns you want to retrieve.

  • The FROM clause specifies the tables those columns are in.

  • The WHERE clause qualifies the rows—it chooses the ones you want to see.

SYNTAX

SELECT select_list
FROM table_list
WHERE search_conditions

Select_list and Search_condition Expressions

Both the SELECT and WHERE clauses (in the select_list or search_conditions) can include

  • Plain column names (price)

  • Column names combined with other elements, such as calculations (price * 1.085)

  • Constants (character strings or display headings)

Collectively, these are expressions. Because the column name expression is the simplest case, examples often start there and then go on to a more complex expression. This does not mean that a column name is not an expression—it's just the place to start looking at expressions. Syntax that includes "expression" or "expr" or "char_expr" means that you can use a column name or a more complex expression.

Combining SELECT, FROM, and WHERE

Artful combinations of the SELECT, FROM, and WHERE clauses produce meaningful answers to your questions and keep you from drowning in a sea of data. Think of the SELECT and WHERE clauses as horizontal and vertical axes on a matrix. (Figure 4.1 illustrates the query you saw at the beginning of the chapter.) The data you get from the SELECT statement is at the intersection of the SELECT (column) and WHERE (row) clauses.

Figure 4.1 Locating a Specific Piece of Data in a Table

Let's look at a SELECT statement with another bookbiz table, authors. The authors table stores information about authors: ID numbers, names, addresses, and phone numbers. If you want to know just the names of authors who live in California (not their addresses and phone numbers), use the SELECT clause and the WHERE clause to limit the data that the SELECT statement returns.

Here's a query that uses the SELECT clause's select_list to limit the columns you see. It lists just the names for the authors, ignoring their ID numbers, addresses, and phone numbers.

SQL
select au_lname, au_fname
from authors
au_lname                            au_fname      
=================================== ====================
Bennet                              Abraham
Green                               Marjorie
Carson                              Cheryl
Ringer                              Albert
Ringer                              Anne
DeFrance                            Michel
Panteley                            Sylvia
McBadden                            Heather
Stringer                            Dirk
Straight                            Dick
Karsen                              Livia
MacFeather                          Stearns
Dull                                Ann
Yokomoto                            Akiko
O'Leary                             Michael
Gringlesby                          Burt
Greene                              Morningstar
White                               Johnson
del Castillo                        Innes
Hunter                              Sheryl
Locksley                            Chastity
Blotchet-Halls                      Reginald
Smith                               Meander
[23 rows]

This display still doesn't provide exactly what you want because it lists all authors regardless of the state they live in. You need to refine the data retrieval statement further with the WHERE clause.

SQL
select au_lname, au_fname
from authors
where state = 'CA'
au_lname                            au_fname
=================================== ====================
Bennet                              Abraham
Green                               Marjorie
Carson                              Cheryl
McBadden                            Heather
Stringer                            Dirk
Straight                            Dick
Karsen                              Livia
MacFeather                          Stearns
Dull                                Ann
Yokomoto                            Akiko
O'Leary                             Michael
Gringlesby                          Burt
White                               Johnson
Hunter                              Sheryl
Locksley                            Chastity
[15 rows]

Now you're looking at just the names of the 15 authors having a California address. The rows for the eight authors living elsewhere are not included in the display.

Full SELECT Syntax

In practice, SELECT syntax can be either simpler or more complex than the example just shown. It can be simpler in that the SELECT and (in most systems) FROM clauses are the only required ones in a SELECT statement. The WHERE clause (and all other clauses) are optional. On the other hand, the full syntax of the SELECT statement includes all of the following phrases and keywords:

SYNTAX

SELECT [ALL | DISTINCT] select_list
 FROM table/view_list
  [WHERE search_conditions]
  [GROUP BY group_by_list ]
   [HAVING search_conditions]
  [ORDER BY order_by_list ]

SELECT Statement Clause Order

Although SQL is a free-form language, you do have to keep the clauses in a SELECT statement in syntactical order (for example, a GROUP BY clause must come before an ORDER BY clause). Otherwise, you'll get syntax errors.

Naming Conventions

You may need to qualify the names of database objects (according to the customs of your SQL dialect) if there is any ambiguity about which object you mean. In this database, there are several columns called title_id (in the titles table, the titleauthors table, and the titleview view, among others—see Figure 2.13). When you are working with multiple tables, you may have to specify which title_id column you're talking about by including the table or view name, usually separated from the column name by a period (titles.title_id). If the system allows multiple tables with the same name, add the owner name (mary.titles.title_id or dba.titles.title_id)—some possible combinations appear in Figure 4.2. You may also see larger elements, such as database and server names, used this way, but that is less common.

Figure 4.2 Qualifying Columns

The examples in this chapter involve queries on a single table, so qualification is not an important issue here. Qualifiers are also omitted in most books, articles, and reference manuals on SQL because the short forms make SELECT statements more readable. However, it's never wrong to include them.

  • + Share This
  • 🔖 Save To Your Account