~ubuntu-branches/ubuntu/karmic/postgresql-8.4/karmic-security

« back to all changes in this revision

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

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2009-05-05 00:58:06 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20090505005806-c19tt7oyqb7kuw49
Tags: 8.4~beta1+cvs20090503-1
New upstream snapshot.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
 <para>
15
15
  The previous chapters explained how to create tables, how to fill
16
16
  them with data, and how to manipulate that data.  Now we finally
17
 
  discuss how to retrieve the data out of the database.
 
17
  discuss how to retrieve the data from the database.
18
18
 </para>
19
19
 
20
20
 
63
63
 </para>
64
64
 
65
65
 <para>
66
 
  <literal>FROM table1</literal> is a particularly simple kind of
 
66
  <literal>FROM table1</literal> is a simple kind of
67
67
  table expression: it reads just one table.  In general, table
68
68
  expressions can be complex constructs of base tables, joins, and
69
69
  subqueries.  But you can also omit the table expression entirely and
133
133
 
134
134
   <para>
135
135
    When a table reference names a table that is the parent of a
136
 
    table inheritance hierarchy, the table reference produces rows of
137
 
    not only that table but all of its descendant tables, unless the
 
136
    table inheritance hierarchy, the table reference produces rows
 
137
    not only of that table but all of its descendant tables, unless the
138
138
    key word <literal>ONLY</> precedes the table name.  However, the
139
139
    reference produces only the columns that appear in the named table
140
140
    &mdash; any columns added in subtables are ignored.
174
174
</synopsis>
175
175
 
176
176
       <para>
177
 
        For each combination of rows from
 
177
        Produce every possible combination of rows from 
178
178
        <replaceable>T1</replaceable> and
179
 
        <replaceable>T2</replaceable>, the derived table will contain a
180
 
        row consisting of all columns in <replaceable>T1</replaceable>
181
 
        followed by all columns in <replaceable>T2</replaceable>.  If
 
179
        <replaceable>T2</replaceable> (i.e., a Cartesian product),
 
180
        with output columns consisting of
 
181
        all <replaceable>T1</replaceable> columns
 
182
        followed by all <replaceable>T2</replaceable> columns.  If
182
183
        the tables have N and M rows respectively, the joined
183
184
        table will have N * M rows.
184
185
       </para>
242
243
        comma-separated list of column names, which the joined tables
243
244
        must have in common, and forms a join condition specifying
244
245
        equality of each of these pairs of columns.  Furthermore, the
245
 
        output of a <literal>JOIN USING</> has one column for each of
246
 
        the equated pairs of input columns, followed by all of the
 
246
        output of <literal>JOIN USING</> has one column for each of
 
247
        the equated pairs of input columns, followed by the
247
248
        other columns from each table.  Thus, <literal>USING (a, b,
248
249
        c)</literal> is equivalent to <literal>ON (t1.a = t2.a AND
249
250
        t1.b = t2.b AND t1.c = t2.c)</literal> with the exception that
250
251
        if <literal>ON</> is used there will be two columns
251
252
        <literal>a</>, <literal>b</>, and <literal>c</> in the result,
252
 
        whereas with <literal>USING</> there will be only one of each.
 
253
        whereas with <literal>USING</> there will be only one of each
 
254
        (and they will appear first if <command>SELECT *</> is used).
253
255
       </para>
254
256
 
255
257
       <para>
262
264
        </indexterm>
263
265
        Finally, <literal>NATURAL</> is a shorthand form of
264
266
        <literal>USING</>: it forms a <literal>USING</> list
265
 
        consisting of exactly those column names that appear in both
 
267
        consisting of all column names that appear in both
266
268
        input tables.  As with <literal>USING</>, these columns appear
267
269
        only once in the output table.
268
270
       </para>
298
300
          <para>
299
301
           First, an inner join is performed.  Then, for each row in
300
302
           T1 that does not satisfy the join condition with any row in
301
 
           T2, a joined row is added with null values in columns of
302
 
           T2.  Thus, the joined table unconditionally has at least
 
303
           T2, a row is added with null values in columns of
 
304
           T2.  Thus, the joined table always has at least
303
305
           one row for each row in T1.
304
306
          </para>
305
307
         </listitem>
321
323
          <para>
322
324
           First, an inner join is performed.  Then, for each row in
323
325
           T2 that does not satisfy the join condition with any row in
324
 
           T1, a joined row is added with null values in columns of
 
