~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to doc/src/sgml/sql.sgml

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!--
 
2
$PostgreSQL: pgsql/doc/src/sgml/sql.sgml,v 1.33.4.1 2005-01-22 23:05:50 momjian Exp $
 
3
-->
 
4
 
 
5
 <chapter id="sql-intro">
 
6
  <title>SQL</title>
 
7
 
 
8
  <abstract>
 
9
   <para>
 
10
    This chapter introduces the mathematical concepts behind
 
11
    relational databases. It is not required reading, so if you bog
 
12
    down or want to get straight to some simple examples feel free to
 
13
    jump ahead to the next chapter and come back when you have more
 
14
    time and patience. This stuff is supposed to be fun!
 
15
   </para>
 
16
 
 
17
   <para>
 
18
    This material originally appeared as a part of
 
19
    Stefan Simkovics' Master's Thesis
 
20
    (<xref linkend="SIM98" endterm="SIM98">).
 
21
   </para>
 
22
  </abstract>
 
23
 
 
24
  <para>
 
25
   <acronym>SQL</acronym> has become the most popular relational query 
 
26
   language.
 
27
   The name <quote><acronym>SQL</acronym></quote> is an abbreviation for
 
28
   <firstterm>Structured Query Language</firstterm>. 
 
29
   In 1974 Donald Chamberlin and others defined the
 
30
   language SEQUEL (<firstterm>Structured English Query
 
31
    Language</firstterm>) at IBM
 
32
   Research. This language was first implemented in an IBM
 
33
   prototype called SEQUEL-XRM in 1974-75. In 1976-77 a revised version
 
34
   of SEQUEL called SEQUEL/2 was defined and the name was changed to
 
35
   <acronym>SQL</acronym>
 
36
   subsequently.
 
37
  </para>
 
38
 
 
39
  <para>
 
40
   A new prototype called System R was developed by IBM in 1977. System R
 
41
   implemented a large subset of SEQUEL/2 (now <acronym>SQL</acronym>)
 
42
   and a number of
 
43
   changes were made to <acronym>SQL</acronym> during the project.
 
44
   System R was installed in
 
45
   a number of user sites, both internal IBM sites and also some selected
 
46
   customer sites. Thanks to the success and acceptance of System R at
 
47
   those user sites IBM started to develop commercial products that
 
48
   implemented the <acronym>SQL</acronym> language based on the System
 
49
   R technology.
 
50
  </para>
 
51
 
 
52
  <para>
 
53
   Over the next years IBM and also a number of other vendors announced
 
54
   <acronym>SQL</acronym> products such as
 
55
   <productname>SQL/DS</productname> (IBM),
 
56
   <productname>DB2</productname> (IBM),
 
57
   <productname>ORACLE</productname> (Oracle Corp.),
 
58
   <productname>DG/SQL</productname> (Data General Corp.),
 
59
   and <productname>SYBASE</productname> (Sybase Inc.).
 
60
  </para>
 
61
 
 
62
  <para>
 
63
   <acronym>SQL</acronym> is also an official standard now. In 1982
 
64
   the American National
 
65
   Standards Institute (<acronym>ANSI</acronym>) chartered its
 
66
   Database Committee X3H2 to
 
67
   develop a proposal for a standard relational language. This proposal
 
68
   was ratified in 1986 and consisted essentially of the IBM dialect of
 
69
   <acronym>SQL</acronym>. In 1987 this <acronym>ANSI</acronym> 
 
70
   standard was also accepted as an international
 
71
   standard by the International Organization for Standardization
 
72
   (<acronym>ISO</acronym>).
 
73
   This original standard version of <acronym>SQL</acronym> is often
 
74
   referred to,
 
75
   informally, as <quote><abbrev>SQL/86</abbrev></quote>. In 1989 the original
 
76
   standard was extended
 
77
   and this new standard is often, again informally, referred to as
 
78
   <quote><abbrev>SQL/89</abbrev></quote>. Also in 1989, a related standard called
 
79
   <firstterm>Database Language Embedded <acronym>SQL</acronym></firstterm>
 
80
   (<acronym>ESQL</acronym>) was developed.
 
81
  </para>
 
82
 
 
83
  <para>
 
84
   The <acronym>ISO</acronym> and <acronym>ANSI</acronym> committees
 
85
   have been working for many years on the
 
86
   definition of a greatly expanded version of the original standard,
 
87
   referred to informally as <firstterm><acronym>SQL2</acronym></firstterm>
 
88
   or <firstterm><acronym>SQL/92</acronym></firstterm>. This version became a
 
89
   ratified standard - <quote>International Standard ISO/IEC 9075:1992,
 
90
   Database Language <acronym>SQL</acronym></quote> - in late 1992.
 
91
   <acronym>SQL/92</acronym> is the version
 
92
   normally meant when people refer to <quote>the <acronym>SQL</acronym>
 
93
   standard</quote>. A detailed
 
94
   description of <acronym>SQL/92</acronym> is given in 
 
95
   <xref linkend="DATE97" endterm="DATE97">. At the time of
 
96
   writing this document a new standard informally referred to
 
97
   as <firstterm><acronym>SQL3</acronym></firstterm>
 
98
   is under development. It is planned to make <acronym>SQL</acronym>
 
99
   a Turing-complete
 
100
   language, i.e. all computable queries (e.g. recursive queries) will be
 
101
   possible. This is a very complex task and therefore the completion of
 
102
   the new standard can not be expected before 1999.
 
103
  </para>
 
104
 
 
105
  <sect1 id="rel-model">
 
106
   <title>The Relational Data Model</title>
 
107
 
 
108
  <para>
 
109
    As mentioned before, <acronym>SQL</acronym> is a relational
 
110
    language. That means it is
 
111
    based on the <firstterm>relational data model</firstterm>
 
112
    first published by E.F. Codd in
 
113
    1970. We will give a formal description of the relational model
 
114
    later (in
 
115
    <xref linkend="formal-notion" endterm="formal-notion">)
 
116
    but first we want to have a look at it from a more intuitive
 
117
    point of view.
 
118
  </para>
 
119
 
 
120
  <para>
 
121
    A <firstterm>relational database</firstterm> is a database that is 
 
122
    perceived by its
 
123
    users as a <firstterm>collection of tables</firstterm> (and
 
124
    nothing else but tables).
 
125
    A table consists of rows and columns where each row represents a
 
126
    record and each column represents an attribute of the records
 
127
    contained in the table.
 
128
    <xref linkend="supplier-fig" endterm="supplier-fig">
 
129
    shows an example of a database consisting of three tables:
 
130
 
 
131
    <itemizedlist>
 
132
     <listitem>
 
133
      <para>
 
134
       SUPPLIER is a table storing the number
 
135
       (SNO), the name (SNAME) and the city (CITY) of a supplier.
 
136
      </para>
 
137
     </listitem>
 
138
 
 
139
     <listitem>
 
140
      <para>
 
141
       PART is a table storing the number (PNO) the name (PNAME) and
 
142
       the price (PRICE) of a part.
 
143
      </para>
 
144
     </listitem>
 
145
 
 
146
     <listitem>
 
147
      <para>
 
148
       SELLS stores information about which part (PNO) is sold by which
 
149
       supplier (SNO). 
 
150
       It serves in a sense to connect the other two tables together.
 
151
      </para>
 
152
     </listitem>
 
153
    </itemizedlist>
 
154
 
 
155
    <example>
 
156
     <title id="supplier-fig">The Suppliers and Parts Database</title>
 
157
     <programlisting>
 
158
SUPPLIER:                   SELLS:
 
159
 SNO |  SNAME  |  CITY       SNO | PNO
 
160
----+---------+--------     -----+-----
 
161
 1  |  Smith  | London        1  |  1
 
162
 2  |  Jones  | Paris         1  |  2
 
163
 3  |  Adams  | Vienna        2  |  4
 
164
 4  |  Blake  | Rome          3  |  1
 
165
                              3  |  3
 
166
                              4  |  2
 
167
PART:                         4  |  3
 
168
 PNO |  PNAME  |  PRICE       4  |  4
 
169
----+---------+---------
 
170
 1  |  Screw  |   10
 
171
 2  |  Nut    |    8
 
172
 3  |  Bolt   |   15
 
173
 4  |  Cam    |   25
 
174
     </programlisting>
 
175
    </example>
 
176
   </para>
 
177
 
 
178
   <para>
 
179
    The tables PART and SUPPLIER may be regarded as
 
180
    <firstterm>entities</firstterm> and
 
181
    SELLS may be regarded as a <firstterm>relationship</firstterm>
 
182
    between a particular
 
183
    part and a particular supplier. 
 
184
   </para>
 
185
 
 
186
   <para>
 
187
    As we will see later, <acronym>SQL</acronym> operates on tables
 
188
    like the ones just
 
189
    defined but before that we will study the theory of the relational
 
190
    model.
 
191
   </para>
 
192
  </sect1>
 
193
 
 
194
  <sect1 id="relmodel-formal">
 
195
   <title id="formal-notion">Relational Data Model Formalities</title>
 
196
 
 
197
   <para>
 
198
    The mathematical concept underlying the relational model is the
 
199
    set-theoretic <firstterm>relation</firstterm> which is a subset of
 
200
    the Cartesian
 
201
    product of a list of domains. This set-theoretic relation gives
 
202
    the model its name (do not confuse it with the relationship from the
 
203
    <firstterm>Entity-Relationship model</firstterm>).
 
204
    Formally a domain is simply a set of
 
205
    values. For example the set of integers is a domain. Also the set of
 
206
    character strings of length 20 and the real numbers are examples of
 
207
    domains.
 
208
   </para>
 
209
 
 
210
   <para>
 
211
<!--
 
212
\begin{definition}
 
213
The <firstterm>Cartesian product</firstterm> of domains $D_{1},
 
214
    D_{2},\ldots, D_{k}$ written
 
215
\mbox{$D_{1} \times D_{2} \times \ldots \times D_{k}$} is the set of
 
216
all $k$-tuples $(v_{1},v_{2},\ldots,v_{k})$ such that \mbox{$v_{1} \in
 
217
D_{1}, v_{2} \in D_{2}, \ldots, v_{k} \in D_{k}$}.
 
218
\end{definition}
 
219
-->
 
220
    The <firstterm>Cartesian product</firstterm> of domains
 
221
    <parameter>D<subscript>1</subscript></parameter>,
 
222
    <parameter>D<subscript>2</subscript></parameter>,
 
223
    ...
 
224
    <parameter>D<subscript>k</subscript></parameter>,
 
225
    written
 
226
    <parameter>D<subscript>1</subscript></parameter> &times;
 
227
    <parameter>D<subscript>2</subscript></parameter> &times;
 
228
    ... &times;
 
229
    <parameter>D<subscript>k</subscript></parameter>
 
230
    is the set of all k-tuples
 
231
    <parameter>v<subscript>1</subscript></parameter>,
 
232
    <parameter>v<subscript>2</subscript></parameter>,
 
233
    ...
 
234
    <parameter>v<subscript>k</subscript></parameter>,
 
235
    such that
 
236
    <parameter>v<subscript>1</subscript></parameter> &isin; 
 
237
    <parameter>D<subscript>1</subscript></parameter>,
 
238
    <parameter>v<subscript>2</subscript></parameter> &isin; 
 
239
    <parameter>D<subscript>2</subscript></parameter>,
 
240
    ...
 
241
    <parameter>v<subscript>k</subscript></parameter> &isin; 
 
242
    <parameter>D<subscript>k</subscript></parameter>.
 
243
   </para>
 
244
 
 
245
   <para>
 
246
    For example, when we have
 
247
<!--
 
248
 $k=2$, $D_{1}=\{0,1\}$ and
 
