• Aucun résultat trouvé

Combining S ELECT s

Dans le document IntroductionandConcepts PostgreSQL (Page 115-119)

So far, this book has covered topics such as regular expressions, aggregates, and joins. These powerfulSQLfeatures allow the construction of complex queries. In some cases, however, even these tools may prove inadequate. This chapter shows howSELECTs can be combined to create even more powerful queries.

8.1 U

NION

, E

XCEPT

, and I

NTERSECT

Clauses

Sometimes a singleSELECTstatement cannot produce the desired result. UNION, EXCEPT,and

INTERSECTallow SELECTstatements to be chained together, enabling the construction of more complex queries.

For example, suppose we want to output the friend table’s firstname and lastname in the same column. Normally, two queries would be required, one for each column.With UNION, however, the output of twoSELECTs can be combined in a single query, as shown in Figure8.1. The query combines two columns into a single output column.

UNIONallows an unlimited number of SELECTstatements to be combined to produce a single result. EachSELECTmust return the same number of columns. If the firstSELECTreturns two columns, the otherSELECTs must return two columns as well. The column types must also be similar. If the firstSELECTreturns anINTEGERvalue in the first column, the otherSELECTs must return anINTEGERin their first columns, too.

WithUNION,anORDER BYclause can be used only at the end of the lastSELECT. The ordering applies to the output of the entire query. In Figure8.1, theORDER BYclause specifies the ordering column by number. Instead of a number, we could useORDER BY firstnamebecauseUNION’s output labels are the same as the column labels of the firstSELECT.

As another example, suppose we have two tables that hold information about various animals.

One table holds information about aquatic animals, and the other contains data about terrestrial animals. Two tables are used because each records information specific to one class of animal.

The aquatic_animal table holds information meaningful only for aquatic animals, like preferred 87

88 CHAPTER 8. COMBININGSELECTS

Figure 8.1: Combining two columns withUNION

water temperature. The terrestrial_animal table holds information meaningful only for terrestrial animals, like running speed. We could have included the animals in the same table, but keeping them separate was clearer. In most cases, we will deal with the animal types separately.

Suppose we need to list all of the animals, both aquatic and terrestrial. No singleSELECTcan show the animals from both tables. We cannot join the tables because no join key exists; joining is not desired. Instead, we want rows from the terrestrial_animal table and the aquatic_animal table output together in a single column. Figure8.2shows how these two tables can be combined with

UNION.

By default,UNIONprevents duplicate rows from being displayed. For example, Figure8.3inserts penguin into both tables, but penguin is not duplicated in the output. To preserve duplicates, you must useUNION ALL,as shown in Figure8.4.

You can perform more complex operations by chainingSELECTs.EXCEPTallows all rows to be returned from the firstSELECTexcept rows that appear in the secondSELECT. Figure8.5shows anEXCEPTquery. Although the aquatic_animal table contains swordfish and penguin, the query in Figure8.5returns only swordfish. The penguin is excluded from the output because it is returned by the second query. WhileUNIONadds rows to the firstSELECT,EXCEPTsubtracts rows from it.

INTERSECTreturns only rows generated by allSELECTs. Figure8.6usesINTERSECTto display only penguin. While several animals are returned by the twoSELECTs, only penguin is returned by bothSELECTs.

You can link any number of SELECTs using these methods. The previous examples allowed

8.1. UNION, EXCEPT,ANDINTERSECTCLAUSES 89

test=> INSERT INTO terrestrial_animal (name) VALUES (’tiger’);

INSERT 19122 1

test=> INSERT INTO aquatic_animal (name) VALUES (’swordfish’);

INSERT 19123 1 test=> SELECT name

test-> FROM aquatic_animal test-> UNION

test-> SELECT name

test-> FROM terrestrial_animal;

name

---swordfish

tiger (2 rows)

Figure 8.2: Combining two tables withUNION

test=> INSERT INTO aquatic_animal (name) VALUES (’penguin’);

INSERT 19124 1

test=> INSERT INTO terrestrial_animal (name) VALUES (’penguin’);

INSERT 19125 1 test=> SELECT name

test-> FROM aquatic_animal test-> UNION

test-> SELECT name

test-> FROM terrestrial_animal;

name

---penguin

swordfish tiger (3 rows)

Figure 8.3: UNIONwith duplicates

90 CHAPTER 8. COMBININGSELECTS

test=> SELECT name

test-> FROM aquatic_animal test-> UNION ALL

test-> SELECT name

test-> FROM terrestrial_animal;

name

---swordfish

penguin tiger penguin (4 rows)

Figure 8.4: UNION ALLwith duplicates

test=> SELECT name

test-> FROM aquatic_animal test-> EXCEPT

test-> SELECT name

test-> FROM terrestrial_animal;

name

---swordfish

(1 row)

Figure 8.5:EXCEPTrestricts output from the firstSELECT

8.2. SUBQUERIES 91 test=> SELECT name

test-> FROM aquatic_animal test-> INTERSECT

test-> SELECT name

test-> FROM terrestrial_animal;

name

---penguin

(1 row)

Figure 8.6: INTERSECTreturns only duplicated rows

multiple columns to occupy a single result column. Without the ability to chainSELECTs using

UNION,EXCEPT,andINTERSECT,it would be impossible to generate some of these results.SELECT

chaining can enable other sophisticated operations, such as joining a column to one table in the firstSELECT, then joining the same column to another table in the secondSELECT.

8.2 Subqueries

Subqueries are similar toSELECTchaining. WhileSELECTchaining combinesSELECTs on the same level in a query, however, subqueries allowSELECTs to be embedded inside other queries. They can perform several functions:

• They can take the place of a constant.

• They can take the place of a constant yet vary based on the row being processed.

• They can return a list of values for use in a comparison.

Subqueries can be quite complicated. If you have trouble understanding this section, skip over it and return to it later.

Dans le document IntroductionandConcepts PostgreSQL (Page 115-119)