326
           T1, a row is added with null values in columns of
325
327
           T1.  This is the converse of a left join: the result table
326
 
           will unconditionally have a row for each row in T2.
 
328
           will always have a row for each row in T2.
327
329
          </para>
328
330
         </listitem>
329
331
        </varlistentry>
335
337
          <para>
336
338
           First, an inner join is performed.  Then, for each row in
337
339
           T1 that does not satisfy the join condition with any row in
338
 
           T2, a joined row is added with null values in columns of
 
340
           T2, a row is added with null values in columns of
339
341
           T2.  Also, for each row of T2 that does not satisfy the
340
 
           join condition with any row in T1, a joined row with null
 
342
           join condition with any row in T1, a row with null
341
343
           values in the columns of T1 is added.
342
344
          </para>
343
345
         </listitem>
350
352
 
351
353
    <para>
352
354
     Joins of all types can be chained together or nested: either or
353
 
     both of <replaceable>T1</replaceable> and
354
 
     <replaceable>T2</replaceable> might be joined tables.  Parentheses
 
355
     both <replaceable>T1</replaceable> and
 
356
     <replaceable>T2</replaceable> can be joined tables.  Parentheses
355
357
     can be used around <literal>JOIN</> clauses to control the join
356
358
     order.  In the absence of parentheses, <literal>JOIN</> clauses
357
359
     nest left-to-right.
460
462
   3 | c    |     |
461
463
(3 rows)
462
464
</screen>
 
465
     Notice that placing the restriction in the <literal>WHERE</> clause
 
466
     produces a different result:
 
467
<screen>
 
468
<prompt>=&gt;</> <userinput>SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num WHERE t2.value = 'xxx';</>
 
469
 num | name | num | value
 
470
-----+------+-----+-------
 
471
   1 | a    |   1 | xxx
 
472
(1 row)
 
473
</screen>
 
474
     This is because a restriction placed in the <literal>ON</>
 
475
     clause is processed <emphasis>before</> the join, while 
 
476
     a restriction placed in the <literal>WHERE</> clause is processed
 
477
     <emphasis>after</> the join.
463
478
    </para>
464
479
   </sect3>
465
480
 
513
528
SELECT * FROM my_table AS m WHERE my_table.a &gt; 5;
514
529
</programlisting>
515
530
     is not valid according to the SQL standard.  In
516
 
     <productname>PostgreSQL</productname> this will draw an error if the
 
531
     <productname>PostgreSQL</productname> this will draw an error, assuming the
517
532
     <xref linkend="guc-add-missing-from"> configuration variable is
518
533
     <literal>off</> (as it is by default).  If it is <literal>on</>,
519
534
     an implicit table reference will be added to the
559
574
 
560
575
    <para>
561
576
     When an alias is applied to the output of a <literal>JOIN</>
562
 
     clause, using any of these forms, the alias hides the original
563
 
     names within the <literal>JOIN</>.  For example:
 
577
     clause, the alias hides the original
 
578
     name referenced in the <literal>JOIN</>.  For example:
564
579
<programlisting>
565
580
SELECT a.* FROM my_table AS a JOIN your_table AS b ON ...
566
581
</programlisting>
568
583
<programlisting>
569
584
SELECT a.* FROM (my_table AS a JOIN your_table AS b ON ...) AS c
570
585
</programlisting>
571
 
     is not valid: the table alias <literal>a</> is not visible
 
586
     is not valid; the table alias <literal>a</> is not visible
572
587
     outside the alias <literal>c</>.
573
588
    </para>
574
589
   </sect3>
631
646
 
632
647
    <para>
633
648
     If a table function returns a base data type, the single result
634
 
     column is named like the function. If the function returns a
 
649
     column name matches the function name. If the function returns a
635
650
     composite type, the result columns get the same names as the
636
651
     individual attributes of the type.
637
652
    </para>
655
670
SELECT * FROM getfoo(1) AS t1;
656
671
 
657
672
SELECT * FROM foo
658
 
    WHERE foosubid IN (select foosubid from getfoo(foo.fooid) z
659
 
                           where z.fooid = foo.fooid);
 
673
    WHERE foosubid IN (
 
674
                        SELECT foosubid
 
675
                        FROM getfoo(foo.fooid) z
 
676
                        WHERE z.fooid = foo.fooid
 
677
                      );
660
678
 
661
679
CREATE VIEW vw_getfoo AS SELECT * FROM getfoo(1);
662
680
 