249
$D_{2}=\{a,b,c\}$, then $D_{1} \times D_{2}$ is
 
250
$\{(0,a),(0,b),(0,c),(1,a),(1,b),(1,c)\}$.
 
251
-->
 
252
    <parameter>k</parameter>=2,
 
253
    <parameter>D<subscript>1</subscript></parameter>=<literal>{0,1}</literal> and
 
254
    <parameter>D<subscript>2</subscript></parameter>=<literal>{a,b,c}</literal> then
 
255
    <parameter>D<subscript>1</subscript></parameter> &times;
 
256
    <parameter>D<subscript>2</subscript></parameter> is
 
257
    <literal>{(0,a),(0,b),(0,c),(1,a),(1,b),(1,c)}</literal>.
 
258
   </para>
 
259
 
 
260
   <para>
 
261
<!--
 
262
\begin{definition}
 
263
A Relation is any subset of the Cartesian product of one or more
 
264
domains: $R \subseteq$ \mbox{$D_{1} \times D_{2} \times \ldots \times D_{k}$}
 
265
\end{definition}
 
266
-->
 
267
    A Relation is any subset of the Cartesian product of one or more
 
268
    domains: <parameter>R</parameter> &sube;
 
269
    <parameter>D<subscript>1</subscript></parameter> &times;
 
270
    <parameter>D<subscript>2</subscript></parameter> &times;
 
271
    ... &times;
 
272
    <parameter>D<subscript>k</subscript></parameter>.
 
273
   </para>
 
274
 
 
275
   <para>
 
276
    For example <literal>{(0,a),(0,b),(1,a)}</literal> is a relation;
 
277
    it is in fact a subset of
 
278
    <parameter>D<subscript>1</subscript></parameter> &times;
 
279
    <parameter>D<subscript>2</subscript></parameter>
 
280
    mentioned above.
 
281
   </para>
 
282
 
 
283
   <para>
 
284
    The members of a relation are called tuples. Each relation of some
 
285
    Cartesian product
 
286
    <parameter>D<subscript>1</subscript></parameter> &times;
 
287
    <parameter>D<subscript>2</subscript></parameter> &times;
 
288
    ... &times;
 
289
    <parameter>D<subscript>k</subscript></parameter>
 
290
    is said to have arity <literal>k</literal> and is therefore a set
 
291
    of <literal>k</literal>-tuples.
 
292
   </para>
 
293
 
 
294
   <para>
 