668
686
     In some cases it is useful to define table functions that can
669
687
     return different column sets depending on how they are invoked.
670
688
     To support this, the table function can be declared as returning
671
 
     the pseudotype <type>record</>.  When such a function is used in
 
689
     the pseudotype <type>record</>, rather than <literal>SET OF</>.  
 
690
     When such a function is used in
672
691
     a query, the expected row structure must be specified in the
673
692
     query itself, so that the system can know how to parse and plan
674
693
     the query.  Consider this example:
675
694
<programlisting>
676
695
SELECT *
677
 
    FROM dblink('dbname=mydb', 'select proname, prosrc from pg_proc')
 
696
    FROM dblink('dbname=mydb', 'SELECT proname, prosrc FROM pg_proc')
678
697
      AS t1(proname name, prosrc text)
679
698
    WHERE proname LIKE 'bytea%';
680
699
</programlisting>
710
729
    After the processing of the <literal>FROM</> clause is done, each
711
730
    row of the derived virtual table is checked against the search
712
731
    condition.  If the result of the condition is true, the row is
713
 
    kept in the output table, otherwise (that is, if the result is
 
732
    kept in the output table, otherwise (i.e., if the result is
714
733
    false or null) it is discarded.  The search condition typically
715
 
    references at least some column of the table generated in the
 
734
    references at least one column of the table generated in the
716
735
    <literal>FROM</> clause; this is not required, but otherwise the
717
736
    <literal>WHERE</> clause will be fairly useless.
718
737
   </para>
735
754
</programlisting>
736
755
     Which one of these you use is mainly a matter of style.  The
737
756
     <literal>JOIN</> syntax in the <literal>FROM</> clause is
738
 
     probably not as portable to other SQL database management systems.  For
739
 
     outer joins there is no choice in any case: they must be done in
740
 
     the <literal>FROM</> clause.  An <literal>ON</>/<literal>USING</>
 
757
     probably not as portable to other SQL database management systems,
 
758
     even though it is in the SQL standard.  For
 
759
     outer joins there is no choice:  they must be done in
 
760
     the <literal>FROM</> clause.  The <literal>ON</>/<literal>USING</>
741
761
     clause of an outer join is <emphasis>not</> equivalent to a
742
 
     <literal>WHERE</> condition, because it determines the addition
 
762
     <literal>WHERE</> condition, because it affects the addition
743
763
     of rows (for unmatched input rows) as well as the removal of rows
744
764
     from the final result.
745
765
    </para>
760
780
 
761
781
SELECT ... FROM fdt WHERE EXISTS (SELECT c1 FROM t2 WHERE c2 &gt; fdt.c1)
762
782
</programlisting>
763
 
    <literal>fdt</literal> is the table derived in the
 
783
    <literal>fdt</literal> is the table used in the
764
784
    <literal>FROM</> clause. Rows that do not meet the search
765
785
    condition of the <literal>WHERE</> clause are eliminated from
766
786
    <literal>fdt</literal>. Notice the use of scalar subqueries as
803
823
 
804
824
   <para>
805
825
    The <xref linkend="sql-groupby" endterm="sql-groupby-title"> is
806
 
    used to group together those rows in a table that share the same
 
826
    used to group together those rows in a table that have the same
807
827
    values in all the columns listed. The order in which the columns
808
828
    are listed does not matter.  The effect is to combine each set
809
 
    of rows sharing common values into one group row that is
810
 
    representative of all rows in the group.  This is done to
 
829
    of rows having common values into one group row that
 
830
    represents all rows in the group.  This is done to
811
831
    eliminate redundancy in the output and/or compute aggregates that
812
832
    apply to these groups.  For instance:
813
833
<screen>
840
860
 
841
861
   <para>
842
862
    In general, if a table is grouped, columns that are not
843
 
    used in the grouping cannot be referenced except in aggregate
 
863
    the same in the group cannot be referenced except in aggregate
844
864
    expressions.  An example with aggregate expressions is:
845
865
<screen>
846
866
<prompt>=&gt;</> <userinput>SELECT x, sum(y) FROM test1 GROUP BY x;</>
860
880
   <tip>
861
881
    <para>
862
882
     Grouping without aggregate expressions effectively calculates the
863
 
     set of distinct values in a column.  This can also be achieved
 
883
     set of distinct values in a column.  This can more clearly be achieved
864
884
     using the <literal>DISTINCT</> clause (see <xref
865
885
     linkend="queries-distinct">).
866
886
    </para>
868
888
 
869
889
   <para>
870
890
    Here is another example:  it calculates the total sales for each
871
 
    product (rather than the total sales on all products):
 
891
    product (rather than the total sales of all products):
872
892
<programlisting>
873
893
SELECT product_id, p.name, (sum(s.units) * p.price) AS sales
874
894
    FROM products p LEFT JOIN sales s USING (product_id)
877
897
    In this example, the columns <literal>product_id</literal>,
878
898
    <literal>p.name</literal>, and <literal>p.price</literal> must be
879
899
    in the <literal>GROUP BY</> clause since they are referenced in
880
 
    the query select list.  (Depending on how exactly the products
 
900
    the query select list.  (Depending on how the products
881
901
    table is set up, name and price might be fully dependent on the
882
902
    product ID, so the additional groupings could theoretically be
883
 
    unnecessary, but this is not implemented yet.)  The column
 
903
    unnecessary, though this is not implemented.)  The column
884
904
    <literal>s.units</> does not have to be in the <literal>GROUP
885
905
    BY</> list since it is only used in an aggregate expression
886
906
    (<literal>sum(...)</literal>), which represents the sales
901
921
   </indexterm>
902
922
 
903
923
   <para>
904
 
    If a table has been grouped using a <literal>GROUP BY</literal>
905
 
    clause, but then only certain groups are of interest, the
 
924
    If a table has been grouped using <literal>GROUP BY</literal>,
 
925
    but only certain groups are of interest, the
906
926
    <literal>HAVING</literal> clause can be used, much like a
907
 
    <literal>WHERE</> clause, to eliminate groups from a grouped
908
 
    table.  The syntax is:
 
927
    <literal>WHERE</> clause, to eliminate groups from the result.
 
928
    The syntax is:
909
929
<synopsis>
910
930
SELECT <replaceable>select_list</replaceable> FROM ... <optional>WHERE ...</optional> GROUP BY ... HAVING <replaceable>boolean_expression</replaceable>
911
931
</synopsis>
1068
1088
    the row's values substituted for any column references.  But the
1069
1089
    expressions in the select list do not have to reference any
1070
1090
    columns in the table expression of the <literal>FROM</> clause;
1071
 
    they could be constant arithmetic expressions as well, for
1072
 
    instance.
 
1091
    they can be constant arithmetic expressions as well.
1073
1092
   </para>
1074
1093
  </sect2>
1075
1094
 
1083
1102
 
1084
1103
   <para>
1085
1104
    The entries in the select list can be assigned names for further
1086
 
    processing.  The <quote>further processing</quote> in this case is
1087
 
    an optional sort specification and the client application (e.g.,
1088
 
    column headers for display).  For example:
 
1105
    processing, perhaps for reference in an <literal>ORDER BY</> clause
 
1106
    or for display by the client application.  For example:
1089
1107
<programlisting>
1090
1108
SELECT a AS value, b + c AS sum FROM ...
1091
1109
</programlisting>
1122
1140
    <para>
1123
1141
     The naming of output columns here is different from that done in
1124
1142
     the <literal>FROM</> clause (see <xref
1125
 
     linkend="queries-table-aliases">).  This pipeline will in fact
1126
 
     allow you to rename the same column twice, but the name chosen in
 
1143
     linkend="queries-table-aliases">).  It is possible 
 
1144
     to rename the same column twice, but the name used in
1127
1145
     the select list is the one that will be passed on.
1128
1146
    </para>
1129
1147
   </note>
1181
1199
    The <literal>DISTINCT ON</> clause is not part of the SQL standard
1182
1200
    and is sometimes considered bad style because of the potentially
1183
1201
    indeterminate nature of its results.  With judicious use of
1184
 
    <literal>GROUP BY</> and subqueries in <literal>FROM</> the
 
1202
    <literal>GROUP BY</> and subqueries in <literal>FROM</>, this
1185
1203
    construct can be avoided, but it is often the most convenient
1186
1204
    alternative.
1187
1205
   </para>
1229
1247
<synopsis>
1230
1248
<replaceable>query1</replaceable> UNION <replaceable>query2</replaceable> UNION <replaceable>query3</replaceable>
1231
1249
</synopsis>
1232
 
   which really says
 
1250
   which is executed as:
1233
1251
<synopsis>
1234
1252
(<replaceable>query1</replaceable> UNION <replaceable>query2</replaceable>) UNION <replaceable>query3</replaceable>
1235
1253
</synopsis>
1328
1346
  <para>
1329
1347
   The <literal>NULLS FIRST</> and <literal>NULLS LAST</> options can be
1330
1348
   used to determine whether nulls appear before or after non-null values