295
    A relation can be viewed as a table (as we already did, remember
 
296
    <xref linkend="supplier-fig" endterm="supplier-fig"> where
 
297
    every tuple is represented by a row and every column corresponds to
 
298
    one component of a tuple. Giving names (called attributes) to the
 
299
    columns leads to the definition of a 
 
300
    <firstterm>relation scheme</firstterm>.
 
301
   </para>
 
302
 
 
303
   <para>
 
304
<!--
 
305
\begin{definition}
 
306
A {\it relation scheme} $R$ is a finite set of attributes
 
307
\mbox{$\{A_{1},A_{2},\ldots,A_{k}\}$}. There is a domain $D_{i}$ for
 
308
each attribute $A_{i}, 1 \le i \le k$ where the values of the
 
309
attributes are taken from. We often write a relation scheme as
 
310
\mbox{$R(A_{1},A_{2},\ldots,A_{k})$}.
 
311
\end{definition}
 
312
-->
 
313
    A <firstterm>relation scheme</firstterm> <literal>R</literal> is a 
 
314
    finite set of attributes
 
315
    <parameter>A<subscript>1</subscript></parameter>,
 
316
    <parameter>A<subscript>2</subscript></parameter>,
 
317
    ...
 
318
    <parameter>A<subscript>k</subscript></parameter>.
 
319
    There is a domain
 
320
    <parameter>D<subscript>i</subscript></parameter>,
 
321
    for each attribute
 
322
    <parameter>A<subscript>i</subscript></parameter>,
 
323
    1 &lt;= <literal>i</literal> &lt;= <literal>k</literal>,
 
324
    where the values of the attributes are taken from. We often write
 
325
    a relation scheme as
 
326
    <literal>R(<parameter>A<subscript>1</subscript></parameter>,
 
327
    <parameter>A<subscript>2</subscript></parameter>,
 
328
    ...
 
329
    <parameter>A<subscript>k</subscript></parameter>)</literal>.
 
330
 
 
331
    <note>
 
332
     <para>
 
333
      A <firstterm>relation scheme</firstterm> is just a kind of template
 
334
      whereas a <firstterm>relation</firstterm> is an instance of a
 
335
      <firstterm>relation
 
336
       scheme</firstterm>. The relation consists of tuples (and can
 
337
      therefore be
 
338
      viewed as a table); not so the relation scheme.
 
339
     </para>
 
340
    </note>
 
341
   </para>
 
342
 
 
343
   <sect2>
 
344
    <title id="domains">Domains vs. Data Types</title>
 
345
 
 
346
    <para>
 
347
     We often talked about <firstterm>domains</firstterm>
 
348
     in the last section. Recall that a
 
349
     domain is, formally, just a set of values (e.g., the set of integers or
 
350
     the real numbers). In terms of database systems we often talk of
 
351
     <firstterm>data types</firstterm> instead of domains.
 
352
     When we define a table we have to make
 
353
     a decision about which attributes to include. Additionally we
 
354
     have to decide which kind of data is going to be stored as
 
355
     attribute values. For example the values of
 
356
     <classname>SNAME</classname> from the table
 
357
     <classname>SUPPLIER</classname> will be character strings,
 
358
     whereas <classname>SNO</classname> will store
 
359
     integers. We define this by assigning a data type to each
 
360
     attribute. The type of <classname>SNAME</classname> will be
 
361
     <type>VARCHAR(20)</type> (this is the <acronym>SQL</acronym> type
 
362
     for character strings of length &lt;= 20),
 
363
     the type of <classname>SNO</classname> will be
 
364
     <type>INTEGER</type>. With the assignment of a data type we also
 
365
     have selected
 
366
     a domain for an attribute. The domain of
 
367
     <classname>SNAME</classname> is the set of all
 
368
     character strings of length &lt;= 20,
 
369
     the domain of <classname>SNO</classname> is the set of
 
370
     all integer numbers.
 
371
    </para>
 
372
   </sect2>
 
373
  </sect1>
 
374
 
 
375
  <sect1 id="relmodel-oper">
 
376
   <title id="operations">Operations in the Relational Data Model</title>
 
377
 
 
378
   <para>
 
379
    In the previous section
 
380
    (<xref linkend="formal-notion" endterm="formal-notion">)
 
381
    we defined the mathematical notion of
 
382
    the relational model. Now we know how the data can be stored using a
 
383
    relational data model but we do not know what to do with all these
 
384
    tables to retrieve something from the database yet. For example somebody
 
385
    could ask for the names of all suppliers that sell the part
 
386
    'Screw'. Therefore two rather different kinds of notations for
 
387
    expressing operations on relations have been defined:
 
388
 
 
389
    <itemizedlist>
 
390
     <listitem>
 
391
      <para>
 
392
       The <firstterm>Relational Algebra</firstterm> which is an
 
393
       algebraic notation,
 
394
       where queries are expressed by applying specialized operators to the
 
395
       relations.
 
396
      </para>
 
397
     </listitem>
 
398
 
 
399
     <listitem>
 
400
      <para>
 
401
       The <firstterm>Relational Calculus</firstterm> which is a
 
402
       logical notation,
 
403
       where queries are expressed by formulating some logical restrictions
 
404
       that the tuples in the answer must satisfy.
 
405
      </para>
 
406
    </listitem>
 
407
    </itemizedlist>
 
408
   </para>
 
409
 
 
410
   <sect2>
 
411
    <title id="rel-alg">Relational Algebra</title>
 
412
 
 
413
    <para>
 
414
     The <firstterm>Relational Algebra</firstterm> was introduced by
 
415
     E. F. Codd in 1972. It consists of a set of operations on relations:
 
416
 
 
417
     <itemizedlist>
 
418
      <listitem>
 
419
       <para>
 
420
        SELECT (&sigma;): extracts <firstterm>tuples</firstterm> from
 
421
        a relation that
 
422
        satisfy a given restriction. Let <parameter>R</parameter> be a 
 
423
        table that contains an attribute
 
424
        <parameter>A</parameter>.
 
425
&sigma;<subscript>A=a</subscript>(R) = {t &isin; R &mid; t(A) = a}
 
426
        where <literal>t</literal> denotes a
 
427
        tuple of <parameter>R</parameter> and <literal>t(A)</literal>
 
428
        denotes the value of attribute <parameter>A</parameter> of
 
429
        tuple <literal>t</literal>.
 
430
       </para>
 
431
      </listitem>
 
432
 
 
433
      <listitem>
 
434
       <para>
 
435
        PROJECT (&pi;): extracts specified
 
436
        <firstterm>attributes</firstterm> (columns) from a
 
437
        relation. Let <classname>R</classname> be a relation
 
438
        that contains an attribute <classname>X</classname>.
 
439
        &pi;<subscript>X</subscript>(<classname>R</classname>) = {t(X) &mid; t &isin; <classname>R</classname>},
 
440
        where <literal>t</literal>(<classname>X</classname>) denotes the value of
 
441
        attribute <classname>X</classname> of tuple <literal>t</literal>.
 
442
       </para>
 
443
      </listitem>
 
444
 
 
445
      <listitem>
 
446
       <para>
 
447
        PRODUCT (&times;): builds the Cartesian product of two
 
448
        relations. Let <classname>R</classname> be a table with arity
 
449
        <literal>k</literal><subscript>1</subscript> and let
 
450
        <classname>S</classname> be a table with
 
451
        arity <literal>k</literal><subscript>2</subscript>.
 
452
        <classname>R</classname> &times; <classname>S</classname>
 
453
        is the set of all 
 
454
        <literal>k</literal><subscript>1</subscript>
 
455
        + <literal>k</literal><subscript>2</subscript>-tuples
 
456
        whose first <literal>k</literal><subscript>1</subscript>
 
457
        components form a tuple in <classname>R</classname> and whose last
 
458
        <literal>k</literal><subscript>2</subscript> components form a
 
459
        tuple in <classname>S</classname>.
 
460
       </para>
 
461
      </listitem>
 
462
 
 
463
      <listitem>
 
464
       <para>
 
465
        UNION (&cup;): builds the set-theoretic union of two
 
466
        tables. Given the tables <classname>R</classname> and
 
467
        <classname>S</classname> (both must have the same arity),
 
468
        the union <classname>R</classname> &cup; <classname>S</classname>
 
469
        is the set of tuples that are in <classname>R</classname>
 
470
        or <classname>S</classname> or both.
 
471
       </para>
 
472
      </listitem>
 
473
 
 
474
      <listitem>
 
475
       <para>
 
476
        INTERSECT (&cap;): builds the set-theoretic intersection of two
 
477
        tables. Given the tables <classname>R</classname> and
 
478
        <classname>S</classname>,
 
479
        <classname>R</classname> &cap; <classname>S</classname> is the
 
480
        set of tuples
 
481
        that are in <classname>R</classname> and in
 
482
        <classname>S</classname>.
 
483
        We again require that <classname>R</classname> and 
 
484
        <classname>S</classname> have the
 
485
        same arity.
 
486
       </para>
 
487
      </listitem>
 
488
 
 
489
      <listitem>
 
490
       <para>
 
491
        DIFFERENCE (&minus; or &setmn;): builds the set difference of
 
492
        two tables. Let <classname>R</classname> and <classname>S</classname>
 
493
        again be two tables with the same
 
494
        arity. <classname>R</classname> - <classname>S</classname>
 
495
        is the set of tuples in <classname>R</classname> but not in
 
496
        <classname>S</classname>.
 
497
       </para>
 
498
      </listitem>
 
499
 
 
500
      <listitem>
 
501
       <para>
 
502
        JOIN (&prod;): connects two tables by their common
 
503
        attributes. Let <classname>R</classname> be a table with the 
 
504
        attributes <classname>A</classname>,<classname>B</classname> 
 
505
        and <classname>C</classname> and
 
506
        let <classname>S</classname> be a table with the attributes
 
507
        <classname>C</classname>,<classname>D</classname>
 
508
        and <classname>E</classname>. There is one
 
509
        attribute common to both relations,
 
510
        the attribute <classname>C</classname>. 
 
511
<!--
 
512
        <classname>R</classname> &prod; <classname>S</classname> =
 
513
        &pi;<subscript><classname>R</classname>.<classname>A</classname>,<classname>R</classname>.<classname>B</classname>,<classname>R</classname>.<classname>C</classname>,<classname>S</classname>.<classname>D</classname>,<classname>S</classname>.<classname>E</classname></subscript>(&sigma;<subscript><classname>R</classname>.<classname>C</classname>=<classname>S</classname>.<classname>C</classname></subscript>(<classname>R</classname> &times; <classname>S</classname>)).
 
514
-->
 
515
        R &prod; S = &pi;<subscript>R.A,R.B,R.C,S.D,S.E</subscript>(&sigma;<subscript>R.C=S.C</subscript>(R &times; S)).
 
516
        What are we doing here? We first calculate the Cartesian
 
517
        product
 
518
        <classname>R</classname> &times; <classname>S</classname>.
 
519
        Then we select those tuples whose values for the common
 
520
        attribute <classname>C</classname> are equal
 
521
        (&sigma;<subscript>R.C = S.C</subscript>).
 
522
        Now we have a table
 
523
        that contains the attribute <classname>C</classname>
 
524
        two times and we correct this by
 
525
        projecting out the duplicate column.
 
526
       </para>
 
527
 
 
528
       <example>
 
529
        <title id="join-example">An Inner Join</title>
 
530
 
 
531
        <para>
 
532
         Let's have a look at the tables that are produced by evaluating the steps
 
533
         necessary for a join.
 
534
         Let the following two tables be given:
 
535
 
 
536
         <programlisting>
 
537
R:                 S:
 
538
 A | B | C          C | D | E
 
539
---+---+---        ---+---+---
 
540
 1 | 2 | 3          3 | a | b
 
541
 4 | 5 | 6          6 | c | d
 
542
 7 | 8 | 9
 
543
         </programlisting>
 
544
        </para>
 
545
       </example>
 
546
 
 
547
       <para>
 
548
        First we calculate the Cartesian product
 
549
        <classname>R</classname> &times; <classname>S</classname> and
 
550
        get:
 
551
 
 
552
        <programlisting>
 
553
R x S:
 
554
 A | B | R.C | S.C | D | E
 
555
---+---+-----+-----+---+---
 
556
 1 | 2 |  3  |  3  | a | b
 
557
 1 | 2 |  3  |  6  | c | d
 
558
 4 | 5 |  6  |  3  | a | b
 
559
 4 | 5 |  6  |  6  | c | d
 
560
 7 | 8 |  9  |  3  | a | b
 
561
 7 | 8 |  9  |  6  | c | d
 
562
        </programlisting>
 
563
       </para>
 
564
 
 
565
       <para>
 
566
        After the selection
 
567
        &sigma;<subscript>R.C=S.C</subscript>(R &times; S)
 
568
        we get:
 
569
 
 
570
        <programlisting>
 
571
 A | B | R.C | S.C | D | E
 
572
---+---+-----+-----+---+---
 
573
 1 | 2 |  3  |  3  | a | b
 
574
 4 | 5 |  6  |  6  | c | d
 
575
        </programlisting>
 
576
       </para>
 
577
 
 
578
       <para>
 
579
        To remove the duplicate column
 
580
        <classname>S</classname>.<classname>C</classname>
 
581
        we project it out by the following operation:
 
582
        &pi;<subscript>R.A,R.B,R.C,S.D,S.E</subscript>(&sigma;<subscript>R.C=S.C</subscript>(R &times; S))
 
583
        and get:
 
584
 
 
585
        <programlisting>
 
586
 A | B | C | D | E
 
587
---+---+---+---+---
 
588
 1 | 2 | 3 | a | b
 
589
 4 | 5 | 6 | c | d
 
590
        </programlisting>
 
591
       </para>
 
592
      </listitem>
 
593
 
 
594
      <listitem>
 
595
       <para>
 
596
        DIVIDE (&divide;): Let <classname>R</classname> be a table
 
597
        with the attributes A, B, C, and D and let
 
598
        <classname>S</classname> be a table with the attributes
 
599
        C and D.
 
600
        Then we define the division as:
 
601
 
 
602
        <programlisting>
 
603
R &divide; S = {t &mid; &forall; t<subscript>s</subscript> &isin; S &exist; t<subscript>r</subscript> &isin; R
 
604
        </programlisting>
 
605
 
 
606
        such that
 
607
t<subscript>r</subscript>(A,B)=t&and;t<subscript>r</subscript>(C,D)=t<subscript>s</subscript>}
 
608
        where
 
609
        t<subscript>r</subscript>(x,y)
 
610
        denotes a
 
611
        tuple of table <classname>R</classname> that consists only of
 
612
        the components <literal>x</literal> and <literal>y</literal>.
 
613
        Note that the tuple <literal>t</literal> only consists of the
 
614
        components <classname>A</classname> and
 
615
        <classname>B</classname> of relation <classname>R</classname>.
 
616
       </para>
 
617
 
 
618
       <para id="divide-example">
 
619
        Given the following tables
 
620
 
 
621
        <programlisting>
 
622
R:                    S:
 
623
 A | B | C | D         C | D
 
624
---+---+---+---       ---+---
 
625
 a | b | c | d         c | d
 
626
 a | b | e | f         e | f
 
627
 b | c | e | f
 
628
 e | d | c | d
 
629
 e | d | e | f
 
630
 a | b | d | e
 
631
        </programlisting>
 
632
 
 
633
        R &divide; S
 
634
        is derived as
 
635
 
 
636
        <programlisting>
 
637
 A | B
 
638
---+---
 
639
 a | b
 
640
 e | d
 
641
        </programlisting>
 
642
       </para>
 
643
      </listitem>
 
644
     </itemizedlist>
 
645
    </para>
 
646
 
 
647
    <para>
 
648
     For a more detailed description and definition of the relational
 
649
     algebra refer to [<xref linkend="ULL88" endterm="ULL88">] or
 
650
     [<xref linkend="DATE94" endterm="DATE94">].
 
651
    </para>
 
652
 
 
653
    <example>
 
654
     <title id="suppl-rel-alg">A Query Using Relational Algebra</title>
 
655
     <para>
 
656
      Recall that we formulated all those relational operators to be able to
 
657
      retrieve data from the database. Let's return to our example from 
 
658
      the previous
 
659
      section (<xref linkend="operations" endterm="operations">)
 
660
      where someone wanted to know the names of all
 
661
      suppliers that sell the part <literal>Screw</literal>. 
 
662
      This question can be answered
 
663
      using relational algebra by the following operation:
 
664
 
 
665
      <programlisting>
 
666
&pi;<subscript>SUPPLIER.SNAME</subscript>(&sigma;<subscript>PART.PNAME='Screw'</subscript>(SUPPLIER &prod; SELLS &prod; PART))
 
667
      </programlisting>
 
668
     </para>
 
669
 
 
670
     <para>
 
671
      We call such an operation a query. If we evaluate the above query
 
672
      against the our example tables
 
673
      (<xref linkend="supplier-fig" endterm="supplier-fig">)
 
674
      we will obtain the following result:
 
675
 
 
676
      <programlisting>
 
677
 SNAME
 
678
-------
 
679
 Smith
 
680
 Adams
 
681
      </programlisting>
 
682
     </para>
 
683
    </example>
 
684
   </sect2>
 
685
 
 
686
   <sect2 id="rel-calc">
 
687
    <title>Relational Calculus</title>
 
688
 
 
689
    <para>
 
690
     The relational calculus is based on the
 
691
     <firstterm>first order logic</firstterm>. There are
 
692
     two variants of the relational calculus:
 
693
 
 
694
     <itemizedlist>
 
695
      <listitem>
 
696
       <para>
 
697
        The <firstterm>Domain Relational Calculus</firstterm>
 
698
        (<acronym>DRC</acronym>), where variables
 
699
        stand for components (attributes) of the tuples.
 
700
       </para>
 
701
      </listitem>
 
702
 
 
703
      <listitem>
 
704
       <para>
 
705
        The <firstterm>Tuple Relational Calculus</firstterm>
 
706
        (<acronym>TRC</acronym>), where variables stand for tuples.
 
707
       </para>
 
708
      </listitem>
 
709
     </itemizedlist>
 
710
    </para>
 
711
 
 
712
    <para>
 
713
     We want to discuss the tuple relational calculus only because it is
 
714
     the one underlying the most relational languages. For a detailed
 
715
     discussion on <acronym>DRC</acronym> (and also
 
716
     <acronym>TRC</acronym>) see
 
717
     <xref linkend="DATE94" endterm="DATE94">
 
718
     or
 
719
     <xref linkend="ULL88" endterm="ULL88">.
 
720
    </para>
 
721
   </sect2>
 
722
 
 
723
   <sect2>
 
724
    <title>Tuple Relational Calculus</title>
 
725
 
 
726
    <para>
 
727
     The queries used in <acronym>TRC</acronym> are of the following
 
728
     form:
 
729
 
 
730
     <programlisting>
 
731
x(A) &mid; F(x)
 
732
     </programlisting>
 
733
 
 
734
     where <literal>x</literal> is a tuple variable
 
735
     <classname>A</classname> is a set of attributes and <literal>F</literal> is a
 
736
     formula. The resulting relation consists of all tuples
 
737
     <literal>t(A)</literal> that satisfy <literal>F(t)</literal>.
 
738
    </para>
 
739
 
 
740
    <para>
 
741
     If we want to answer the question from example
 
742
     <xref linkend="suppl-rel-alg" endterm="suppl-rel-alg">
 
743
     using <acronym>TRC</acronym> we formulate the following query:
 
744
 
 
745
     <programlisting>
 
746
{x(SNAME) &mid; x &isin; SUPPLIER &and;
 
747
    &exist; y &isin; SELLS &exist; z &isin; PART (y(SNO)=x(SNO) &and;
 
748
    z(PNO)=y(PNO) &and;
 
749
    z(PNAME)='Screw')}
 
750
     </programlisting>
 
751
    </para>
 
752
 
 
753
    <para>
 
754
     Evaluating the query against the tables from
 
755
     <xref linkend="supplier-fig" endterm="supplier-fig">
 
756
     again leads to the same result
 
757
     as in
 
758
     <xref linkend="suppl-rel-alg" endterm="suppl-rel-alg">.
 
759
    </para>
 
760
   </sect2>
 
761
 
 
762
   <sect2 id="alg-vs-calc">
 
763
    <title>Relational Algebra vs. Relational Calculus</title>
 
764
 
 
765
    <para>
 
766
     The relational algebra and the relational calculus have the same
 
767
     <firstterm>expressive power</firstterm>; i.e. all queries that
 
768
     can be formulated using relational algebra can also be formulated 
 
769
     using the relational calculus and vice versa.
 
770
     This was first proved by E. F. Codd in
 
771
     1972. This proof is based on an algorithm (<quote>Codd's reduction
 
772
     algorithm</quote>) by which an arbitrary expression of the relational
 
773
     calculus can be reduced to a semantically equivalent expression of
 
774
     relational algebra. For a more detailed discussion on that refer to
 
775
     <xref linkend="DATE94" endterm="DATE94">
 
776
     and
 
777
     <xref linkend="ULL88" endterm="ULL88">.
 
778
    </para>
 
779
 
 
780
    <para>
 
781
     It is sometimes said that languages based on the relational
 
782
     calculus are <quote>higher level</quote> or <quote>more
 
783
     declarative</quote> than languages based on relational algebra
 
784
     because the algebra (partially) specifies the order of operations
 
785
     while the calculus leaves it to a compiler or interpreter to
 
786
     determine the most efficient order of evaluation.
 
787
    </para>
 
788
   </sect2>
 
789
  </sect1>
 
790
 
 
791
  <sect1 id="sql-language">
 
792
   <title>The <acronym>SQL</acronym> Language</title>
 
793
 
 
794
   <para>
 
795
    As is the case with most modern relational languages,
 
796
    <acronym>SQL</acronym> is based on the tuple
 
797
    relational calculus. As a result every query that can be formulated
 
798
    using the tuple relational calculus (or equivalently, relational
 
799
    algebra) can also be formulated using
 
800
    <acronym>SQL</acronym>. There are, however,
 
801
    capabilities beyond the scope of relational algebra or calculus. Here
 
802
    is a list of some additional features provided by
 
803
    <acronym>SQL</acronym> that are not
 
804
    part of relational algebra or calculus:
 
805
 
 
806
    <itemizedlist>
 
807
     <listitem>
 
808
      <para>
 
809
       Commands for insertion, deletion or modification of data.
 
810
      </para>
 
811
     </listitem>
 
812
 
 
813
     <listitem>
 
814
      <para>
 
815
       Arithmetic capability: In <acronym>SQL</acronym> it is possible
 
816
       to involve
 
817
       arithmetic operations as well as comparisons, e.g.
 
818
 
 
819
       <programlisting>
 
820
A &lt; B + 3.
 
821
       </programlisting>
 
822
 
 
823
       Note
 
824
       that + or other arithmetic operators appear neither in relational
 
825
       algebra nor in relational calculus.
 
826
      </para>
 
827
     </listitem>
 
828
 
 
829
     <listitem>
 
830
      <para>
 
831
       Assignment and Print Commands: It is possible to print a
 
832
       relation constructed by a query and to assign a computed relation to a
 
833
       relation name.
 
834
      </para>
 
835
     </listitem>
 
836
 
 
837
     <listitem>
 
838
      <para>
 
839
       Aggregate Functions: Operations such as
 
840
       <firstterm>average</firstterm>, <firstterm>sum</firstterm>,
 
841
       <firstterm>max</firstterm>, etc. can be applied to columns of a 
 
842
       relation to
 
843
       obtain a single quantity.
 
844
      </para>
 
845
     </listitem>
 
846
    </itemizedlist>
 
847
   </para>
 
848
 
 
849
   <sect2 id="select">
 
850
    <title id="select-title">Select</title>
 
851
 
 
852
    <para>
 
853
     The most often used command in <acronym>SQL</acronym> is the
 
854
     <command>SELECT</command> statement,
 
855
     used to retrieve data. The syntax is:
 
856
 
 
857
     <synopsis>
 
858
SELECT [ ALL | DISTINCT [ ON ( <replaceable class="PARAMETER">expression</replaceable> [, ...] ) ] ]
 
859
    * | <replaceable class="PARAMETER">expression</replaceable> [ AS <replaceable class="PARAMETER">output_name</replaceable> ] [, ...]
 
860
    [ INTO [ TEMPORARY | TEMP ] [ TABLE ] <replaceable class="PARAMETER">new_table</replaceable> ]
 
861
    [ FROM <replaceable class="PARAMETER">from_item</replaceable> [, ...] ]
 
862
    [ WHERE <replaceable class="PARAMETER">condition</replaceable> ]
 
863
    [ GROUP BY <replaceable class="PARAMETER">expression</replaceable> [, ...] ]
 
864
    [ HAVING <replaceable class="PARAMETER">condition</replaceable> [, ...] ]
 
865
    [ { UNION | INTERSECT | EXCEPT } [ ALL ] <replaceable class="PARAMETER">select</replaceable> ]
 
866
    [ ORDER BY <replaceable class="PARAMETER">expression</replaceable> [ ASC | DESC | USING <replaceable class="PARAMETER">operator</replaceable> ] [, ...] ]
 
867
    [ LIMIT { <replaceable class="PARAMETER">count</replaceable> | ALL } ]
 
868
    [ OFFSET <replaceable class="PARAMETER">start</replaceable> ]
 
869
    [ FOR UPDATE [ OF <replaceable class="PARAMETER">class_name</replaceable> [, ...] ] ]
 
870
     </synopsis>
 
871
    </para>
 
872
 
 
873
    <para>
 
874
     Now we will illustrate the complex syntax of the
 
875
     <command>SELECT</command> statement with various examples. The
 
876
     tables used for the examples are defined in <xref
 
877
     linkend="supplier-fig" endterm="supplier-fig">.
 
878
    </para>
 
879
 
 
880
    <sect3>
 
881
     <title>Simple Selects</title>
 
882
 
 
883
     <para>
 
884
      Here are some simple examples using a <command>SELECT</command> statement:
 
885
 
 
886
      <example>
 
887
       <title id="simple-query">Simple Query with Qualification</title>
 
888
       <para>
 
889
        To retrieve all tuples from table PART where the attribute PRICE is
 
890
        greater than 10 we formulate the following query:
 
891
 
 
892
        <programlisting>
 
893
SELECT * FROM PART
 
894
    WHERE PRICE &gt; 10;
 
895
        </programlisting>
 
896
 
 
897
        and get the table:
 
898
 
 
899
        <programlisting>
 
900
 PNO |  PNAME  |  PRICE
 
901
-----+---------+--------
 
902
  3  |  Bolt   |   15
 
903
  4  |  Cam    |   25
 
904
        </programlisting>
 
905
       </para>
 
906
 
 
907
       <para>
 
908
        Using <quote>*</quote> in the <command>SELECT</command> statement
 
909
        will deliver all attributes from the table. If we want to retrieve
 
910
        only the attributes PNAME and PRICE from table PART we use the
 
911
        statement:
 
912
 
 
913
        <programlisting>
 
914
SELECT PNAME, PRICE 
 
915
    FROM PART
 
916
    WHERE PRICE &gt; 10;
 
917
        </programlisting>
 
918
 
 
919
        In this case the result is:
 
920
 
 
921
        <programlisting>
 
922
                      PNAME  |  PRICE
 
923
                     --------+--------
 
924
                      Bolt   |   15
 
925
                      Cam    |   25
 
926
        </programlisting>
 
927
 
 
928
        Note that the <acronym>SQL</acronym> <command>SELECT</command>
 
929
        corresponds to the <quote>projection</quote> in relational algebra
 
930
        not to the <quote>selection</quote> (see <xref linkend="rel-alg"
 
931
        endterm="rel-alg"> for more details).
 
932
       </para>
 
933
 
 
934
       <para>
 
935
        The qualifications in the WHERE clause can also be logically connected
 
936
        using the keywords OR, AND, and NOT:
 
937
 
 
938
        <programlisting>
 
939
SELECT PNAME, PRICE 
 
940
    FROM PART
 
941
    WHERE PNAME = 'Bolt' AND
 
942
         (PRICE = 0 OR PRICE &lt;= 15);
 
943
        </programlisting>
 
944
 
 
945
        will lead to the result:
 
946
 
 
947
        <programlisting>
 
948
 PNAME  |  PRICE
 
949
--------+--------
 
950
 Bolt   |   15
 
951
        </programlisting>
 
952
       </para>
 
953
 
 
954
       <para>
 
955
        Arithmetic operations may be used in the target list and in the WHERE
 
956
        clause. For example if we want to know how much it would cost if we
 
957
        take two pieces of a part we could use the following query:
 
958
 
 
959
        <programlisting>
 
960
SELECT PNAME, PRICE * 2 AS DOUBLE
 
961
    FROM PART
 
962
    WHERE PRICE * 2 &lt; 50;
 
963
        </programlisting>
 
964
 
 
965
        and we get:
 
966
 
 
967
        <programlisting>
 
968
 PNAME  |  DOUBLE
 
969
--------+---------
 
970
 Screw  |    20
 
971
 Nut    |    16
 
972
 Bolt   |    30
 
973
        </programlisting>
 
974
 
 
975
        Note that the word DOUBLE after the keyword AS is the new title of the
 
976
        second column. This technique can be used for every element of the
 
977
        target list to assign a new title to the resulting
 
978
        column. This new title
 
979
        is often referred to as alias. The alias cannot be used throughout the
 
980
        rest of the query.
 
981
       </para>
 
982
      </example>
 
983
     </para>
 
984
    </sect3>
 
985
 
 
986
    <sect3>
 
987
     <title>Joins</title>
 
988
 
 
989
     <para id="simple-join">
 
990
      The following example shows how <firstterm>joins</firstterm> are
 
991
      realized in <acronym>SQL</acronym>.
 
992
     </para>
 
993
 
 
994
     <para>
 
995
      To join the three tables SUPPLIER, PART and SELLS over their common
 
996
      attributes we formulate the following statement:
 
997
 
 
998
      <programlisting>
 
999
SELECT S.SNAME, P.PNAME
 
1000
    FROM SUPPLIER S, PART P, SELLS SE
 
1001
    WHERE S.SNO = SE.SNO AND
 
1002
          P.PNO = SE.PNO;
 
1003
      </programlisting>
 
1004
 
 
1005
      and get the following table as a result:
 
1006
 
 
1007
      <programlisting>
 
1008
 SNAME | PNAME
 
1009
-------+-------
 
1010
 Smith | Screw
 
1011
 Smith | Nut
 
1012
 Jones | Cam
 
1013
 Adams | Screw
 
1014
 Adams | Bolt
 
1015
 Blake | Nut
 
1016
 Blake | Bolt
 
1017
 Blake | Cam
 
1018
      </programlisting>
 
1019
     </para>
 
1020
 
 
1021
     <para>
 
1022
      In the FROM clause we introduced an alias name for every relation
 
1023
      because there are common named attributes (SNO and PNO) among the
 
1024
      relations. Now we can distinguish between the common named attributes
 
1025
      by simply prefixing the attribute name with the alias name followed by
 
1026
      a dot. The join is calculated in the same way as shown in 
 
1027
      <xref linkend="join-example" endterm="join-example">.
 
1028
      First the Cartesian product
 
1029
 
 
1030
      SUPPLIER &times; PART &times; SELLS
 
1031
 
 
1032
      is derived. Now only those tuples satisfying the
 
1033
      conditions given in the WHERE clause are selected (i.e. the common
 
1034
      named attributes have to be equal). Finally we project out all
 
1035
      columns but S.SNAME and P.PNAME. 
 
1036
     </para>
 
1037
 
 
1038
         <para>
 
1039
         Another way to perform joins is to use the SQL JOIN syntax as follows:
 
1040
         <programlisting>
 
1041
select sname, pname from supplier
 
1042
        JOIN sells USING (sno)
 
1043
        JOIN part USING (pno);
 
1044
        </programlisting>
 
1045
        giving again:
 
1046
        <programlisting>
 
1047
 sname | pname
 
1048
-------+-------
 
1049
 Smith | Screw
 
1050
 Adams | Screw
 
1051
 Smith | Nut
 
1052
 Blake | Nut
 
1053
 Adams | Bolt
 
1054
 Blake | Bolt
 
1055
 Jones | Cam
 
1056
 Blake | Cam
 
1057
(8 rows) 
 
1058
         </programlisting>
 
1059
         </para>
 
1060
 
 
1061
         <para>
 
1062
         A joined table, created using JOIN syntax, is a table reference list
 
1063
         item that occurs in a FROM clause and before any WHERE, GROUP BY,
 
1064
         or HAVING clause.  Other table references, including table names or
 
1065
         other JOIN clauses, may be included in the FROM clause if separated
 
1066
         by commas.  JOINed tables are logically like any other
 
1067
         table listed in the FROM clause.
 
1068
         </para>
 
1069
 
 
1070
         <para>
 
1071
          SQL JOINs come in two main types, CROSS JOINs (unqualified joins)
 
1072
          and <firstterm>qualified JOINs</>.  Qualified joins can be further
 
1073
          subdivided based on the way in which the <firstterm>join condition</>
 
1074
          is specified (ON, USING, or NATURAL) and the way in which it is
 
1075
          applied (INNER or OUTER join).
 
1076
         </para>
 
1077
 
 
1078
    <variablelist>
 
1079
        <title>Join Types</title>
 
1080
        <varlistentry>
 
1081
            <term>CROSS JOIN</term>
 
1082
                <listitem>
 
1083
                        <cmdsynopsis>
 
1084
                            <arg choice="req"> <replaceable class="parameter">T1</replaceable> </arg>
 
1085
                            <command> CROSS JOIN </command>
 
1086
                            <arg choice="req"> <replaceable class="parameter">T2</replaceable> </arg>
 
1087
            </cmdsynopsis>
 
1088
 
 
1089
                        <para>
 
1090
                        A cross join takes two tables T1 and T2 having N and M rows
 
1091
                        respectively, and returns a joined table containing all
 
1092
                        N*M possible joined rows. For each row R1 of T1, each row
 
1093
                        R2 of T2 is joined with R1 to yield a joined table row JR
 
1094
                        consisting of all fields in R1 and R2. A CROSS JOIN is
 
1095
                        equivalent to an INNER JOIN ON TRUE.
 
1096
                        </para>
 
1097
                        </listitem>
 
1098
                </varlistentry>
 
1099
 
 
1100
                <varlistentry>
 
1101
                    <term>Qualified JOINs</term>
 
1102
                    <listitem>
 
1103
 
 
1104
                        <cmdsynopsis>
 
1105
                        <arg choice="req"> <replaceable class="parameter">T1</replaceable> </arg>
 
1106
                        <arg choice="opt"> NATURAL </arg>
 
1107
                        <group choice="opt">
 
1108
                                <arg choice="opt"> INNER </arg>
 
1109
                                <arg>
 
1110
                                <group choice="req">
 
1111
                                        <arg choice="plain"> LEFT </arg>
 
1112
                                        <arg choice="plain"> RIGHT </arg>
 
1113
                                        <arg choice="plain"> FULL </arg>
 
1114
                                </group>
 
1115
                                <arg choice="opt"> OUTER </arg>
 
1116
                                </arg>
 
1117
                        </group>
 
1118
                        <command> JOIN </command>
 
1119
                        <arg choice="req"> <replaceable class="parameter">T2</replaceable> </arg>
 
1120
                        <group choice="req">
 
1121
                                <arg> ON <replaceable>search condition</replaceable></arg>
 
1122
                                <arg> USING ( <replaceable>join column list</replaceable> ) </arg>
 
1123
                        </group>
 
1124
                        </cmdsynopsis>
 
1125
 
 
1126
                        <para>
 
1127
                        A qualified JOIN must specify its join condition
 
1128
                        by providing one (and only one) of NATURAL, ON, or
 
1129
                        USING.  The ON clause
 
1130
                        takes a <replaceable>search condition</replaceable>,
 
1131
                        which is the same as in a WHERE clause.  The USING
 
1132
                        clause takes a comma-separated list of column names,
 
1133
                        which the joined tables must have in common, and joins
 
1134
                        the tables on equality of those columns.  NATURAL is
 
1135
                        shorthand for a USING clause that lists all the common
 
1136
                        column names of the two tables.  A side-effect of both
 
1137
                        USING and NATURAL is that only one copy of each joined
 
1138
                        column is emitted into the result table (compare the
 
1139
                        relational-algebra definition of JOIN, shown earlier).
 
1140
                        </para>
 
1141
 
 
1142
                        <!-- begin join semantics -->
 
1143
                        <variablelist>
 
1144
                        <varlistentry>
 
1145
                                <term>
 
1146
                                        <cmdsynopsis>
 
1147
                                                <arg> INNER </arg>
 
1148
                                                <command> JOIN </command>
 
1149
                                        </cmdsynopsis>
 
1150
                                </term>
 
1151
                                <listitem>
 
1152
                                <para>
 
1153
                                For each row R1 of T1, the joined table has a row for each row
 
1154
                                in T2 that satisfies the join condition with R1. 
 
1155
                                </para>
 
1156
                                <tip>
 
1157
                                <para>
 
1158
                                        The words INNER and OUTER are optional for all JOINs.
 
1159
                                        INNER is the default.  LEFT, RIGHT, and FULL imply an
 
1160
                                        OUTER JOIN.
 
1161
                                        </para>
 
1162
                                </tip>
 
1163
                                </listitem>
 
1164
                </varlistentry>
 
1165
                        <varlistentry>
 
1166
                                <term>
 
1167
                                        <cmdsynopsis>
 
1168
                                                <arg choice="plain"> LEFT </arg>
 
1169
                                                <arg> OUTER </arg>
 
1170
                                                <command> JOIN </command>
 
1171
                                        </cmdsynopsis>
 
1172
                        </term>
 
1173
                                <listitem>
 
1174
                                <para>
 
1175
                First, an INNER JOIN is performed.
 
1176
                Then, for each row in T1 that does not satisfy the join
 
1177
                                condition with any row in T2, an additional joined row is
 
1178
                                returned with null fields in the columns from T2.
 
1179
                                </para>
 
1180
                                <tip>
 
1181
                                        <para>
 
1182
                                        The joined table unconditionally has a row for each row in T1.
 
1183
                                        </para>
 
1184
                                </tip>
 
1185
                                </listitem>
 
1186
                        </varlistentry>
 
1187
                        <varlistentry>
 
1188
                                <term>
 
1189
                                        <cmdsynopsis>
 
1190
                                                <arg choice="plain"> RIGHT </arg>
 
1191
                                                <arg> OUTER </arg>
 
1192
                                                <command> JOIN </command>
 
1193
                                </cmdsynopsis>
 
1194
                        </term>
 
1195
                                <listitem>
 
1196
                                <para>
 
1197
                First, an INNER JOIN is performed.
 
1198
                Then, for each row in T2 that does not satisfy the join
 
1199
                                condition with any row in T1, an additional joined row is
 
1200
                                returned with null fields in the columns from T1.
 
1201
                                </para>
 
1202
                                <tip>
 
1203
                                        <para>
 
1204
                                        The joined table unconditionally has a row for each row in T2.
 
1205
                                        </para>
 
1206
                                </tip>
 
1207
                                </listitem>
 
1208
                </varlistentry>
 
1209
                        <varlistentry>
 
1210
                                <term>
 
1211
                                        <cmdsynopsis>
 
1212
                                                <arg choice="plain"> FULL </arg>
 
1213
                                                <arg> OUTER </arg>
 
1214
                                                <command> JOIN </command>
 
1215
                                </cmdsynopsis>
 
1216
                        </term>
 
1217
                <listitem>
 
1218
                                <para>
 
1219
                First, an INNER JOIN is performed.
 
1220
                Then, for each row in T1 that does not satisfy the join
 
1221
                                condition with any row in T2, an additional joined row is
 
1222
                                returned with null fields in the columns from T2.
 
1223
                Also, for each row in T2 that does not satisfy the join
 
1224
                                condition with any row in T1, an additional joined row is
 
1225
                                returned with null fields in the columns from T1.
 
1226
                                </para>
 
1227
                                <tip>
 
1228
                                        <para>
 
1229
                                The joined table unconditionally has a row for every row of T1
 
1230
                                        and a row for every row of T2.
 
1231
                                        </para>
 
1232
                                </tip>
 
1233
                                </listitem>
 
1234
                </varlistentry>
 
1235
                        </variablelist>
 
1236
                        <!-- end join semantics -->
 
1237
 
 
1238
                        </listitem>
 
1239
        </varlistentry>
 
1240
         </variablelist>
 
1241
 
 
1242
         <para>
 
1243
         JOINs of all types can be chained together or nested where either or both of
 
1244
         <replaceable class="parameter">T1</replaceable> and
 
1245
         <replaceable class="parameter">T2</replaceable> may be JOINed tables.
 
1246
         Parenthesis can be used around JOIN clauses to control the order
 
1247
         of JOINs which are otherwise processed left to right.
 
1248
         </para>
 
1249
 
 
1250
    </sect3>
 
1251
 
 
1252
    <sect3>
 
1253
     <title id="aggregates-tutorial">Aggregate Operators</title>
 
1254
 
 
1255
     <para>
 
1256
      <acronym>SQL</acronym> provides aggregate operators (e.g. AVG,
 
1257
      COUNT, SUM, MIN, MAX) that take an expression as argument.  The
 
1258
      expression is evaluated at each row that satisfies the WHERE
 
1259
      clause, and the aggregate operator is calculated over this set
 
1260
      of input values.  Normally, an aggregate delivers a single
 
1261
      result for a whole <command>SELECT</command> statement.  But if
 
1262
      grouping is specified in the query, then a separate calculation
 
1263
      is done over the rows of each group, and an aggregate result is
 
1264
      delivered per group (see next section).
 
1265
 
 
1266
      <example>
 
1267
       <title id="aggregates-example">Aggregates</title>
 
1268
 
 
1269
       <para>
 
1270
        If we want to know the average cost of all parts in table PART we use
 
1271
        the following query:
 
1272
 
 
1273
        <programlisting>
 
1274
SELECT AVG(PRICE) AS AVG_PRICE
 
1275
    FROM PART;
 
1276
        </programlisting>
 
1277
       </para>
 
1278
 
 
1279
       <para>
 
1280
        The result is:
 
1281
 
 
1282
        <programlisting>
 
1283
 AVG_PRICE
 
1284
-----------
 
1285
   14.5
 
1286
        </programlisting>
 
1287
       </para>
 
1288
 
 
1289
       <para>
 
1290
        If we want to know how many parts are defined in table PART we use
 
1291
        the statement:
 
1292
 
 
1293
        <programlisting>
 
1294
SELECT COUNT(PNO)
 
1295
    FROM PART;
 
1296
        </programlisting>
 
1297
 
 
1298
        and get:
 
1299
 
 
1300
        <programlisting>
 
1301
 COUNT
 
1302
-------
 
1303
   4
 
1304
        </programlisting>
 
1305
 
 
1306
       </para>
 
1307
      </example>
 
1308
     </para>
 
1309
    </sect3>
 
1310
 
 
1311
    <sect3>
 
1312
     <title>Aggregation by Groups</title>
 
1313
 
 
1314
     <para>
 
1315
      <acronym>SQL</acronym> allows one to partition the tuples of a table
 
1316
      into groups. Then the
 
1317
      aggregate operators described above can be applied to the groups &mdash;
 
1318
      i.e. the value of the aggregate operator is no longer calculated over
 
1319
      all the values of the specified column but over all values of a
 
1320
      group. Thus the aggregate operator is evaluated separately for every
 
1321
      group.
 
1322
     </para>
 
1323
 
 
1324
     <para>
 
1325
      The partitioning of the tuples into groups is done by using the
 
1326
      keywords <command>GROUP BY</command> followed by a list of
 
1327
      attributes that define the
 
1328
      groups. If we have 
 
1329
      <command>GROUP BY A<subscript>1</subscript>, &tdot;, A<subscript>k</subscript></command>
 
1330
      we partition
 
1331
      the relation into groups, such that two tuples are in the same group
 
1332
      if and only if they agree on all the attributes 
 
1333
      A<subscript>1</subscript>, &tdot;, A<subscript>k</subscript>.
 
1334
 
 
1335
      <example>
 
1336
       <title id="aggregates-groupby">Aggregates</title>
 
1337
       <para>
 
1338
        If we want to know how many parts are sold by every supplier we
 
1339
        formulate the query:
 
1340
 
 
1341
        <programlisting>
 
1342
SELECT S.SNO, S.SNAME, COUNT(SE.PNO)
 
1343
    FROM SUPPLIER S, SELLS SE
 
1344
    WHERE S.SNO = SE.SNO
 
1345
    GROUP BY S.SNO, S.SNAME;
 
1346
        </programlisting>
 
1347
 
 
1348
        and get:
 
1349
 
 
1350
        <programlisting>
 
1351
 SNO | SNAME | COUNT
 
1352
-----+-------+-------
 
1353
  1  | Smith |   2
 
1354
  2  | Jones |   1
 
1355
  3  | Adams |   2
 
1356
  4  | Blake |   3
 
1357
        </programlisting>
 
1358
       </para>
 
1359
 
 
1360
       <para>
 
1361
        Now let's have a look of what is happening here.
 
1362
        First the join of the
 
1363
        tables SUPPLIER and SELLS is derived:
 
1364
 
 
1365
        <programlisting>
 
1366
 S.SNO | S.SNAME | SE.PNO
 
1367
-------+---------+--------
 
1368
   1   |  Smith  |   1
 
1369
   1   |  Smith  |   2
 
1370
   2   |  Jones  |   4
 
1371
   3   |  Adams  |   1
 
1372
   3   |  Adams  |   3
 
1373
   4   |  Blake  |   2
 
1374
   4   |  Blake  |   3
 
1375
   4   |  Blake  |   4
 
1376
        </programlisting>
 
1377
       </para>
 
1378
 
 
1379
       <para>
 
1380
        Next we partition the tuples into groups by putting all tuples
 
1381
        together that agree on both attributes S.SNO and S.SNAME:
 
1382
 
 
1383
        <programlisting>
 
1384
 S.SNO | S.SNAME | SE.PNO
 
1385
-------+---------+--------
 
1386
   1   |  Smith  |   1
 
1387
                 |   2
 
1388
--------------------------
 
1389
   2   |  Jones  |   4
 
1390
--------------------------
 
1391
   3   |  Adams  |   1
 
1392
                 |   3
 
1393
--------------------------
 
1394
   4   |  Blake  |   2
 
1395
                 |   3
 
1396
                 |   4
 
1397
        </programlisting>
 
1398
       </para>
 
1399
 
 
1400
       <para>
 
1401
        In our example we got four groups and now we can apply the aggregate
 
1402
        operator COUNT to every group leading to the final result of the query
 
1403
        given above.
 
1404
       </para>
 
1405
      </example>
 
1406
     </para>
 
1407
 
 
1408
     <para>
 
1409
      Note that for a query using GROUP BY and aggregate
 
1410
      operators to make sense the target list can only refer directly to
 
1411
      the attributes being grouped by.  Other attributes may only be used
 
1412
      inside the argument of an aggregate function.  Otherwise there would
 
1413
      not be a unique value to associate with the other attributes.
 
1414
     </para>
 
1415
 
 
1416
     <para>
 
1417
      Also observe that it makes no sense to ask for an aggregate of
 
1418
      an aggregate, e.g., AVG(MAX(sno)), because a
 
1419
      <command>SELECT</command> only does one pass of grouping and
 
1420
      aggregation.  You can get a result of this kind by using a
 
1421
      temporary table or a sub-SELECT in the FROM clause to do the
 
1422
      first level of aggregation.
 
1423
     </para>
 
1424
    </sect3>
 
1425
 
 
1426
    <sect3>
 
1427
     <title>Having</title>
 
1428
 
 
1429
     <para>
 
1430
      The HAVING clause works much like the WHERE clause and is used to
 
1431
      consider only those groups satisfying the qualification given in the
 
1432
      HAVING clause.  Essentially, WHERE filters out unwanted input rows
 
1433
      before grouping and aggregation are done, whereas HAVING filters out
 
1434
      unwanted group rows post-GROUP.  Therefore, WHERE cannot refer to the
 
1435
      results of aggregate functions.  On the other hand, there's no point
 
1436
      in writing a HAVING condition that doesn't involve an aggregate
 
1437
      function!  If your condition doesn't involve aggregates, you might
 
1438
      as well write it in WHERE, and thereby avoid the computation of
 
1439
      aggregates for groups that you're just going to throw away anyway.
 
1440
 
 
1441
      <example>
 
1442
       <title id="having-example">Having</title>
 
1443
 
 
1444
       <para>
 
1445
        If we want only those suppliers selling more than one part we use the
 
1446
        query:
 
1447
 
 
1448
        <programlisting>
 
1449
SELECT S.SNO, S.SNAME, COUNT(SE.PNO)
 
1450
    FROM SUPPLIER S, SELLS SE
 
1451
    WHERE S.SNO = SE.SNO
 
1452
    GROUP BY S.SNO, S.SNAME
 
1453
    HAVING COUNT(SE.PNO) &gt; 1;
 
1454
        </programlisting>
 
1455
 
 
1456
        and get:
 
1457
 
 
1458
        <programlisting>
 
1459
 SNO | SNAME | COUNT
 
1460
-----+-------+-------
 
1461
  1  | Smith |   2
 
1462
  3  | Adams |   2
 
1463
  4  | Blake |   3
 
1464
        </programlisting>
 
1465
       </para>
 
1466
      </example>
 
1467
     </para>
 
1468
    </sect3>
 
1469
 
 
1470
    <sect3>
 
1471
     <title>Subqueries</title>
 
1472
 
 
1473
     <para>
 
1474
      In the WHERE and HAVING clauses the use of subqueries (subselects) is
 
1475
      allowed in every place where a value is expected. In this case the
 
1476
      value must be derived by evaluating the subquery first. The usage of
 
1477
      subqueries extends the expressive power of
 
1478
      <acronym>SQL</acronym>.
 
1479
 
 
1480
      <example>
 
1481
       <title id="subselect-example">Subselect</title>
 
1482
 
 
1483
       <para>
 
1484
        If we want to know all parts having a greater price than the part
 
1485
        named 'Screw' we use the query:
 
1486
 
 
1487
        <programlisting>
 
1488
SELECT * 
 
1489
    FROM PART 
 
1490
    WHERE PRICE &gt; (SELECT PRICE FROM PART
 
1491
                   WHERE PNAME='Screw');
 
1492
        </programlisting>
 
1493
       </para>
 
1494
 
 
1495
       <para>
 
1496
        The result is:
 
1497
 
 
1498
        <programlisting>
 
1499
 PNO |  PNAME  |  PRICE
 
1500
-----+---------+--------
 
1501
  3  |  Bolt   |   15
 
1502
  4  |  Cam    |   25
 
1503
        </programlisting>
 
1504
       </para>
 
1505
 
 
1506
       <para>
 
1507
        When we look at the above query we can see the keyword
 
1508
        <command>SELECT</command> two times. The first one at the
 
1509
        beginning of the query - we will refer to it as outer
 
1510
        <command>SELECT</command> - and the one in the WHERE clause which
 
1511
        begins a nested query - we will refer to it as inner
 
1512
        <command>SELECT</command>. For every tuple of the outer
 
1513
        <command>SELECT</command> the inner <command>SELECT</command> has
 
1514
        to be evaluated. After every evaluation we know the price of the
 
1515
        tuple named 'Screw' and we can check if the price of the actual
 
1516
        tuple is greater.  (Actually, in this example the inner query need
 
1517
        only be evaluated once, since it does not depend on the state of
 
1518
        the outer query.)
 
1519
       </para>
 
1520
 
 
1521
       <para>
 
1522
        If we want to know all suppliers that do not sell any part 
 
1523
        (e.g. to be able to remove these suppliers from the database) we use:
 
1524
 
 
1525
        <programlisting>
 
1526
SELECT * 
 
1527
    FROM SUPPLIER S
 
1528
    WHERE NOT EXISTS
 
1529
        (SELECT * FROM SELLS SE
 
1530
         WHERE SE.SNO = S.SNO);
 
1531
        </programlisting>
 
1532
       </para>
 
1533
 
 
1534
       <para>
 
1535
        In our example the result will be empty because every supplier
 
1536
        sells at least one part. Note that we use S.SNO from the outer
 
1537
        <command>SELECT</command> within the WHERE clause of the inner
 
1538
        <command>SELECT</command>. Here the subquery must be evaluated
 
1539
        afresh for each tuple from the outer query, i.e. the value for
 
1540
        S.SNO is always taken from the current tuple of the outer
 
1541
        <command>SELECT</command>.
 
1542
       </para>
 
1543
      </example>
 
1544
     </para>
 
1545
    </sect3>
 
1546
 
 
1547
    <sect3>
 
1548
     <title>Subqueries in FROM</title>
 
1549
 
 
1550
     <para>
 
1551
      A somewhat different way of using subqueries is to put them in the
 
1552
      FROM clause.  This is a useful feature because a subquery of this
 
1553
      kind can output multiple columns and rows, whereas a subquery used
 
1554
      in an expression must deliver just a single result.  It also lets
 
1555
      us get more than one round of grouping/aggregation without resorting
 
1556
      to a temporary table.
 
1557
 
 
1558
      <example>
 
1559
       <title id="subselect-in-from-example">Subselect in FROM</title>
 
1560
 
 
1561
       <para>
 
1562
        If we want to know the highest average part price among all our
 
1563
        suppliers, we can't write MAX(AVG(PRICE)), but we can write:
 
1564
 
 
1565
        <programlisting>
 
1566
SELECT MAX(subtable.avgprice)
 
1567
    FROM (SELECT AVG(P.PRICE) AS avgprice
 
1568
          FROM SUPPLIER S, PART P, SELLS SE
 
1569
          WHERE S.SNO = SE.SNO AND
 
1570
                P.PNO = SE.PNO
 
1571
          GROUP BY S.SNO) subtable;
 
1572
        </programlisting>
 
1573
 
 
1574
        The subquery returns one row per supplier (because of its GROUP BY)
 
1575
        and then we aggregate over those rows in the outer query.
 
1576
       </para>
 
1577
      </example>
 
1578
     </para>
 
1579
    </sect3>
 
1580
 
 
1581
    <sect3>
 
1582
     <title>Union, Intersect, Except</title>
 
1583
 
 
1584
     <para>
 
1585
      These operations calculate the union, intersection and set theoretic
 
1586
      difference of the tuples derived by two subqueries.
 
1587
 
 
1588
      <example>
 
1589
       <title id="union-example">Union, Intersect, Except</title>
 
1590
 
 
1591
       <para>
 
1592
        The following query is an example for UNION:
 
1593
 
 
1594
        <programlisting>
 
1595
SELECT S.SNO, S.SNAME, S.CITY
 
1596
    FROM SUPPLIER S
 
1597
    WHERE S.SNAME = 'Jones'
 
1598
UNION
 
1599
    SELECT S.SNO, S.SNAME, S.CITY
 
1600
    FROM SUPPLIER S
 
1601
    WHERE S.SNAME = 'Adams';    
 
1602
        </programlisting>
 
1603
 
 
1604
gives the result:
 
1605
 
 
1606
        <programlisting>
 
1607
 SNO | SNAME |  CITY
 
1608
-----+-------+--------
 
1609
  2  | Jones | Paris
 
1610
  3  | Adams | Vienna
 
1611
        </programlisting>
 
1612
       </para>
 
1613
 
 
1614
       <para>
 
1615
        Here is an example for INTERSECT:
 
1616
 
 
1617
        <programlisting>
 
1618
SELECT S.SNO, S.SNAME, S.CITY
 
1619
    FROM SUPPLIER S
 
1620
    WHERE S.SNO &gt; 1
 
1621
INTERSECT
 
1622
    SELECT S.SNO, S.SNAME, S.CITY
 
1623
    FROM SUPPLIER S
 
1624
    WHERE S.SNO &lt; 3;
 
1625
        </programlisting>
 
1626
 
 
1627
        gives the result:
 
1628
 
 
1629
        <programlisting>
 
1630
 SNO | SNAME |  CITY
 
1631
-----+-------+--------
 
1632
  2  | Jones | Paris
 
1633
        </programlisting>
 
1634
 
 
1635
        The only tuple returned by both parts of the query is the one having SNO=2.
 
1636
       </para>
 
1637
 
 
1638
       <para>
 
1639
        Finally an example for EXCEPT:
 
1640
 
 
1641
        <programlisting>
 
1642
SELECT S.SNO, S.SNAME, S.CITY
 
1643
    FROM SUPPLIER S
 
1644
    WHERE S.SNO &gt; 1
 
1645
EXCEPT
 
1646
    SELECT S.SNO, S.SNAME, S.CITY
 
1647
    FROM SUPPLIER S
 
1648
    WHERE S.SNO &gt; 3;
 
1649
        </programlisting>
 
1650
 
 
1651
        gives the result:
 
1652
 
 
1653
        <programlisting>
 
1654
 SNO | SNAME |  CITY
 
1655
-----+-------+--------
 
1656
  2  | Jones | Paris
 
1657
  3  | Adams | Vienna
 
1658
        </programlisting>
 
1659
       </para>
 
1660
      </example>
 
1661
     </para>
 
1662
    </sect3>
 
1663
   </sect2>
 
1664
 
 
1665
   <sect2 id="datadef">
 
1666
    <title>Data Definition</title>
 
1667
 
 
1668
    <para>
 
1669
     There is a set of commands used for data definition included in the
 
1670
     <acronym>SQL</acronym> language. 
 
1671
    </para>
 
1672
 
 
1673
    <sect3 id="create">
 
1674
     <title id="create-title">Create Table</title>
 
1675
 
 
1676
     <para>
 
1677
      The most fundamental command for data definition is the
 
1678
      one that creates a new relation (a new table). The syntax of the
 
1679
      <command>CREATE TABLE</command> command is:
 
1680
 
 
1681
      <synopsis>
 
1682
CREATE TABLE <replaceable class="parameter">table_name</replaceable>
 
1683
    (<replaceable class="parameter">name_of_attr_1</replaceable> <replaceable class="parameter">type_of_attr_1</replaceable>
 
1684
     [, <replaceable class="parameter">name_of_attr_2</replaceable> <replaceable class="parameter">type_of_attr_2</replaceable> 
 
1685
     [, ...]]);
 
1686
      </synopsis>
 
1687
 
 
1688
      <example>
 
1689
       <title id="table-create">Table Creation</title>
 
1690
 
 
1691
       <para>
 
1692
        To create the tables defined in
 
1693
        <xref linkend="supplier-fig" endterm="supplier-fig"> the
 
1694
        following <acronym>SQL</acronym> statements are used:
 
1695
 
 
1696
        <programlisting>
 
1697
CREATE TABLE SUPPLIER
 
1698
    (SNO   INTEGER,
 
1699
     SNAME VARCHAR(20),
 
1700
     CITY  VARCHAR(20));
 
1701
     </programlisting>
 
1702
 
 
1703
     <programlisting>
 
1704
CREATE TABLE PART
 
1705
    (PNO   INTEGER,
 
1706
     PNAME VARCHAR(20),
 
1707
     PRICE DECIMAL(4 , 2));
 
1708
     </programlisting>
 
1709
 
 
1710
     <programlisting>
 
1711
CREATE TABLE SELLS
 
1712
    (SNO INTEGER,
 
1713
     PNO INTEGER);
 
1714
        </programlisting>
 
1715
       </para>
 
1716
      </example>
 
1717
     </para>
 
1718
    </sect3>
 
1719
 
 
1720
    <sect3>
 
1721
     <title>Data Types in <acronym>SQL</acronym></title>
 
1722
 
 
1723
     <para>
 
1724
      The following is a list of some data types that are supported by 
 
1725
      <acronym>SQL</acronym>:
 
1726
 
 
1727
      <itemizedlist>
 
1728
       <listitem>
 
1729
        <para>
 
1730
         INTEGER: signed fullword binary integer (31 bits precision).
 
1731
        </para>
 
1732
       </listitem>
 
1733
 
 
1734
       <listitem>
 
1735
        <para>
 
1736
         SMALLINT: signed halfword binary integer (15 bits precision).
 
1737
        </para>
 
1738
       </listitem>
 
1739
 
 
1740
       <listitem>
 
1741
        <para>
 
1742
         DECIMAL (<replaceable class="parameter">p</replaceable>[,<replaceable class="parameter">q</replaceable>]):
 
1743
         signed packed decimal number of up to
 
1744
         <replaceable class="parameter">p</replaceable>
 
1745
         digits, with
 
1746
         <replaceable class="parameter">q</replaceable>
 
1747
         digits to the right of the decimal point.
 
1748
         If <replaceable class="parameter">q</replaceable>
 
1749
         is omitted it is assumed to be 0.
 
1750
        </para>
 
1751
       </listitem>
 
1752
 
 
1753
       <listitem>
 
1754
        <para>
 
1755
         FLOAT: signed doubleword floating point number.
 
1756
        </para>
 
1757
       </listitem>
 
1758
 
 
1759
       <listitem>
 
1760
        <para>
 
1761
         VARCHAR(<replaceable class="parameter">n</replaceable>):
 
1762
         varying length character string of maximum length
 
1763
         <replaceable class="parameter">n</replaceable>.
 
1764
        </para>
 
1765
       </listitem>
 
1766
 
 
1767
       <listitem>
 
1768
        <para>
 
1769
         CHAR(<replaceable class="parameter">n</replaceable>):
 
1770
         fixed length character string of length
 
1771
         <replaceable class="parameter">n</replaceable>.
 
1772
        </para>
 
1773
       </listitem>
 
1774
 
 
1775
      </itemizedlist>
 
1776
     </para>
 
1777
    </sect3>
 
1778
 
 
1779
    <sect3>
 
1780
     <title>Create Index</title>
 
1781
 
 
1782
     <para>
 
1783
      Indexes are used to speed up access to a relation. If a relation <classname>R</classname>
 
1784
      has an index on attribute <classname>A</classname> then we can
 
1785
      retrieve all tuples <replaceable>t</replaceable>
 
1786
      having
 
1787
      <replaceable>t</replaceable>(<classname>A</classname>) = <replaceable>a</replaceable>
 
1788
      in time roughly proportional to the number of such
 
1789
      tuples <replaceable>t</replaceable>
 
1790
      rather than in time proportional to the size of <classname>R</classname>.
 
1791
     </para>
 
1792
 
 
1793
     <para>
 
1794
      To create an index in <acronym>SQL</acronym>
 
1795
      the <command>CREATE INDEX</command> command is used. The syntax is:
 
1796
 
 
1797
      <programlisting>
 
1798
CREATE INDEX <replaceable class="parameter">index_name</replaceable> 
 
1799
    ON <replaceable class="parameter">table_name</replaceable> ( <replaceable class="parameter">name_of_attribute</replaceable> );
 
1800
      </programlisting>
 
1801
     </para>
 
1802
 
 
1803
     <para>
 
1804
      <example>
 
1805
       <title id="index-create">Create Index</title>
 
1806
 
 
1807
       <para>
 
1808
        To create an index named I on attribute SNAME of relation SUPPLIER
 
1809
        we use the following statement:
 
1810
 
 
1811
      <programlisting>
 
1812
CREATE INDEX I ON SUPPLIER (SNAME);
 
1813
      </programlisting>
 
1814
     </para>
 
1815
 
 
1816
       <para>
 
1817
        The created index is maintained automatically, i.e. whenever a new
 
1818
        tuple is inserted into the relation SUPPLIER the index I is
 
1819
        adapted. Note that the only changes a user can perceive when an
 
1820
        index is present are increased speed for <command>SELECT</command>
 
1821
        and decreases in speed of updates.
 
1822
       </para>
 
1823
      </example>
 
1824
     </para>
 
1825
    </sect3>
 
1826
 
 
1827
    <sect3>
 
1828
     <title>Create View</title>
 
1829
 
 
1830
     <para>
 
1831
      A view may be regarded as a <firstterm>virtual table</firstterm>,
 
1832
      i.e. a table that
 
1833
      does not <emphasis>physically</emphasis> exist in the database
 
1834
      but looks to the user
 
1835
      as if it does. By contrast, when we talk of a
 
1836
      <firstterm>base table</firstterm> there is
 
1837
      really a physically stored counterpart of each row of the table
 
1838
      somewhere in the physical storage.
 
1839
     </para>
 
1840
 
 
1841
     <para>
 
1842
      Views do not have their own, physically separate, distinguishable
 
1843
      stored data. Instead, the system stores the definition of the
 
1844
      view (i.e. the rules about how to access physically stored base
 
1845
      tables in order to materialize the view) somewhere in the system
 
1846
      catalogs (see
 
1847
      <xref linkend="tutorial-catalogs-title" endterm="tutorial-catalogs-title">). For a
 
1848
      discussion on different techniques to implement views refer to
 
1849
<!--
 
1850
      section
 
1851
      <xref linkend="view-impl" endterm="view-impl">.
 
1852
-->
 
1853
      <citetitle>SIM98</citetitle>.
 
1854
     </para>
 
1855
 
 
1856
     <para>
 
1857
      In <acronym>SQL</acronym> the <command>CREATE VIEW</command>
 
1858
      command is used to define a view. The syntax
 
1859
      is:
 
1860
 
 
1861
      <programlisting>
 
1862
CREATE VIEW <replaceable class="parameter">view_name</replaceable>
 
1863
    AS <replaceable class="parameter">select_stmt</replaceable>
 
1864
      </programlisting>
 
1865
 
 
1866
      where <replaceable class="parameter">select_stmt</replaceable> 
 
1867
      is a valid select statement as defined
 
1868
      in <xref linkend="select-title" endterm="select-title">.
 
1869
      Note that <replaceable class="parameter">select_stmt</replaceable> is
 
1870
      not executed when the view is created. It is just stored in the 
 
1871
      <firstterm>system catalogs</firstterm>
 
1872
      and is executed whenever a query against the view is made.
 
1873
     </para>
 
1874
 
 
1875
     <para>
 
1876
      Let the following view definition be given (we use
 
1877
      the tables from
 
1878
      <xref linkend="supplier-fig" endterm="supplier-fig"> again):
 
1879
 
 
1880
      <programlisting>
 
1881
CREATE VIEW London_Suppliers
 
1882
    AS SELECT S.SNAME, P.PNAME
 
1883
        FROM SUPPLIER S, PART P, SELLS SE
 
1884
        WHERE S.SNO = SE.SNO AND
 
1885
              P.PNO = SE.PNO AND
 
1886
              S.CITY = 'London';
 
1887
      </programlisting>
 
1888
     </para>
 
1889
 
 
1890
     <para>
 
1891
      Now we can use this <firstterm>virtual relation</firstterm>
 
1892
      <classname>London_Suppliers</classname> as
 
1893
      if it were another base table:
 
1894
 
 
1895
      <programlisting>
 
1896
SELECT * FROM London_Suppliers
 
1897
    WHERE PNAME = 'Screw';
 
1898
      </programlisting>
 
1899
 
 
1900
      which will return the following table:
 
1901
 
 
1902
      <programlisting>
 
1903
 SNAME | PNAME
 
1904
-------+-------
 
1905
 Smith | Screw                 
 
1906
      </programlisting>
 
1907
     </para>
 
1908
 
 
1909
     <para>
 
1910
      To calculate this result the database system has to do a
 
1911
      <emphasis>hidden</emphasis>
 
1912
      access to the base tables SUPPLIER, SELLS and PART first. It
 
1913
      does so by executing the query given in the view definition against
 
1914
      those base tables. After that the additional qualifications
 
1915
      (given in the
 
1916
      query against the view) can be applied to obtain the resulting
 
1917
      table.
 
1918
     </para>
 
1919
    </sect3>
 
1920
 
 
1921
    <sect3>
 
1922
     <title>Drop Table, Drop Index, Drop View</title>
 
1923
 
 
1924
     <para>
 
1925
      To destroy a table (including all tuples stored in that table) the
 
1926
      <command>DROP TABLE</command> command is used:
 
1927
 
 
1928
      <programlisting>
 
1929
DROP TABLE <replaceable class="parameter">table_name</replaceable>;
 
1930
       </programlisting>
 
1931
      </para>
 
1932
 
 
1933
     <para>
 
1934
      To destroy the SUPPLIER table use the following statement:
 
1935
 
 
1936
      <programlisting>
 
1937
DROP TABLE SUPPLIER;
 
1938
      </programlisting>
 
1939
     </para>
 
1940
 
 
1941
     <para>
 
1942
      The <command>DROP INDEX</command> command is used to destroy an index:
 
1943
 
 
1944
      <programlisting>
 
1945
DROP INDEX <replaceable class="parameter">index_name</replaceable>;
 
1946
      </programlisting>
 
1947
     </para>
 
1948
 
 
1949
     <para>
 
1950
      Finally to destroy a given view use the command <command>DROP
 
1951
      VIEW</command>:
 
1952
 
 
1953
      <programlisting>
 
1954
DROP VIEW <replaceable class="parameter">view_name</replaceable>;
 
1955
      </programlisting>
 
1956
     </para>
 
1957
    </sect3>
 
1958
   </sect2>
 
1959
 
 
1960
   <sect2>
 
1961
    <title>Data Manipulation</title>
 
1962
 
 
1963
    <sect3>
 
1964
     <title>Insert Into</title>
 
1965
 
 
1966
     <para>
 
1967
      Once a table is created (see
 
1968
      <xref linkend="create-title" endterm="create-title">), it can be filled
 
1969
      with tuples using the command <command>INSERT INTO</command>.
 
1970
      The syntax is:
 
1971
 
 
1972
      <programlisting>
 
1973
INSERT INTO <replaceable class="parameter">table_name</replaceable> (<replaceable class="parameter">name_of_attr_1</replaceable> 
 
1974
    [, <replaceable class="parameter">name_of_attr_2</replaceable> [,...]])
 
1975
    VALUES (<replaceable class="parameter">val_attr_1</replaceable> [, <replaceable class="parameter">val_attr_2</replaceable> [, ...]]);
 
1976
      </programlisting>
 
1977
     </para>
 
1978
 
 
1979
     <para>
 
1980
      To insert the first tuple into the relation SUPPLIER (from
 
1981
      <xref linkend="supplier-fig" endterm="supplier-fig">) we use the
 
1982
      following statement:
 
1983
 
 
1984
      <programlisting>
 
1985
INSERT INTO SUPPLIER (SNO, SNAME, CITY)
 
1986
    VALUES (1, 'Smith', 'London');
 
1987
      </programlisting>
 
1988
     </para>
 
1989
 
 
1990
     <para>
 
1991
      To insert the first tuple into the relation SELLS we use:
 
1992
 
 
1993
      <programlisting>
 
1994
INSERT INTO SELLS (SNO, PNO)
 
1995
    VALUES (1, 1);
 
1996
      </programlisting>
 
1997
     </para>
 
1998
    </sect3>
 
1999
 
 
2000
    <sect3>
 
2001
     <title>Update</title>
 
2002
 
 
2003
     <para>
 
2004
      To change one or more attribute values of tuples in a relation the
 
2005
      <command>UPDATE</command> command is used. The syntax is:
 
2006
 
 
2007
      <programlisting>
 
2008
UPDATE <replaceable class="parameter">table_name</replaceable>
 
2009
    SET <replaceable class="parameter">name_of_attr_1</replaceable> = <replaceable class="parameter">value_1</replaceable> 
 
2010
        [, ... [, <replaceable class="parameter">name_of_attr_k</replaceable> = <replaceable class="parameter">value_k</replaceable>]]
 
2011
    WHERE <replaceable class="parameter">condition</replaceable>;
 
2012
      </programlisting>
 
2013
     </para>
 
2014
 
 
2015
     <para>
 
2016
      To change the value of attribute PRICE of the part 'Screw' in the
 
2017
      relation PART we use:
 
2018
 
 
2019
      <programlisting>
 
2020
UPDATE PART
 
2021
    SET PRICE = 15
 
2022
    WHERE PNAME = 'Screw';
 
2023
      </programlisting>
 
2024
     </para>
 
2025
 
 
2026
     <para>
 
2027
      The new value of attribute PRICE of the tuple whose name is 'Screw' is
 
2028
      now 15.
 
2029
     </para>
 
2030
    </sect3>
 
2031
 
 
2032
    <sect3>
 
2033
     <title>Delete</title>
 
2034
 
 
2035
     <para>
 
2036
      To delete a tuple from a particular table use the command DELETE
 
2037
      FROM. The syntax is:
 
2038
 
 
2039
      <programlisting>
 
2040
DELETE FROM <replaceable class="parameter">table_name</replaceable>
 
2041
    WHERE <replaceable class="parameter">condition</replaceable>;
 
2042
      </programlisting>
 
2043
     </para>
 
2044
 
 
2045
     <para>
 
2046
      To delete the supplier called 'Smith' of the table SUPPLIER the
 
2047
      following statement is used:
 
2048
 
 
2049
      <programlisting>
 
2050
DELETE FROM SUPPLIER
 
2051
    WHERE SNAME = 'Smith';
 
2052
      </programlisting>
 
2053
     </para>
 
2054
    </sect3>
 
2055
   </sect2>
 
2056
 
 
2057
   <sect2 id="tutorial-catalogs">
 
2058
    <title id="tutorial-catalogs-title">System Catalogs</title>
 
2059
 
 
2060
    <para>
 
2061
     In every <acronym>SQL</acronym> database system
 
2062
     <firstterm>system catalogs</firstterm> are used to keep
 
2063
     track of which tables, views indexes etc. are defined in the
 
2064
     database. These system catalogs can be queried as if they were normal
 
2065
     relations. For example there is one catalog used for the definition of
 
2066
     views. This catalog stores the query from the view definition. Whenever
 
2067
     a query against a view is made, the system first gets the
 
2068
     <firstterm>view definition query</firstterm> out of the catalog
 
2069
     and materializes the view
 
2070
     before proceeding with the user query (see
 
2071
<!--
 
2072
      section
 
2073
      <xref linkend="view-impl" endterm="view-impl">.
 
2074
    <citetitle>SIM98</citetitle>
 
2075
-->
 
2076
     <xref linkend="SIM98" endterm="SIM98">
 
2077
     for a more detailed
 
2078
     description). For more information about system catalogs refer to
 
2079
     <xref linkend="DATE94" endterm="DATE94">.
 
2080
    </para>
 
2081
   </sect2>
 
2082
 
 
2083
   <sect2>
 
2084
    <title>Embedded <acronym>SQL</acronym></title>
 
2085
 
 
2086
    <para>
 
2087
     In this section we will sketch how <acronym>SQL</acronym> can be
 
2088
     embedded into a host language (e.g. <literal>C</literal>).
 
2089
     There are two main reasons why we want to use <acronym>SQL</acronym>
 
2090
     from a host language:
 
2091
 
 
2092
     <itemizedlist>
 
2093
      <listitem>
 
2094
       <para>
 
2095
        There are queries that cannot be formulated using pure <acronym>SQL</acronym>
 
2096
        (i.e. recursive queries). To be able to perform such queries we need a
 
2097
        host language with a greater expressive power than
 
2098
        <acronym>SQL</acronym>.
 
2099
       </para>
 
2100
      </listitem>
 
2101
 
 
2102
      <listitem>
 
2103
       <para>
 
2104
        We simply want to access a database from some application that
 
2105
        is written in the host language (e.g. a ticket reservation system
 
2106
        with a graphical user interface is written in C and the information
 
2107
        about which tickets are still left is stored in a database that can be
 
2108
        accessed using embedded <acronym>SQL</acronym>).
 
2109
       </para>
 
2110
      </listitem>
 
2111
     </itemizedlist>
 
2112
    </para>
 
2113
 
 
2114
    <para>
 
2115
     A program using embedded <acronym>SQL</acronym>
 
2116
     in a host language consists of statements
 
2117
     of the host language and of
 
2118
     <firstterm>embedded <acronym>SQL</acronym></firstterm>
 
2119
     (<acronym>ESQL</acronym>) statements. Every <acronym>ESQL</acronym>
 
2120
     statement begins with the keywords <command>EXEC SQL</command>.
 
2121
     The <acronym>ESQL</acronym> statements are
 
2122
     transformed to statements of the host language
 
2123
     by a <firstterm>precompiler</firstterm>
 
2124
     (which usually inserts
 
2125
     calls to library routines that perform the various <acronym>SQL</acronym>
 
2126
     commands). 
 
2127
    </para>
 
2128
 
 
2129
    <para>
 
2130
     When we look at the examples throughout
 
2131
     <xref linkend="select-title" endterm="select-title"> we
 
2132
     realize that the result of the queries is very often a set of
 
2133
     tuples. Most host languages are not designed to operate on sets so we
 
2134
     need a mechanism to access every single tuple of the set of tuples
 
2135
     returned by a SELECT statement. This mechanism can be provided by
 
2136
     declaring a <firstterm>cursor</firstterm>.
 
2137
     After that we can use the <command>FETCH</command> command to
 
2138
     retrieve a tuple and set the cursor to the next tuple.
 
2139
    </para>
 
2140
 
 
2141
    <para>
 
2142
     For a detailed discussion on embedded <acronym>SQL</acronym>
 
2143
     refer to
 
2144
     <xref linkend="DATE97" endterm="DATE97">,
 
2145
     <xref linkend="DATE94" endterm="DATE94">,
 
2146
     or
 
2147
     <xref linkend="ULL88" endterm="ULL88">.
 
2148
    </para>
 
2149
   </sect2>
 
2150
  </sect1>
 
2151
 </chapter>
 
2152
 
 
2153
<!-- Keep this comment at the end of the file
 
2154
Local variables:
 
2155
mode:sgml
 
2156
sgml-omittag:nil
 
2157
sgml-shorttag:t
 
2158
sgml-minimize-attributes:nil
 
2159
sgml-always-quote-attributes:t
 
2160
sgml-indent-step:1
 
2161
sgml-indent-data:t
 
2162
sgml-parent-document:nil
 
2163
sgml-default-dtd-file:"./reference.ced"
 
2164
sgml-exposed-tags:nil
 
2165
sgml-local-catalogs:("/usr/lib/sgml/catalog")
 
2166
sgml-local-ecat-files:nil
 
2167
End:
 
2168
-->