1331
 
   in the sort ordering.  By default, null values sort as if larger than any
1332
 
   non-null value; that is, <literal>NULLS FIRST</> is the default for
1333
 
   <literal>DESC</> order, and <literal>NULLS LAST</> otherwise.
 
1349
   in the sort ordering.  The default behavior is for null values sort as
 
1350
   if larger than all non-null values (<literal>NULLS FIRST</>), except
 
1351
   in <literal>DESC</> ordering, where <literal>NULLS LAST</> is the default.
1334
1352
  </para>
1335
1353
 
1336
1354
  <para>
1341
1359
  </para>
1342
1360
 
1343
1361
  <para>
1344
 
   For backwards compatibility with the SQL92 version of the standard,
1345
 
   a <replaceable>sort_expression</> can instead be the name or number
 
1362
   A <replaceable>sort_expression</> can also be the column label or number
1346
1363
   of an output column, as in:
1347
1364
<programlisting>
1348
1365
SELECT a + b AS sum, c FROM table1 ORDER BY sum;
1349
1366
SELECT a, max(b) FROM table1 GROUP BY a ORDER BY 1;
1350
1367
</programlisting>
1351
1368
   both of which sort by the first output column.  Note that an output
1352
 
   column name has to stand alone, it's not allowed as part of an expression
 
1369
   column name has to stand alone, e.g., it cannot be used in an expression
1353
1370
   &mdash; for example, this is <emphasis>not</> correct:
1354
1371
<programlisting>
1355
1372
SELECT a + b AS sum, c FROM table1 ORDER BY sum + c;          -- wrong
1412
1429
 
1413
1430
  <para>
1414
1431
   When using <literal>LIMIT</>, it is important to use an
1415
 
   <literal>ORDER BY</> clause that constrains the result rows into a
 
1432
   <literal>ORDER BY</> clause that constrains the result rows in a
1416
1433
   unique order.  Otherwise you will get an unpredictable subset of
1417
1434
   the query's rows. You might be asking for the tenth through
1418
 
   twentieth rows, but tenth through twentieth in what ordering?  The
 
1435
   twentieth rows, but tenth through twentieth using what ordering? The
1419
1436
   ordering is unknown, unless you specified <literal>ORDER BY</>.
1420
1437
  </para>
1421
1438
 
1422
1439
  <para>
1423
1440
   The query optimizer takes <literal>LIMIT</> into account when
1424
 
   generating a query plan, so you are very likely to get different
 
1441
   generating query plans, so you are very likely to get different
1425
1442
   plans (yielding different row orders) depending on what you give
1426
1443
   for <literal>LIMIT</> and <literal>OFFSET</>.  Thus, using
1427
1444
   different <literal>LIMIT</>/<literal>OFFSET</> values to select
1455
1472
<synopsis>
1456
1473
VALUES ( <replaceable class="PARAMETER">expression</replaceable> [, ...] ) [, ...]
1457
1474
</synopsis>
1458
 
   Each parenthesized list of expressions generates a row in the table.
 
1475
   Each parenthesized list of expressions generates a row in the table expression.
1459
1476
   The lists must all have the same number of elements (i.e., the number
1460
1477
   of columns in the table), and corresponding entries in each list must
1461
1478
   have compatible data types.  The actual data type assigned to each column
1489
1506
 
1490
1507
  <para>
1491
1508
   Syntactically, <literal>VALUES</> followed by expression lists is
1492
 
   treated as equivalent to
 
1509
   treated as equivalent to:
1493
1510
<synopsis>
1494
1511
SELECT <replaceable>select_list</replaceable> FROM <replaceable>table_expression</replaceable>
1495
1512
</synopsis>
1496
1513
   and can appear anywhere a <literal>SELECT</> can.  For example, you can
1497
 
   use it as an arm of a <literal>UNION</>, or attach a
 
1514
   use it as part of a <literal>UNION</>, or attach a
1498
1515
   <replaceable>sort_specification</replaceable> (<literal>ORDER BY</>,
1499
1516
   <literal>LIMIT</>, and/or <literal>OFFSET</>) to it.  <literal>VALUES</>
1500
1517
   is most commonly used as the data source in an <command>INSERT</> command,