ddl.sgml 93.8 KB
Newer Older
1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.46 2005/11/01 23:19:05 neilc Exp $ -->
P
Peter Eisentraut 已提交
2 3 4 5 6 7 8 9 10 11 12

<chapter id="ddl">
 <title>Data Definition</title>

 <para>
  This chapter covers how one creates the database structures that
  will hold one's data.  In a relational database, the raw data is
  stored in tables, so the majority of this chapter is devoted to
  explaining how tables are created and modified and what features are
  available to control what data is stored in the tables.
  Subsequently, we discuss how tables can be organized into
13
  schemas, and how privileges can be assigned to tables.  Finally,
P
Peter Eisentraut 已提交
14
  we will briefly look at other features that affect the data storage,
T
Tom Lane 已提交
15
  such as views, functions, and triggers.
P
Peter Eisentraut 已提交
16 17 18 19 20
 </para>

 <sect1 id="ddl-basics">
  <title>Table Basics</title>

P
Peter Eisentraut 已提交
21 22 23 24 25 26 27 28 29 30 31 32
  <indexterm zone="ddl-basics">
   <primary>table</primary>
  </indexterm>

  <indexterm>
   <primary>row</primary>
  </indexterm>

  <indexterm>
   <primary>column</primary>
  </indexterm>

P
Peter Eisentraut 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  <para>
   A table in a relational database is much like a table on paper: It
   consists of rows and columns.  The number and order of the columns
   is fixed, and each column has a name.  The number of rows is
   variable -- it reflects how much data is stored at a given moment.
   SQL does not make any guarantees about the order of the rows in a
   table.  When a table is read, the rows will appear in random order,
   unless sorting is explicitly requested.  This is covered in <xref
   linkend="queries">.  Furthermore, SQL does not assign unique
   identifiers to rows, so it is possible to have several completely
   identical rows in a table.  This is a consequence of the
   mathematical model that underlies SQL but is usually not desirable.
   Later in this chapter we will see how to deal with this issue.
  </para>

  <para>
   Each column has a data type.  The data type constrains the set of
   possible values that can be assigned to a column and assigns
   semantics to the data stored in the column so that it can be used
   for computations.  For instance, a column declared to be of a
   numerical type will not accept arbitrary text strings, and the data
   stored in such a column can be used for mathematical computations.
   By contrast, a column declared to be of a character string type
   will accept almost any kind of data but it does not lend itself to
   mathematical calculations, although other operations such as string
   concatenation are available.
  </para>

  <para>
   <productname>PostgreSQL</productname> includes a sizable set of
   built-in data types that fit many applications.  Users can also
   define their own data types.  Most built-in data types have obvious
   names and semantics, so we defer a detailed explanation to <xref
   linkend="datatype">.  Some of the frequently used data types are
   <type>integer</type> for whole numbers, <type>numeric</type> for
   possibly fractional numbers, <type>text</type> for character
   strings, <type>date</type> for dates, <type>time</type> for
   time-of-day values, and <type>timestamp</type> for values
   containing both date and time.
  </para>

P
Peter Eisentraut 已提交
74 75 76 77 78
  <indexterm>
   <primary>table</primary>
   <secondary>creating</secondary>
  </indexterm>

P
Peter Eisentraut 已提交
79
  <para>
80 81
   To create a table, you use the aptly named <command>CREATE
   TABLE</command> command.  In this command you specify at least a
P
Peter Eisentraut 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   name for the new table, the names of the columns and the data type
   of each column.  For example:
<programlisting>
CREATE TABLE my_first_table (
    first_column text,
    second_column integer
);
</programlisting>
   This creates a table named <literal>my_first_table</literal> with
   two columns.  The first column is named
   <literal>first_column</literal> and has a data type of
   <type>text</type>; the second column has the name
   <literal>second_column</literal> and the type <type>integer</type>.
   The table and column names follow the identifier syntax explained
   in <xref linkend="sql-syntax-identifiers">.  The type names are
97
   usually also identifiers, but there are some exceptions.  Note that the
P
Peter Eisentraut 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
   column list is comma-separated and surrounded by parentheses.
  </para>

  <para>
   Of course, the previous example was heavily contrived.  Normally,
   you would give names to your tables and columns that convey what
   kind of data they store.  So let's look at a more realistic
   example:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric
);
</programlisting>
   (The <type>numeric</type> type can store fractional components, as
   would be typical of monetary amounts.)
  </para>

  <tip>
   <para>
    When you create many interrelated tables it is wise to choose a
120
    consistent naming pattern for the tables and columns.  For
P
Peter Eisentraut 已提交
121 122 123 124 125 126 127 128 129 130 131 132
    instance, there is a choice of using singular or plural nouns for
    table names, both of which are favored by some theorist or other.
   </para>
  </tip>

  <para>
   There is a limit on how many columns a table can contain.
   Depending on the column types, it is between 250 and 1600.
   However, defining a table with anywhere near this many columns is
   highly unusual and often a questionable design.
  </para>

P
Peter Eisentraut 已提交
133 134 135 136 137
  <indexterm>
   <primary>table</primary>
   <secondary>removing</secondary>
  </indexterm>

P
Peter Eisentraut 已提交
138
  <para>
139 140
   If you no longer need a table, you can remove it using the
   <command>DROP TABLE</command> command.  For example:
P
Peter Eisentraut 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
<programlisting>
DROP TABLE my_first_table;
DROP TABLE products;
</programlisting>
   Attempting to drop a table that does not exist is an error.
   Nevertheless, it is common in SQL script files to unconditionally
   try to drop each table before creating it, ignoring the error
   messages.
  </para>

  <para>
   If you need to modify a table that already exists look into <xref
   linkend="ddl-alter"> later in this chapter.
  </para>

  <para>
   With the tools discussed so far you can create fully functional
   tables.  The remainder of this chapter is concerned with adding
   features to the table definition to ensure data integrity,
   security, or convenience.  If you are eager to fill your tables with
   data now you can skip ahead to <xref linkend="dml"> and read the
   rest of this chapter later.
  </para>
 </sect1>

166
 <sect1 id="ddl-default">
P
Peter Eisentraut 已提交
167 168
  <title>Default Values</title>

P
Peter Eisentraut 已提交
169 170 171 172
  <indexterm zone="ddl-default">
   <primary>default value</primary>
  </indexterm>

P
Peter Eisentraut 已提交
173 174 175 176 177
  <para>
   A column can be assigned a default value.  When a new row is
   created and no values are specified for some of the columns, the
   columns will be filled with their respective default values.  A
   data manipulation command can also request explicitly that a column
178
   be set to its default value, without having to know what that value is.
179
   (Details about data manipulation commands are in <xref linkend="dml">.)
P
Peter Eisentraut 已提交
180 181 182
  </para>

  <para>
P
Peter Eisentraut 已提交
183
   <indexterm><primary>null value</primary><secondary>default value</secondary></indexterm>
184 185 186
   If no default value is declared explicitly, the default value is the
   null value.  This usually makes sense because a null value can
   be considered to represent unknown data.
P
Peter Eisentraut 已提交
187 188 189 190 191 192 193
  </para>

  <para>
   In a table definition, default values are listed after the column
   data type.  For example:
<programlisting>
CREATE TABLE products (
194
    product_no integer,
P
Peter Eisentraut 已提交
195 196 197 198 199 200 201
    name text,
    price numeric <emphasis>DEFAULT 9.99</emphasis>
);
</programlisting>
  </para>

  <para>
T
Tom Lane 已提交
202
   The default value may be an expression, which will be
P
Peter Eisentraut 已提交
203
   evaluated whenever the default value is inserted
204 205
   (<emphasis>not</emphasis> when the table is created).  A common example
   is that a timestamp column may have a default of <literal>now()</>,
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
   so that it gets set to the time of row insertion.  Another common
   example is generating a <quote>serial number</> for each row.
   In <productname>PostgreSQL</productname> this is typically done by
   something like
<programlisting>
CREATE TABLE products (
    product_no integer <emphasis>DEFAULT nextval('products_product_no_seq')</emphasis>,
    ...
);
</programlisting>
   where the <literal>nextval()</> function supplies successive values
   from a <firstterm>sequence object</> (see <xref
   linkend="functions-sequence">). This arrangement is sufficiently common
   that there's a special shorthand for it:
<programlisting>
CREATE TABLE products (
    product_no <emphasis>SERIAL</emphasis>,
    ...
);
</programlisting>
   The <literal>SERIAL</> shorthand is discussed further in <xref
   linkend="datatype-serial">.
P
Peter Eisentraut 已提交
228 229 230 231 232 233
  </para>
 </sect1>

 <sect1 id="ddl-constraints">
  <title>Constraints</title>

P
Peter Eisentraut 已提交
234 235 236 237
  <indexterm zone="ddl-constraints">
   <primary>constraint</primary>
  </indexterm>

P
Peter Eisentraut 已提交
238 239 240 241 242
  <para>
   Data types are a way to limit the kind of data that can be stored
   in a table.  For many applications, however, the constraint they
   provide is too coarse.  For example, a column containing a product
   price should probably only accept positive values.  But there is no
T
Tom Lane 已提交
243
   standard data type that accepts only positive numbers.  Another issue is
P
Peter Eisentraut 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
   that you might want to constrain column data with respect to other
   columns or rows.  For example, in a table containing product
   information, there should only be one row for each product number.
  </para>

  <para>
   To that end, SQL allows you to define constraints on columns and
   tables.  Constraints give you as much control over the data in your
   tables as you wish.  If a user attempts to store data in a column
   that would violate a constraint, an error is raised.  This applies
   even if the value came from the default value definition.
  </para>

  <sect2>
   <title>Check Constraints</title>

P
Peter Eisentraut 已提交
260 261 262 263 264 265 266 267 268
   <indexterm>
    <primary>check constraint</primary>
   </indexterm>

   <indexterm>
    <primary>constraint</primary>
    <secondary>check</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
269 270
   <para>
    A check constraint is the most generic constraint type.  It allows
T
Tom Lane 已提交
271 272 273
    you to specify that the value in a certain column must satisfy a
    Boolean (truth-value) expression.  For instance, to require positive
    product prices, you could use:
P
Peter Eisentraut 已提交
274 275 276 277
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
278
    price numeric <emphasis>CHECK (price &gt; 0)</emphasis>
P
Peter Eisentraut 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292
);
</programlisting>
   </para>

   <para>
    As you see, the constraint definition comes after the data type,
    just like default value definitions.  Default values and
    constraints can be listed in any order.  A check constraint
    consists of the key word <literal>CHECK</literal> followed by an
    expression in parentheses.  The check constraint expression should
    involve the column thus constrained, otherwise the constraint
    would not make too much sense.
   </para>

P
Peter Eisentraut 已提交
293 294 295 296 297
   <indexterm>
    <primary>constraint</primary>
    <secondary>name</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
298 299 300 301 302 303 304 305
   <para>
    You can also give the constraint a separate name.  This clarifies
    error messages and allows you to refer to the constraint when you
    need to change it.  The syntax is:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
306
    price numeric <emphasis>CONSTRAINT positive_price</emphasis> CHECK (price &gt; 0)
P
Peter Eisentraut 已提交
307 308
);
</programlisting>
309
    So, to specify a named constraint, use the key word
P
Peter Eisentraut 已提交
310
    <literal>CONSTRAINT</literal> followed by an identifier followed
T
Tom Lane 已提交
311 312
    by the constraint definition.  (If you don't specify a constraint
    name in this way, the system chooses a name for you.)
P
Peter Eisentraut 已提交
313 314 315 316 317 318 319 320 321 322
   </para>

   <para>
    A check constraint can also refer to several columns.  Say you
    store a regular price and a discounted price, and you want to
    ensure that the discounted price is lower than the regular price.
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
323 324 325
    price numeric CHECK (price &gt; 0),
    discounted_price numeric CHECK (discounted_price &gt; 0),
    <emphasis>CHECK (price &gt; discounted_price)</emphasis>
P
Peter Eisentraut 已提交
326 327 328 329 330 331 332 333
);
</programlisting>
   </para>

   <para>
    The first two constraints should look familiar.  The third one
    uses a new syntax.  It is not attached to a particular column,
    instead it appears as a separate item in the comma-separated
334
    column list.  Column definitions and these constraint
P
Peter Eisentraut 已提交
335 336 337 338
    definitions can be listed in mixed order.
   </para>

   <para>
339
    We say that the first two constraints are column constraints, whereas the
P
Peter Eisentraut 已提交
340
    third one is a table constraint because it is written separately
T
Tom Lane 已提交
341
    from any one column definition.  Column constraints can also be
P
Peter Eisentraut 已提交
342
    written as table constraints, while the reverse is not necessarily
T
Tom Lane 已提交
343 344 345 346 347
    possible, since a column constraint is supposed to refer to only the
    column it is attached to.  (<productname>PostgreSQL</productname> doesn't
    enforce that rule, but you should follow it if you want your table
    definitions to work with other database systems.)  The above example could
    also be written as
P
Peter Eisentraut 已提交
348 349 350 351 352
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
353
    CHECK (price &gt; 0),
P
Peter Eisentraut 已提交
354
    discounted_price numeric,
355 356
    CHECK (discounted_price &gt; 0),
    CHECK (price &gt; discounted_price)
P
Peter Eisentraut 已提交
357 358 359 360 361 362 363
);
</programlisting>
    or even
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
364
    price numeric CHECK (price &gt; 0),
P
Peter Eisentraut 已提交
365
    discounted_price numeric,
366
    CHECK (discounted_price &gt; 0 AND price &gt; discounted_price)
P
Peter Eisentraut 已提交
367 368 369 370 371
);
</programlisting>
    It's a matter of taste.
   </para>

T
Tom Lane 已提交
372 373 374 375 376 377 378 379
   <para>
    Names can be assigned to table constraints in just the same way as
    for column constraints:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
380
    CHECK (price &gt; 0),
T
Tom Lane 已提交
381
    discounted_price numeric,
382 383
    CHECK (discounted_price &gt; 0),
    <emphasis>CONSTRAINT valid_discount</> CHECK (price &gt; discounted_price)
T
Tom Lane 已提交
384 385 386 387
);
</programlisting>
   </para>

P
Peter Eisentraut 已提交
388 389 390 391 392
   <indexterm>
    <primary>null value</primary>
    <secondary sortas="check constraints">with check constraints</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
393 394
   <para>
    It should be noted that a check constraint is satisfied if the
395
    check expression evaluates to true or the null value.  Since most
T
Tom Lane 已提交
396
    expressions will evaluate to the null value if any operand is null,
397 398
    they will not prevent null values in the constrained columns.  To
    ensure that a column does not contain null values, the not-null
399
    constraint described in the next section can be used.
P
Peter Eisentraut 已提交
400
   </para>
401 402 403 404 405 406 407

    <para>
     Check constraints can also be used to enhance performance with
     very large tables, when used in conjunction with the <xref
     linkend="guc-constraint-exclusion"> parameter.  This is discussed
     in more detail in <xref linkend="ce-partitioning">.
   </para>
P
Peter Eisentraut 已提交
408 409 410 411 412
  </sect2>

  <sect2>
   <title>Not-Null Constraints</title>

P
Peter Eisentraut 已提交
413 414 415 416 417 418 419 420 421
   <indexterm>
    <primary>not-null constraint</primary>
   </indexterm>

   <indexterm>
    <primary>constraint</primary>
    <secondary>NOT NULL</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435
   <para>
    A not-null constraint simply specifies that a column must not
    assume the null value.  A syntax example:
<programlisting>
CREATE TABLE products (
    product_no integer <emphasis>NOT NULL</emphasis>,
    name text <emphasis>NOT NULL</emphasis>,
    price numeric
);
</programlisting>
   </para>

   <para>
    A not-null constraint is always written as a column constraint.  A
436 437 438 439 440
    not-null constraint is functionally equivalent to creating a check
    constraint <literal>CHECK (<replaceable>column_name</replaceable>
    IS NOT NULL)</literal>, but in
    <productname>PostgreSQL</productname> creating an explicit
    not-null constraint is more efficient.  The drawback is that you
T
Tom Lane 已提交
441
    cannot give explicit names to not-null constraints created this
442
    way.
P
Peter Eisentraut 已提交
443 444 445 446
   </para>

   <para>
    Of course, a column can have more than one constraint.  Just write
T
Tom Lane 已提交
447
    the constraints one after another:
P
Peter Eisentraut 已提交
448 449 450 451
<programlisting>
CREATE TABLE products (
    product_no integer NOT NULL,
    name text NOT NULL,
452
    price numeric NOT NULL CHECK (price &gt; 0)
P
Peter Eisentraut 已提交
453 454
);
</programlisting>
T
Tom Lane 已提交
455
    The order doesn't matter.  It does not necessarily determine in which
P
Peter Eisentraut 已提交
456 457 458 459 460 461 462
    order the constraints are checked.
   </para>

   <para>
    The <literal>NOT NULL</literal> constraint has an inverse: the
    <literal>NULL</literal> constraint.  This does not mean that the
    column must be null, which would surely be useless.  Instead, this
T
Tom Lane 已提交
463
    simply selects the default behavior that the column may be null.
P
Peter Eisentraut 已提交
464 465 466
    The <literal>NULL</literal> constraint is not defined in the SQL
    standard and should not be used in portable applications.  (It was
    only added to <productname>PostgreSQL</productname> to be
T
Tom Lane 已提交
467
    compatible with some other database systems.)  Some users, however,
P
Peter Eisentraut 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    like it because it makes it easy to toggle the constraint in a
    script file.  For example, you could start with
<programlisting>
CREATE TABLE products (
    product_no integer NULL,
    name text NULL,
    price numeric NULL
);
</programlisting>
    and then insert the <literal>NOT</literal> key word where desired.
   </para>

   <tip>
    <para>
     In most database designs the majority of columns should be marked
     not null.
    </para>
   </tip>
  </sect2>

  <sect2>
   <title>Unique Constraints</title>

P
Peter Eisentraut 已提交
491 492 493 494 495 496 497 498 499
   <indexterm>
    <primary>unique constraint</primary>
   </indexterm>

   <indexterm>
    <primary>constraint</primary>
    <secondary>unique</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
   <para>
    Unique constraints ensure that the data contained in a column or a
    group of columns is unique with respect to all the rows in the
    table.  The syntax is
<programlisting>
CREATE TABLE products (
    product_no integer <emphasis>UNIQUE</emphasis>,
    name text,
    price numeric
);
</programlisting>
    when written as a column constraint, and
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    <emphasis>UNIQUE (product_no)</emphasis>
);
</programlisting>
    when written as a table constraint.
   </para>

   <para>
    If a unique constraint refers to a group of columns, the columns
    are listed separated by commas:
<programlisting>
CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    <emphasis>UNIQUE (a, c)</emphasis>
);
</programlisting>
T
Tom Lane 已提交
534 535 536
    This specifies that the combination of values in the indicated columns
    is unique across the whole table, though any one of the columns
    need not be (and ordinarily isn't) unique.
P
Peter Eisentraut 已提交
537 538 539
   </para>

   <para>
T
Tom Lane 已提交
540
    You can assign your own name for a unique constraint, in the usual way:
P
Peter Eisentraut 已提交
541 542 543 544 545 546 547 548 549
<programlisting>
CREATE TABLE products (
    product_no integer <emphasis>CONSTRAINT must_be_different</emphasis> UNIQUE,
    name text,
    price numeric
);
</programlisting>
   </para>

P
Peter Eisentraut 已提交
550 551 552 553 554
   <indexterm>
    <primary>null value</primary>
    <secondary sortas="unique constraints">with unique constraints</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
555
   <para>
556 557 558
    In general, a unique constraint is violated when there are two or
    more rows in the table where the values of all of the
    columns included in the constraint are equal.
P
Peter Eisentraut 已提交
559
    However, null values are not considered equal in this
560
    comparison.  That means even in the presence of a
T
Tom Lane 已提交
561
    unique constraint it is possible to store duplicate
P
Peter Eisentraut 已提交
562 563 564 565 566 567 568 569 570 571 572
    rows that contain a null value in at least one of the constrained
    columns.  This behavior conforms to the SQL standard, but we have
    heard that other SQL databases may not follow this rule.  So be
    careful when developing applications that are intended to be
    portable.
   </para>
  </sect2>

  <sect2>
   <title>Primary Keys</title>

P
Peter Eisentraut 已提交
573 574 575 576 577 578 579 580 581
   <indexterm>
    <primary>primary key</primary>
   </indexterm>

   <indexterm>
    <primary>constraint</primary>
    <secondary>primary key</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
   <para>
    Technically, a primary key constraint is simply a combination of a
    unique constraint and a not-null constraint.  So, the following
    two table definitions accept the same data:
<programlisting>
CREATE TABLE products (
    product_no integer UNIQUE NOT NULL,
    name text,
    price numeric
);
</programlisting>

<programlisting>
CREATE TABLE products (
    product_no integer <emphasis>PRIMARY KEY</emphasis>,
    name text,
    price numeric
);
</programlisting>
   </para>

   <para>
    Primary keys can also constrain more than one column; the syntax
    is similar to unique constraints:
<programlisting>
CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    <emphasis>PRIMARY KEY (a, c)</emphasis>
);
</programlisting>
   </para>

   <para>
    A primary key indicates that a column or group of columns can be
    used as a unique identifier for rows in the table.  (This is a
    direct consequence of the definition of a primary key.  Note that
T
Tom Lane 已提交
620
    a unique constraint does not, by itself, provide a unique identifier
P
Peter Eisentraut 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
    because it does not exclude null values.)  This is useful both for
    documentation purposes and for client applications.  For example,
    a GUI application that allows modifying row values probably needs
    to know the primary key of a table to be able to identify rows
    uniquely.
   </para>

   <para>
    A table can have at most one primary key (while it can have many
    unique and not-null constraints).  Relational database theory
    dictates that every table must have a primary key.  This rule is
    not enforced by <productname>PostgreSQL</productname>, but it is
    usually best to follow it.
   </para>
  </sect2>

  <sect2 id="ddl-constraints-fk">
   <title>Foreign Keys</title>

P
Peter Eisentraut 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652
   <indexterm>
    <primary>foreign key</primary>
   </indexterm>

   <indexterm>
    <primary>constraint</primary>
    <secondary>foreign key</secondary>
   </indexterm>

   <indexterm>
    <primary>referential integrity</primary>
   </indexterm>

P
Peter Eisentraut 已提交
653 654
   <para>
    A foreign key constraint specifies that the values in a column (or
655 656
    a group of columns) must match the values appearing in some row
    of another table.
P
Peter Eisentraut 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
    We say this maintains the <firstterm>referential
    integrity</firstterm> between two related tables.
   </para>

   <para>
    Say you have the product table that we have used several times already:
<programlisting>
CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);
</programlisting>
    Let's also assume you have a table storing orders of those
    products.  We want to ensure that the orders table only contains
    orders of products that actually exist.  So we define a foreign
    key constraint in the orders table that references the products
    table:
<programlisting>
CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer <emphasis>REFERENCES products (product_no)</emphasis>,
    quantity integer
);
</programlisting>
    Now it is impossible to create orders with
683
    <structfield>product_no</structfield> entries that do not appear in the
P
Peter Eisentraut 已提交
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
    products table.
   </para>

   <para>
    We say that in this situation the orders table is the
    <firstterm>referencing</firstterm> table and the products table is
    the <firstterm>referenced</firstterm> table.  Similarly, there are
    referencing and referenced columns.
   </para>

   <para>
    You can also shorten the above command to
<programlisting>
CREATE TABLE orders (
    order_id integer PRIMARY KEY,
T
Tom Lane 已提交
699
    product_no integer <emphasis>REFERENCES products</emphasis>,
P
Peter Eisentraut 已提交
700 701 702 703
    quantity integer
);
</programlisting>
    because in absence of a column list the primary key of the
704
    referenced table is used as the referenced column(s).
P
Peter Eisentraut 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718
   </para>

   <para>
    A foreign key can also constrain and reference a group of columns.
    As usual, it then needs to be written in table constraint form.
    Here is a contrived syntax example:
<programlisting>
CREATE TABLE t1 (
  a integer PRIMARY KEY,
  b integer,
  c integer,
  <emphasis>FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)</emphasis>
);
</programlisting>
T
Tom Lane 已提交
719
    Of course, the number and type of the constrained columns need to
720
    match the number and type of the referenced columns.
P
Peter Eisentraut 已提交
721 722
   </para>

T
Tom Lane 已提交
723 724 725 726 727
   <para>
    You can assign your own name for a foreign key constraint,
    in the usual way.
   </para>

P
Peter Eisentraut 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
   <para>
    A table can contain more than one foreign key constraint.  This is
    used to implement many-to-many relationships between tables.  Say
    you have tables about products and orders, but now you want to
    allow one order to contain possibly many products (which the
    structure above did not allow).  You could use this table structure:
<programlisting>
CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    shipping_address text,
    ...
);

CREATE TABLE order_items (
    product_no integer REFERENCES products,
    order_id integer REFERENCES orders,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);
</programlisting>
T
Tom Lane 已提交
754
    Notice that the primary key overlaps with the foreign keys in
P
Peter Eisentraut 已提交
755 756 757
    the last table.
   </para>

P
Peter Eisentraut 已提交
758 759 760 761 762 763 764 765 766 767
   <indexterm>
    <primary>CASCADE</primary>
    <secondary>foreign key action</secondary>
   </indexterm>

   <indexterm>
    <primary>RESTRICT</primary>
    <secondary>foreign key action</secondary>
   </indexterm>

P
Peter Eisentraut 已提交
768 769
   <para>
    We know that the foreign keys disallow creation of orders that
770
    do not relate to any products.  But what if a product is removed
P
Peter Eisentraut 已提交
771
    after an order is created that references it?  SQL allows you to
772
    handle that as well.  Intuitively, we have a few options:
P
Peter Eisentraut 已提交
773 774 775 776 777 778 779 780 781
    <itemizedlist spacing="compact">
     <listitem><para>Disallow deleting a referenced product</para></listitem>
     <listitem><para>Delete the orders as well</para></listitem>
     <listitem><para>Something else?</para></listitem>
    </itemizedlist>
   </para>

   <para>
    To illustrate this, let's implement the following policy on the
782
    many-to-many relationship example above: when someone wants to
P
Peter Eisentraut 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
    remove a product that is still referenced by an order (via
    <literal>order_items</literal>), we disallow it.  If someone
    removes an order, the order items are removed as well.
<programlisting>
CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    shipping_address text,
    ...
);

CREATE TABLE order_items (
    product_no integer REFERENCES products <emphasis>ON DELETE RESTRICT</emphasis>,
    order_id integer REFERENCES orders <emphasis>ON DELETE CASCADE</emphasis>,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);
</programlisting>
   </para>

   <para>
    Restricting and cascading deletes are the two most common options.
810
    <literal>RESTRICT</literal> prevents deletion of a
811 812
    referenced row. <literal>NO ACTION</literal> means that if any
    referencing rows still exist when the constraint is checked, an error
813 814
    is raised; this is the default behavior if you do not specify anything.
    (The essential difference between these two choices is that
815 816
    <literal>NO ACTION</literal> allows the check to be deferred until
    later in the transaction, whereas <literal>RESTRICT</literal> does not.)
817 818
    <literal>CASCADE</> specifies that when a referenced row is deleted,
    row(s) referencing it should be automatically deleted as well.
819
    There are two other options:
P
Peter Eisentraut 已提交
820
    <literal>SET NULL</literal> and <literal>SET DEFAULT</literal>.
821 822
    These cause the referencing columns to be set to nulls or default
    values, respectively, when the referenced row is deleted.
P
Peter Eisentraut 已提交
823 824 825
    Note that these do not excuse you from observing any constraints.
    For example, if an action specifies <literal>SET DEFAULT</literal>
    but the default value would not satisfy the foreign key, the
826
    operation will fail.
P
Peter Eisentraut 已提交
827 828 829 830
   </para>

   <para>
    Analogous to <literal>ON DELETE</literal> there is also
831 832
    <literal>ON UPDATE</literal> which is invoked when a referenced
    column is changed (updated).  The possible actions are the same.
P
Peter Eisentraut 已提交
833 834 835 836 837 838 839 840 841
   </para>

   <para>
    More information about updating and deleting data is in <xref
    linkend="dml">.
   </para>

   <para>
    Finally, we should mention that a foreign key must reference
842
    columns that either are a primary key or form a unique constraint.
P
Peter Eisentraut 已提交
843 844
    If the foreign key references a unique constraint, there are some
    additional possibilities regarding how null values are matched.
845 846
    These are explained in the reference documentation for
    <xref linkend="sql-createtable" endterm="sql-createtable-title">.
P
Peter Eisentraut 已提交
847 848 849 850
   </para>
  </sect2>
 </sect1>

T
Tom Lane 已提交
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
 <sect1 id="ddl-system-columns">
  <title>System Columns</title>

  <para>
   Every table has several <firstterm>system columns</> that are
   implicitly defined by the system.  Therefore, these names cannot be
   used as names of user-defined columns.  (Note that these
   restrictions are separate from whether the name is a key word or
   not; quoting a name will not allow you to escape these
   restrictions.)  You do not really need to be concerned about these
   columns, just know they exist.
  </para>

  <indexterm>
   <primary>column</primary>
   <secondary>system column</secondary>
  </indexterm>

  <variablelist>
   <varlistentry>
    <term><structfield>oid</></term>
    <listitem>
     <para>
      <indexterm>
       <primary>OID</primary>
       <secondary>column</secondary>
      </indexterm>
878 879 880
      The object identifier (object ID) of a row. This column is only
      present if the table was created using <literal>WITH
      OIDS</literal>, or if the <xref linkend="guc-default-with-oids">
881
      configuration variable was set. This column is of type
T
Tom Lane 已提交
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
      <type>oid</type> (same name as the column); see <xref
      linkend="datatype-oid"> for more information about the type.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term><structfield>tableoid</></term>
    <listitem>
     <indexterm>
      <primary>tableoid</primary>
     </indexterm>

     <para>
      The OID of the table containing this row.  This column is
      particularly handy for queries that select from inheritance
      hierarchies, since without it, it's difficult to tell which
      individual table a row came from.  The
      <structfield>tableoid</structfield> can be joined against the
      <structfield>oid</structfield> column of
      <structname>pg_class</structname> to obtain the table name.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term><structfield>xmin</></term>
    <listitem>
     <indexterm>
      <primary>xmin</primary>
     </indexterm>

     <para>
      The identity (transaction ID) of the inserting transaction for
      this row version.  (A row version is an individual state of a
      row; each update of a row creates a new row version for the same
      logical row.)
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term><structfield>cmin</></term>
    <listitem>
     <indexterm>
      <primary>cmin</primary>
     </indexterm>

     <para>
      The command identifier (starting at zero) within the inserting
      transaction.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term><structfield>xmax</></term>
    <listitem>
     <indexterm>
      <primary>xmax</primary>
     </indexterm>

     <para>
      The identity (transaction ID) of the deleting transaction, or
      zero for an undeleted row version.  It is possible for this column to
      be nonzero in a visible row version. That usually indicates that the
      deleting transaction hasn't committed yet, or that an attempted
      deletion was rolled back.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term><structfield>cmax</></term>
    <listitem>
     <indexterm>
      <primary>cmax</primary>
     </indexterm>

     <para>
      The command identifier within the deleting transaction, or zero.
     </para>
    </listitem>
   </varlistentry>

   <varlistentry>
    <term><structfield>ctid</></term>
    <listitem>
     <indexterm>
      <primary>ctid</primary>
     </indexterm>

     <para>
      The physical location of the row version within its table.  Note that
      although the <structfield>ctid</structfield> can be used to
      locate the row version very quickly, a row's
      <structfield>ctid</structfield> will change each time it is
      updated or moved by <command>VACUUM FULL</>.  Therefore
      <structfield>ctid</structfield> is useless as a long-term row
      identifier.  The OID, or even better a user-defined serial
      number, should be used to identify logical rows.
     </para>
    </listitem>
   </varlistentry>
  </variablelist>

   <para>
    OIDs are 32-bit quantities and are assigned from a single
    cluster-wide counter.  In a large or long-lived database, it is
    possible for the counter to wrap around.  Hence, it is bad
    practice to assume that OIDs are unique, unless you take steps to
    ensure that this is the case.  If you need to identify the rows in
    a table, using a sequence generator is strongly recommended.
    However, OIDs can be used as well, provided that a few additional
    precautions are taken:

    <itemizedlist>
     <listitem>
      <para>
       A unique constraint should be created on the OID column of each
1002 1003 1004 1005 1006 1007 1008
       table for which the OID will be used to identify rows.  When such
       a unique constraint (or unique index) exists, the system takes
       care not to generate an OID matching an already-existing row.
       (Of course, this is only possible if the table contains fewer
       than 2<superscript>32</> (4 billion) rows, and in practice the
       table size had better be much less than that, or performance
       may suffer.)
T
Tom Lane 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
      </para>
     </listitem>
     <listitem>
      <para>
       OIDs should never be assumed to be unique across tables; use
       the combination of <structfield>tableoid</> and row OID if you
       need a database-wide identifier.
      </para>
     </listitem>
     <listitem>
      <para>
       The tables in question should be created using <literal>WITH
1021 1022
       OIDS</literal>.  As of <productname>PostgreSQL</productname> 8.1,
       <literal>WITHOUT OIDS</> is the default.
T
Tom Lane 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
      </para>
     </listitem>
    </itemizedlist>
   </para>

   <para>
    Transaction identifiers are also 32-bit quantities.  In a
    long-lived database it is possible for transaction IDs to wrap
    around.  This is not a fatal problem given appropriate maintenance
    procedures; see <xref linkend="maintenance"> for details.  It is
    unwise, however, to depend on the uniqueness of transaction IDs
    over the long term (more than one billion transactions).
   </para>

   <para>
    Command
    identifiers are also 32-bit quantities.  This creates a hard limit
    of 2<superscript>32</> (4 billion) <acronym>SQL</acronym> commands
    within a single transaction.  In practice this limit is not a
    problem &mdash; note that the limit is on number of
    <acronym>SQL</acronym> commands, not number of rows processed.
   </para>
 </sect1>

P
Peter Eisentraut 已提交
1047 1048 1049
 <sect1 id="ddl-inherit">
  <title>Inheritance</title>

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
   <indexterm>
    <primary>not-null constraint</primary>
   </indexterm>

   <indexterm>
    <primary>constraint</primary>
    <secondary>NOT NULL</secondary>
   </indexterm>

  <para>
   <productname>PostgreSQL</productname> implements table inheritance
   which can be a useful tool for database designers.  The SQL:2003
   standard optionally defines type inheritance which differs in many
   respects from the features described here.
  </para>
P
Peter Eisentraut 已提交
1065 1066

  <para>
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
   Let's start with an example: suppose we are trying to build a data
   model for cities.  Each state has many cities, but only one
   capital. We want to be able to quickly retrieve the capital city
   for any particular state. This can be done by creating two tables,
   one for state capitals and one for cities that are not
   capitals. However, what happens when we want to ask for data about
   a city, regardless of whether it is a capital or not? The
   inheritance feature can help to resolve this problem. We define the
   <literal>capitals</literal> table so that it inherits from
   <literal>cities</literal>:
P
Peter Eisentraut 已提交
1077 1078 1079 1080 1081

<programlisting>
CREATE TABLE cities (
    name            text,
    population      float,
1082
    altitude        int     -- in feet
P
Peter Eisentraut 已提交
1083 1084 1085 1086 1087 1088 1089
);

CREATE TABLE capitals (
    state           char(2)
) INHERITS (cities);
</programlisting>

1090 1091 1092 1093
   In this case, a row of <literal>capitals</> <firstterm>inherits</>
   all the columns of its parent table, <literal>cities</>. State
   capitals have an extra attribute, <literal>state</>, that shows
   their state.
P
Peter Eisentraut 已提交
1094 1095 1096
  </para>

  <para>
1097 1098 1099 1100 1101 1102
   In <productname>PostgreSQL</productname>, a table can inherit from
   zero or more other tables, and a query can reference either all
   rows of a table or all rows of a table plus all of its descendants.
   For example, the following query finds the names of all cities,
   including state capitals, that are located at an altitude over
   500ft:
P
Peter Eisentraut 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

<programlisting>
SELECT name, altitude
    FROM cities
    WHERE altitude &gt; 500;
</programlisting>

   which returns:

<programlisting>
   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
 Madison   |      845
</programlisting>
  </para>

  <para>
1122 1123
   On the other hand, the following query finds all the cities that
   are not state capitals and are situated at an altitude over 500ft:
P
Peter Eisentraut 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

<programlisting>
SELECT name, altitude
    FROM ONLY cities
    WHERE altitude &gt; 500;

   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
1134
</programlisting>
P
Peter Eisentraut 已提交
1135 1136 1137
  </para>

  <para>
1138 1139 1140 1141 1142 1143 1144
   Here the <literal>ONLY</literal> keyword indicates that the query
   should apply only to <literal>cities</literal>, and not any tables
   below <literal>cities</literal> in the inheritance hierarchy.  Many
   of the commands that we have already discussed &mdash;
   <command>SELECT</command>, <command>UPDATE</command> and
   <command>DELETE</command> &mdash; support the
   <literal>ONLY</literal> keyword.
P
Peter Eisentraut 已提交
1145 1146
  </para>

1147
  <note>
1148
   <title>Inheritance and Permissions</title>
1149
   <para>
1150 1151 1152 1153 1154 1155
    Because permissions are not inherited automatically, a user
    attempting to access a parent table must either have at least the
    same permission for the child table or must use the
    <quote>ONLY</quote> notation. If creating a new inheritance
    relationship in an existing system be careful that this does not
    create problems.
1156 1157 1158
   </para>
  </note>

P
Peter Eisentraut 已提交
1159
  <para>
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
   Inheritance does not automatically propogate data from
   <command>INSERT</command> or <command>COPY</command> commands to
   other tables in the inheritance hierarchy. In our example, the
   following <command>INSERT</command> statement will fail:
<programlisting>
INSERT INTO cities
(name, population, altitude, state)
VALUES ('New York', NULL, NULL, 'NY');
</programlisting>
   We might hope that the data would be somehow routed to the
   <literal>capitals</literal> table, though this does not happen. If
   the child has no locally defined columns, then it is possible to
   route data from the parent to the child using a rule, see <xref
   linkend="rules-update">.  This is not possible with the above
   <command>INSERT</> statement because the <literal>state</> column
   does not exist on both parent and child tables.
  </para>

  <para>
   In some cases you may wish to know which table a particular row
   originated from. There is a system column called
   <structfield>tableoid</structfield> in each table which can tell you the
   originating table:
P
Peter Eisentraut 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

<programlisting>
SELECT c.tableoid, c.name, c.altitude
FROM cities c
WHERE c.altitude &gt; 500;
</programlisting>

   which returns:

<programlisting>
 tableoid |   name    | altitude
----------+-----------+----------
   139793 | Las Vegas |     2174
   139793 | Mariposa  |     1953
   139798 | Madison   |      845
</programlisting>

1200 1201 1202
   (If you try to reproduce this example, you will probably get
   different numeric OIDs.)  By doing a join with
   <structname>pg_class</> you can see the actual table names:
P
Peter Eisentraut 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

<programlisting>
SELECT p.relname, c.name, c.altitude
FROM cities c, pg_class p
WHERE c.altitude &gt; 500 and c.tableoid = p.oid;
</programlisting>

   which returns:

<programlisting>
 relname  |   name    | altitude
----------+-----------+----------
 cities   | Las Vegas |     2174
 cities   | Mariposa  |     1953
 capitals | Madison   |      845
</programlisting>
  </para>

1221
  <para>
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
   As shown above, a child table may locally define columns as well as
   inheriting them from their parents.  However, a locally defined
   column cannot override the datatype of an inherited column of the
   same name.  A table can inherit from a table that has itself
   inherited from other tables. A table can also inherit from more
   than one parent table, in which case it inherits the union of the
   columns defined by the parent tables.  Inherited columns with
   duplicate names and datatypes will be merged so that only a single
   column is stored.
  </para>

  <para>
   Table inheritance can currently only be defined using the <xref
   linkend="sql-createtable" endterm="sql-createtable-title">
   statement.  The related statement <literal>CREATE TABLE ... AS
   SELECT</literal> does not allow inheritance to be specified. There
   is no way to add an inheritance link to make an existing table into
   a child table. Similarly, there is no way to remove an inheritance
   link from a child table once it has been defined, other than using
   <literal>DROP TABLE</literal>.  A parent table cannot be dropped
   while any of its children remain. If you wish to remove a table and
   all of its descendants, then you can do so using the
   <literal>CASCADE</literal> option of the <xref
   linkend="sql-droptable" endterm="sql-droptable-title"> statement.
  </para>

  <para>
   Check constraints can be defined on tables within an inheritance
   hierarchy. All check constraints on a parent table are
   automatically inherited by all of their children. It is currently
   possible to inherit mutually exclusive check constraints, but that
   definition quickly shows itself since all attempted row inserts
   will be rejected.
  </para>

  <para>
   <xref linkend="sql-altertable" endterm="sql-altertable-title"> will
   propogate any changes in data definition on columns or check
   constraints down the inheritance hierarchy.  Again, dropping
   columns or constraints on parent tables is only possible when using
   the <literal>CASCADE</literal> option. <command>ALTER
   TABLE</command> follows the same rules for duplicate column merging
   and rejection that apply during <command>CREATE TABLE</command>.
1265 1266
  </para>

P
Peter Eisentraut 已提交
1267
  <para>
1268 1269 1270 1271 1272 1273 1274 1275 1276
   Both parent and child tables can have primary and foreign keys, so
   that they can take part normally on both the referencing and
   referenced sides of a foreign key constraint. Indexes may be
   defined on any of these columns whether or not they are inherited.
   However, a serious current limitation of the inheritance feature is
   that indexes (including unique constraints) and foreign key
   constraints only apply to single tables and do not also index their
   inheritance children.  This is true on both sides of a foreign key
   constraint.  Thus, in the terms of the above example:
1277 1278 1279 1280 1281 1282 1283 1284

   <itemizedlist>
    <listitem>
     <para>
      If we declared <structname>cities</>.<structfield>name</> to be
      <literal>UNIQUE</> or a <literal>PRIMARY KEY</>, this would not stop the
      <structname>capitals</> table from having rows with names duplicating
      rows in <structname>cities</>.  And those duplicate rows would by
P
Peter Eisentraut 已提交
1285
      default show up in queries from <structname>cities</>.  In fact, by
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
      default <structname>capitals</> would have no unique constraint at all,
      and so could contain multiple rows with the same name.
      You could add a unique constraint to <structname>capitals</>, but this
      would not prevent duplication compared to <structname>cities</>.
     </para>
    </listitem>

    <listitem>
     <para>
      Similarly, if we were to specify that
      <structname>cities</>.<structfield>name</> <literal>REFERENCES</> some
      other table, this constraint would not automatically propagate to
1298 1299 1300 1301 1302
      <structname>capitals</>.  However, it is possible to set up a
      foreign key such as <structname>capitals</>.<structfield>name</>
      <literal>REFERENCES</> <structname>states</>.<structfield>name</>.
      So it is possible to workaround this restriction by manually adding
      foreign keys to each child table.
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
     </para>
    </listitem>

    <listitem>
     <para>
      Specifying that another table's column <literal>REFERENCES
      cities(name)</> would allow the other table to contain city names, but
      not capital names.  There is no good workaround for this case.
     </para>
    </listitem>
   </itemizedlist>

   These deficiencies will probably be fixed in some future release,
   but in the meantime considerable care is needed in deciding whether
   inheritance is useful for your problem.
1318

P
Peter Eisentraut 已提交
1319
  </para>
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867

  <note>
   <title>Deprecated</title>
   <para>
     In previous versions of <productname>PostgreSQL</productname>, the
     default behavior was not to include child tables in queries. This was
     found to be error prone and is also in violation of the SQL:2003
     standard. Under the old syntax, to get the sub-tables you append
     <literal>*</literal> to the table name. For example:
<programlisting>
SELECT * from cities*;
</programlisting>
     You can still explicitly specify scanning child tables by
     appending <literal>*</literal>, as well as explicitly specify not
     scanning child tables by writing <quote>ONLY</quote>.  But
     beginning in version 7.1, the default behavior for an undecorated
     table name is to scan its child tables too, whereas before the
     default was not to do so.  To get the old default behavior,
     disable the <xref linkend="guc-sql-inheritance"> configuration
     option.
   </para>
  </note>

  </sect1>

  <sect1 id="ce-partitioning">
   <title>Constraint Exclusion and Partitioning</title>

   <indexterm>
    <primary>partitioning</primary>
   </indexterm>

   <indexterm>
    <primary>constraint exclusion</primary>
   </indexterm>

   <para>
    <productname>PostgreSQL</productname> supports basic table
    partitioning. This section describes why and how you can implement
    this as part of your database design.
   </para>

   <sect2 id="ce-partitioning-overview">
     <title>Overview</title>

   <para>
    Currently, partitioning is implemented in conjunction with table
    inheritance only, though using fully SQL:2003 compliant syntax.
    Table inheritance allows tables to be split into partitions, and
    constraint exclusion allows partitions to be selectively combined
    as needed to satisfy a particular <command>SELECT</command>
    statement. You should be familiar with inheritance (see <xref
    linkend="ddl-inherit">) before attempting to implement
    partitioning.
   </para>

   <para>
    Partitioning can provide several benefits:
   <itemizedlist>
    <listitem>
     <para>
      Query performance can be improved dramatically for certain kinds
      of queries without the need to maintain costly indexes.
     </para>
    </listitem>

    <listitem>
     <para>
      Insert performance can be improved by breaking down a large
      index into multiple pieces. When an index no longer fits easily
      in memory, both read and write operations on the index take
      progressively more disk accesses.
     </para>
    </listitem>

    <listitem>
     <para>
      Bulk deletes may be avoided altogether by simply removing one of the
      partitions, if that requirement is planned into the partitioning design.
     </para>
    </listitem>

    <listitem>
     <para>
      Seldom-used data can be migrated to cheaper and slower storage media.
     </para>
    </listitem>
   </itemizedlist>

    The benefits will normally be worthwhile only when a data table would
    otherwise be very large. That is for you to judge, though would not
    usually be lower than the size of physical RAM on the database server.
   </para>

   <para>
    In <productname>PostgreSQL</productname> &version;, the following
    partitioning types are supported:

    <itemizedlist>
     <listitem>
      <para>
       "Range Partitioning" where the table is partitioned along a
       "range" defined by a single column or set of columns, with no
       overlap between partitions. Examples might be a date range or a
       range of identifiers for particular business objects.
      </para>
     </listitem>

     <listitem>
      <para>
       "List Partitioning" where the table is partitioned by
       explicitly listing which values relate to each partition.
      </para>
     </listitem>
    </itemizedlist>

    Hash partitioning is not currently supported.
   </para>
   </sect2>

   <sect2 id="ce-partitioning-implementation">
     <title>Implementing Partitioning</title>

    <para>
     Partitioning a table is a straightforward process.  There
     are a wide range of options for you to consider, so judging exactly
     when and how to implement partitioning is a more complex topic. We
     will address that complexity primarily through the examples in this
     section.
    </para>

    <para>
     To use partitioning, do the following:
     <orderedlist spacing=compact>
      <listitem>
       <para>
        Create the <quote>master</quote> table, from which all of the
        partitions will inherit.
       </para>
       <para>
        This table will contain no data.  Do not define any
        constraints or keys on this table, unless you intend them to
        be applied equally to all partitions.
       </para>
      </listitem>

      <listitem>
       <para>
        Create several <quote>child</quote> tables that inherit from
        the master table.
       </para>

       <para>
        We will refer to the child tables as partitions, though they
        are in every way just normal <productname>PostgreSQL</>
        tables.
       </para>
      </listitem>

      <listitem>
       <para>
        Add table constraints to define the allowed values in each partition.
       </para>
       <para>
        Only clauses of the form [COLUMN] [OPERATOR] [CONSTANT(s)] will be used
        for constraint exclusion. Simple examples would be:
<programlisting>
CHECK ( x = 1 )
CHECK ( county IN ('Oxfordshire','Buckinghamshire','Warwickshire'))
CHECK ( outletID BETWEEN 1 AND 99 )
</programlisting>

        These can be linked together with boolean operators AND and OR to
        form complex constraints. Note that there is no difference in syntax
        between Range and List Partitioning mechanisms; those terms are
        descriptive only. Ensure that the set of values in each child table
        do not overlap.
       </para>
      </listitem>

      <listitem>
       <para>
        Add any other indexes you want to the partitions, bearing in
        mind that it is always more efficient to add indexes after
        data has been bulk loaded.
       </para>
      </listitem>

      <listitem>
       <para>
        Optionally, define a rule or trigger to redirect modifications
        of the master table to the appropriate partition.
       </para>
      </listitem>

     </orderedlist>
    </para>

    <para>
     For example, suppose we are constructing a database for a large
     ice cream company. The company measures peak temperatures every
     day as well as ice cream sales in each region. They have two
     tables:

<programlisting>
CREATE TABLE cities (
    id              int not null,
    name            text not null,
    altitude        int            -- in feet
);

CREATE TABLE measurement (
    city_id         int not null,
    logdate         date not null,
    peaktemp        int,
    unitsales       int
);
</programlisting>

     To reduce the amount of old data that needs to be stored, we
     decide to only keep the most recent 3 years worth of data. At the
     beginning of each month we remove the oldest month's data.
    </para>

    <para>
     Most queries just access the last week, month or quarter's data,
     since we need to keep track of sales. As a result we have a large table,
     yet only the most frequent 10% is accessed. Most of these queries
     are online reports for various levels of management. These queries access
     much of the table, so it is difficult to build enough indexes and at
     the same time allow us to keep loading all of the data fast enough.
     Yet, the reports are online so we need to respond quickly.
    </para>

    <para>
     In this situation we can use partitioning to help us meet all of our
     different requirements for the measurements table. Following the
     steps outlined above, partitioning can be enabled as follows:
    </para>

    <para>
     <orderedlist spacing=compact>
      <listitem>
       <para>
        The measurement table is our master table.
       </para>
      </listitem>

      <listitem>
       <para>
        Next we create one partition for each month using inheritance:

<programlisting>
CREATE TABLE measurement_yy04mm02 ( ) INHERITS (measurement);
CREATE TABLE measurement_yy04mm03 ( ) INHERITS (measurement);
...
CREATE TABLE measurement_yy05mm11 ( ) INHERITS (measurement);
CREATE TABLE measurement_yy05mm12 ( ) INHERITS (measurement);
CREATE TABLE measurement_yy06mm01 ( ) INHERITS (measurement);
</programlisting>

        Each of the partitions are complete tables in their own right,
        but they inherit their definition from the measurement table.
       </para>

       <para>
        This solves one of our problems: deleting old data. Each
        month, all we need to do is perform a <command>DROP
        TABLE</command> on the oldest table and create a new table to
        insert into.
       </para>
      </listitem>

      <listitem>
       <para>
        We now add non-overlapping table constraints, so that our
        table creation script becomes:

 <programlisting>
CREATE TABLE measurement_yy04mm02 (
    CHECK ( logdate >= DATE '2004-02-01' AND logdate < DATE '2004-03-01' )
                                    ) INHERITS (measurement);
CREATE TABLE measurement_yy04mm03 (
    CHECK ( logdate >= DATE '2004-03-01' AND logdate < DATE '2004-04-01' )
                                    ) INHERITS (measurement);
...
CREATE TABLE measurement_yy05mm11 (
    CHECK ( logdate >= DATE '2005-11-01' AND logdate < DATE '2005-12-01' )
                                    ) INHERITS (measurement);
CREATE TABLE measurement_yy05mm12 (
    CHECK ( logdate >= DATE '2005-12-01' AND logdate < DATE '2006-01-01' )
                                    ) INHERITS (measurement);
CREATE TABLE measurement_yy06mm01 (
    CHECK ( logdate >= DATE '2006-01-01' AND logdate < DATE '2006-02-01' )
                                    ) INHERITS (measurement);
</programlisting>
       </para>
      </listitem>

      <listitem>
       <para>
        We choose not to add further indexes at this time.
       </para>
      </listitem>

      <listitem>
       <para>
        Data will be added each day to the latest partition. This
        allows us to set up a very simple rule to insert data. We must
        redefine this each month so that it always points to the
        current partition.

<programlisting>
CREATE OR REPLACE RULE measurement_current_partition AS
ON INSERT
TO measurement
DO INSTEAD
    INSERT INTO measurement_yy06mm01 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
</programlisting>

        We might want to insert data and have the server automatically
        locate the partition into which the row should be added. We
        could do this with a more complex set of rules as shown below.

<programlisting>
CREATE RULE measurement_insert_yy04mm02 AS
ON INSERT
TO measurement WHERE
    ( logdate >= DATE '2004-02-01' AND logdate < DATE '2004-03-01' )
DO INSTEAD
    INSERT INTO measurement_yy04mm02 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
...
CREATE RULE measurement_insert_yy05mm12 AS
ON INSERT
TO measurement WHERE
    ( logdate >= DATE '2005-12-01' AND logdate < DATE '2006-01-01' )
DO INSTEAD
    INSERT INTO measurement_yy05mm12 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
CREATE RULE measurement_insert_yy06mm01 AS
ON INSERT
TO measurement WHERE
    ( logdate >= DATE '2006-01-01' AND logdate < DATE '2006-02-01' )
DO INSTEAD
    INSERT INTO measurement_yy06mm01 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
</programlisting>

        Note that the <literal>WHERE</literal> clause in each rule
        exactly matches those used for the <literal>CHECK</literal>
        constraints on each partition.
       </para>
      </listitem>
     </orderedlist>
    </para>

    <para>
     As we can see, a complex partitioning scheme could require a
     substantial amount of DDL. In the above example we would be
     creating a new partition each month, so it may be wise to write a
     script that generates the required DDL automatically.
    </para>

   <para>
    The following caveats apply:
   <itemizedlist>
    <listitem>
     <para>
      There is currently no way to specify that all of the
      <literal>CHECK</literal> constraints are mutually
      exclusive. Care is required by the database designer.
     </para>
    </listitem>

    <listitem>
     <para>
      There is currently no way to specify that rows may not be
      inserted into the master table. A <literal>CHECK</literal>
      constraint on the master table will be inherited by all child
      tables, so that cannot not be used for this purpose.
     </para>
    </listitem>

    <listitem>
     <para>
      For some datatypes you must explicitly coerce the constant values
      into the datatype of the column. The following constraint will
      work if x is an INTEGER datatype, but not if x is BIGINT datatype.
<programlisting>
CHECK ( x = 1 )
</programlisting>
      For BIGINT we must use a constraint like:
<programlisting>
CHECK ( x = 1::bigint )
</programlisting>
      The issue is not restricted to BIGINT datatypes but can occur whenever
      the default datatype of the constant does not match the datatype of
      the column to which it is being compared.
     </para>
    </listitem>

    <listitem>
     <para>
      Partitioning can also be arranged using a <literal>UNION
      ALL</literal> view:

<programlisting>
CREATE VIEW measurement AS
          SELECT * FROM measurement_yy04mm02
UNION ALL SELECT * FROM measurement_yy04mm03
...
UNION ALL SELECT * FROM measurement_yy05mm11
UNION ALL SELECT * FROM measurement_yy05mm12
UNION ALL SELECT * FROM measurement_yy06mm01;
</programlisting>

      However, constraint exclusion is currently not supported for
      partitioned tables defined in this manner.
     </para>
    </listitem>
   </itemizedlist>
   </para>
   </sect2>

   <sect2 id="constraint-exclusion-queries">
    <title>Constraint Exclusion in Queries</title>

   <para>
    Partitioning can be used to improve query performance when used in
    conjunction with constraint exclusion. As an example:

<programlisting>
SET constraint_exclusion=true;
SELECT count(*) FROM measurement WHERE logdate >= DATE '2006-01-01';
</programlisting>

    Without constraint exclusion, the above query would scan each of
    the partitions of the measurement table. With constraint
    exclusion, the planner will examine each of the constraints and
    try to prove that each of the partitions needs to be involved in
    the query. If the planner is able to refute that for any
    partition, it excludes the partition from the query plan.
   </para>

   <para>
    You can use the <command>EXPLAIN</> command to show the difference
    between a plan with <varname>constraint_exclusion</> on and a plan
    with it off.

<programlisting>
SET constraint_exclusion=false;
EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2006-01-01';

                                          QUERY PLAN
-----------------------------------------------------------------------------------------------
 Aggregate  (cost=158.66..158.68 rows=1 width=0)
   ->  Append  (cost=0.00..151.88 rows=2715 width=0)
         ->  Seq Scan on measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
         ->  Seq Scan on measurement_yy04mm02 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
         ->  Seq Scan on measurement_yy04mm03 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
...
         ->  Seq Scan on measurement_yy05mm12 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
         ->  Seq Scan on measurement_yy06mm01 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
</programlisting>

    Now when we enable constraint exclusion, we get a significantly
    reduced plan but the same result set:

<programlisting>
SET constraint_exclusion=true;
EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2006-01-01';
                                          QUERY PLAN
-----------------------------------------------------------------------------------------------
 Aggregate  (cost=63.47..63.48 rows=1 width=0)
   ->  Append  (cost=0.00..60.75 rows=1086 width=0)
         ->  Seq Scan on measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
         ->  Seq Scan on measurement_yy06mm01 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
</programlisting>

    Don't forget that you still need to run <command>ANALYZE</command>
    on each partition individually. A command like this
<programlisting>
ANALYZE measurement;
</programlisting>

    only affects the master table.
   </para>

   <para>
    No indexes are required to use constraint exclusion. The
    partitions should be defined with appropriate <literal>CHECK</>
    constraints. These are then compared with the predicates of the
    <command>SELECT</> query to determine which partitions must be
    scanned.
   </para>

   <para>
    The following caveats apply to this release:
   <itemizedlist>
    <listitem>
     <para>
      Constraint exclusion only works when the query directly matches
      a constant. A constant bound to a parameterised query will not
      work in the same way since the plan is fixed and would need to
      vary with each execution.  Also, stable constants such as
      <literal>CURRENT_DATE</literal> may not be used, since these are
      constant only for during the execution of a single query.  Join
      conditions will not allow constraint exclusion to work either.
     </para>
    </listitem>

    <listitem>
     <para>
      UPDATEs and DELETEs against the master table do not perform
      constraint exclusion.
     </para>
    </listitem>

    <listitem>
     <para>
      All constraints on all partitions of the master table are considered for
      constraint exclusion, so large numbers of partitions are likely to
      increase query planning time considerably.
     </para>
    </listitem>

   </itemizedlist>
   </para>

   </sect2>

P
Peter Eisentraut 已提交
1868 1869 1870 1871 1872
 </sect1>

 <sect1 id="ddl-alter">
  <title>Modifying Tables</title>

P
Peter Eisentraut 已提交
1873 1874 1875 1876 1877
  <indexterm zone="ddl-alter">
   <primary>table</primary>
   <secondary>modifying</secondary>
  </indexterm>

P
Peter Eisentraut 已提交
1878
  <para>
1879
   When you create a table and you realize that you made a mistake, or
T
Tom Lane 已提交
1880
   the requirements of the application change, then you can drop the
1881 1882 1883 1884
   table and create it again.  But this is not a convenient option if
   the table is already filled with data, or if the table is
   referenced by other database objects (for instance a foreign key
   constraint).  Therefore <productname>PostgreSQL</productname>
T
Tom Lane 已提交
1885 1886 1887 1888
   provides a family of commands to make modifications to existing
   tables.  Note that this is conceptually distinct from altering
   the data contained in the table: here we are interested in altering
   the definition, or structure, of the table.
P
Peter Eisentraut 已提交
1889 1890 1891 1892 1893 1894 1895 1896
  </para>

  <para>
   You can
   <itemizedlist spacing="compact">
    <listitem>
     <para>Add columns,</para>
    </listitem>
1897
    <listitem>
1898
     <para>Remove columns,</para>
1899
    </listitem>
P
Peter Eisentraut 已提交
1900 1901 1902 1903 1904 1905 1906 1907 1908
    <listitem>
     <para>Add constraints,</para>
    </listitem>
    <listitem>
     <para>Remove constraints,</para>
    </listitem>
    <listitem>
     <para>Change default values,</para>
    </listitem>
1909 1910 1911
    <listitem>
     <para>Change column data types,</para>
    </listitem>
P
Peter Eisentraut 已提交
1912
    <listitem>
1913
     <para>Rename columns,</para>
P
Peter Eisentraut 已提交
1914 1915
    </listitem>
    <listitem>
1916
     <para>Rename tables.</para>
P
Peter Eisentraut 已提交
1917 1918 1919
    </listitem>
   </itemizedlist>

1920 1921 1922
   All these actions are performed using the
   <xref linkend="sql-altertable" endterm="sql-altertable-title">
   command.
P
Peter Eisentraut 已提交
1923 1924
  </para>

1925 1926 1927
  <sect2>
   <title>Adding a Column</title>

P
Peter Eisentraut 已提交
1928 1929 1930 1931 1932
   <indexterm>
    <primary>column</primary>
    <secondary>adding</secondary>
   </indexterm>

1933
   <para>
T
Tom Lane 已提交
1934
    To add a column, use a command like this:
1935 1936 1937
<programlisting>
ALTER TABLE products ADD COLUMN description text;
</programlisting>
1938 1939
    The new column is initially filled with whatever default
    value is given (null if you don't specify a <literal>DEFAULT</> clause).
1940 1941 1942
   </para>

   <para>
1943
    You can also define constraints on the column at the same time,
1944 1945 1946 1947
    using the usual syntax:
<programlisting>
ALTER TABLE products ADD COLUMN description text CHECK (description &lt;&gt; '');
</programlisting>
1948 1949 1950 1951 1952 1953
    In fact all the options that can be applied to a column description
    in <command>CREATE TABLE</> can be used here.  Keep in mind however
    that the default value must satisfy the given constraints, or the
    <literal>ADD</> will fail.  Alternatively, you can add
    constraints later (see below) after you've filled in the new column
    correctly.
1954 1955 1956 1957 1958 1959
   </para>
  </sect2>

  <sect2>
   <title>Removing a Column</title>

P
Peter Eisentraut 已提交
1960 1961 1962 1963 1964
   <indexterm>
    <primary>column</primary>
    <secondary>removing</secondary>
   </indexterm>

1965
   <para>
T
Tom Lane 已提交
1966
    To remove a column, use a command like this:
1967 1968 1969
<programlisting>
ALTER TABLE products DROP COLUMN description;
</programlisting>
T
Tom Lane 已提交
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
    Whatever data was in the column disappears.  Table constraints involving
    the column are dropped, too.  However, if the column is referenced by a
    foreign key constraint of another table,
    <productname>PostgreSQL</productname> will not silently drop that
    constraint.  You can authorize dropping everything that depends on
    the column by adding <literal>CASCADE</>:
<programlisting>
ALTER TABLE products DROP COLUMN description CASCADE;
</programlisting>
    See <xref linkend="ddl-depend"> for a description of the general
    mechanism behind this.
1981 1982 1983 1984 1985 1986
   </para>
  </sect2>

  <sect2>
   <title>Adding a Constraint</title>

P
Peter Eisentraut 已提交
1987 1988 1989 1990 1991
   <indexterm>
    <primary>constraint</primary>
    <secondary>adding</secondary>
   </indexterm>

1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
   <para>
    To add a constraint, the table constraint syntax is used.  For example:
<programlisting>
ALTER TABLE products ADD CHECK (name &lt;&gt; '');
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;
</programlisting>
    To add a not-null constraint, which cannot be written as a table
    constraint, use this syntax:
<programlisting>
ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;
</programlisting>
   </para>

   <para>
    The constraint will be checked immediately, so the table data must
    satisfy the constraint before it can be added.
   </para>
  </sect2>

  <sect2>
   <title>Removing a Constraint</title>

P
Peter Eisentraut 已提交
2015 2016 2017 2018 2019
   <indexterm>
    <primary>constraint</primary>
    <secondary>removing</secondary>
   </indexterm>

2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
   <para>
    To remove a constraint you need to know its name.  If you gave it
    a name then that's easy.  Otherwise the system assigned a
    generated name, which you need to find out.  The
    <application>psql</application> command <literal>\d
    <replaceable>tablename</replaceable></literal> can be helpful
    here; other interfaces might also provide a way to inspect table
    details.  Then the command is:
<programlisting>
ALTER TABLE products DROP CONSTRAINT some_name;
</programlisting>
T
Tom Lane 已提交
2031 2032 2033 2034 2035
    (If you are dealing with a generated constraint name like <literal>$2</>,
    don't forget that you'll need to double-quote it to make it a valid
    identifier.)
   </para>

T
Tom Lane 已提交
2036 2037 2038 2039 2040 2041 2042
   <para>
    As with dropping a column, you need to add <literal>CASCADE</> if you
    want to drop a constraint that something else depends on.  An example
    is that a foreign key constraint depends on a unique or primary key
    constraint on the referenced column(s).
   </para>

T
Tom Lane 已提交
2043
   <para>
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    This works the same for all constraint types except not-null
    constraints. To drop a not null constraint use
<programlisting>
ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;
</programlisting>
    (Recall that not-null constraints do not have names.)
   </para>
  </sect2>

  <sect2>
2054
   <title>Changing a Column's Default Value</title>
2055

P
Peter Eisentraut 已提交
2056 2057 2058 2059 2060
   <indexterm>
    <primary>default value</primary>
    <secondary>changing</secondary>
   </indexterm>

2061 2062 2063 2064 2065
   <para>
    To set a new default for a column, use a command like this:
<programlisting>
ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;
</programlisting>
2066 2067 2068 2069 2070
    Note that this doesn't affect any existing rows in the table, it
    just changes the default for future <command>INSERT</> commands.
   </para>

   <para>
2071 2072 2073 2074
    To remove any default value, use
<programlisting>
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
</programlisting>
T
Tom Lane 已提交
2075
    This is effectively the same as setting the default to null.
2076
    As a consequence, it is not an error
B
Bruce Momjian 已提交
2077 2078
    to drop a default where one hadn't been defined, because the
    default is implicitly the null value.
2079 2080 2081
   </para>
  </sect2>

2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
  <sect2>
   <title>Changing a Column's Data Type</title>

   <indexterm>
    <primary>column data type</primary>
    <secondary>changing</secondary>
   </indexterm>

   <para>
    To convert a column to a different data type, use a command like this:
<programlisting>
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
</programlisting>
    This will succeed only if each existing entry in the column can be
    converted to the new type by an implicit cast.  If a more complex
    conversion is needed, you can add a <literal>USING</> clause that
    specifies how to compute the new values from the old.
   </para>

   <para>
    <productname>PostgreSQL</> will attempt to convert the column's
    default value (if any) to the new type, as well as any constraints
    that involve the column.  But these conversions may fail, or may
    produce surprising results.  It's often best to drop any constraints
    on the column before altering its type, and then add back suitably
    modified constraints afterwards.
   </para>
  </sect2>

2111 2112 2113
  <sect2>
   <title>Renaming a Column</title>

P
Peter Eisentraut 已提交
2114 2115 2116 2117 2118
   <indexterm>
    <primary>column</primary>
    <secondary>renaming</secondary>
   </indexterm>

2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
   <para>
    To rename a column:
<programlisting>
ALTER TABLE products RENAME COLUMN product_no TO product_number;
</programlisting>
   </para>
  </sect2>

  <sect2>
   <title>Renaming a Table</title>

P
Peter Eisentraut 已提交
2130 2131 2132 2133 2134
   <indexterm>
    <primary>table</primary>
    <secondary>renaming</secondary>
   </indexterm>

2135 2136 2137 2138 2139 2140 2141
   <para>
    To rename a table:
<programlisting>
ALTER TABLE products RENAME TO items;
</programlisting>
   </para>
  </sect2>
P
Peter Eisentraut 已提交
2142
 </sect1>
2143

2144 2145 2146
 <sect1 id="ddl-priv">
  <title>Privileges</title>

P
Peter Eisentraut 已提交
2147 2148 2149 2150 2151 2152 2153 2154 2155
  <indexterm zone="ddl-priv">
   <primary>privilege</primary>
  </indexterm>

  <indexterm>
   <primary>permission</primary>
   <see>privilege</see>
  </indexterm>

2156 2157 2158 2159
  <para>
   When you create a database object, you become its owner.  By
   default, only the owner of an object can do anything with the
   object. In order to allow other users to use it,
2160 2161
   <firstterm>privileges</firstterm> must be granted.  (However,
   users that have the superuser attribute can always
2162 2163 2164 2165 2166 2167 2168
   access any object.)
  </para>

  <para>
   There are several different privileges: <literal>SELECT</>,
   <literal>INSERT</>, <literal>UPDATE</>, <literal>DELETE</>,
   <literal>RULE</>, <literal>REFERENCES</>, <literal>TRIGGER</>,
2169 2170
   <literal>CREATE</>, <literal>TEMPORARY</>, <literal>EXECUTE</>, and
   <literal>USAGE</>.  The privileges applicable to a particular
2171
   object vary depending on the object's type (table, function, etc).
2172 2173 2174 2175 2176
   For complete information on the different types of privileges
   supported by <productname>PostgreSQL</productname>, refer to the
   <xref linkend="sql-grant" endterm="sql-grant-title"> reference
   page.  The following sections and chapters will also show you how
   those privileges are used.
2177 2178 2179 2180 2181 2182 2183
  </para>

  <para>
   The right to modify or destroy an object is always the privilege of
   the owner only.
  </para>

2184 2185 2186
  <note>
   <para>
    To change the owner of a table, index, sequence, or view, use the
2187 2188 2189
    <xref linkend="sql-altertable" endterm="sql-altertable-title">
    command.  There are corresponding <literal>ALTER</> commands for
    other object types.
2190 2191 2192
   </para>
  </note>

2193 2194
  <para>
   To assign privileges, the <command>GRANT</command> command is
2195
   used. For example, if <literal>joe</literal> is an existing user, and
2196 2197 2198 2199 2200
   <literal>accounts</literal> is an existing table, the privilege to
   update the table can be granted with
<programlisting>
GRANT UPDATE ON accounts TO joe;
</programlisting>
2201
   To grant a privilege to a group, use this syntax:
2202 2203 2204 2205 2206
<programlisting>
GRANT SELECT ON accounts TO GROUP staff;
</programlisting>
   The special <quote>user</quote> name <literal>PUBLIC</literal> can
   be used to grant a privilege to every user on the system. Writing
2207 2208
   <literal>ALL</literal> in place of a specific privilege grants all
   privileges that are relevant for the object type.
2209 2210 2211 2212 2213 2214 2215 2216
  </para>

  <para>
   To revoke a privilege, use the fittingly named
   <command>REVOKE</command> command:
<programlisting>
REVOKE ALL ON accounts FROM PUBLIC;
</programlisting>
2217
   The special privileges of the object owner (i.e., the right to do
2218
   <command>DROP</>, <command>GRANT</>, <command>REVOKE</>, etc.)
2219
   are always implicit in being the owner,
2220
   and cannot be granted or revoked.  But the object owner can choose
2221 2222 2223
   to revoke his own ordinary privileges, for example to make a
   table read-only for himself as well as others.
  </para>
2224 2225

  <para>
2226 2227 2228 2229 2230 2231 2232 2233 2234
   Ordinarily, only the object's owner (or a superuser) can grant or
   revoke privileges on an object.  However, it is possible to grant a
   privilege <quote>with grant option</>, which gives the recipient
   the right to grant it in turn to others.  If the grant option is
   subsequently revoked then all who received the privilege from that
   recipient (directly or through a chain of grants) will lose the
   privilege.  For details see the <xref linkend="sql-grant"
   endterm="sql-grant-title"> and <xref linkend="sql-revoke"
   endterm="sql-revoke-title"> reference pages.
2235
  </para>
2236
 </sect1>
P
Peter Eisentraut 已提交
2237 2238 2239 2240

 <sect1 id="ddl-schemas">
  <title>Schemas</title>

P
Peter Eisentraut 已提交
2241 2242
  <indexterm zone="ddl-schemas">
   <primary>schema</primary>
2243 2244 2245
  </indexterm>

  <para>
2246
   A <productname>PostgreSQL</productname> database cluster
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
   contains one or more named databases.  Users and groups of users are
   shared across the entire cluster, but no other data is shared across
   databases.  Any given client connection to the server can access
   only the data in a single database, the one specified in the connection
   request.
  </para>

  <note>
   <para>
    Users of a cluster do not necessarily have the privilege to access every
    database in the cluster.  Sharing of user names means that there
    cannot be different users named, say, <literal>joe</> in two databases
    in the same cluster; but the system can be configured to allow
    <literal>joe</> access to only some of the databases.
   </para>
  </note>

  <para>
   A database contains one or more named <firstterm>schemas</>, which
   in turn contain tables.  Schemas also contain other kinds of named
   objects, including data types, functions, and operators.  The same
   object name can be used in different schemas without conflict; for
   example, both <literal>schema1</> and <literal>myschema</> may
   contain tables named <literal>mytable</>.  Unlike databases,
   schemas are not rigidly separated: a user may access objects in any
   of the schemas in the database he is connected to, if he has
   privileges to do so.
  </para>

  <para>
   There are several reasons why one might want to use schemas:

   <itemizedlist>
    <listitem>
     <para>
      To allow many users to use one database without interfering with
      each other.
     </para>
    </listitem>

    <listitem>
     <para>
      To organize database objects into logical groups to make them
      more manageable.
     </para>
    </listitem>

    <listitem>
     <para>
      Third-party applications can be put into separate schemas so
      they cannot collide with the names of other objects.
     </para>
    </listitem>
   </itemizedlist>

   Schemas are analogous to directories at the operating system level,
2303
   except that schemas cannot be nested.
2304 2305 2306 2307 2308
  </para>

  <sect2 id="ddl-schemas-create">
   <title>Creating a Schema</title>

P
Peter Eisentraut 已提交
2309 2310 2311 2312 2313
   <indexterm zone="ddl-schemas-create">
    <primary>schema</primary>
    <secondary>creating</secondary>
   </indexterm>

2314
   <para>
2315
    To create a schema, use the command <literal>CREATE
2316 2317 2318 2319 2320 2321 2322 2323
    SCHEMA</literal>.  Give the schema a name of your choice.  For
    example:
<programlisting>
CREATE SCHEMA myschema;
</programlisting>
   </para>

   <indexterm>
P
Peter Eisentraut 已提交
2324
    <primary>qualified name</primary>
2325 2326 2327
   </indexterm>

   <indexterm>
P
Peter Eisentraut 已提交
2328
    <primary>name</primary>
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
    <secondary>qualified</secondary>
   </indexterm>

   <para>
    To create or access objects in a schema, write a
    <firstterm>qualified name</> consisting of the schema name and
    table name separated by a dot:
<synopsis>
<replaceable>schema</><literal>.</><replaceable>table</>
</synopsis>
T
Tom Lane 已提交
2339 2340 2341
    This works anywhere a table name is expected, including the table
    modification commands and the data access commands discussed in
    the following chapters.
2342 2343 2344 2345 2346
    (For brevity we will speak of tables only, but the same ideas apply
    to other kinds of named objects, such as types and functions.)
   </para>

   <para>
2347 2348 2349 2350
    Actually, the even more general syntax
<synopsis>
<replaceable>database</><literal>.</><replaceable>schema</><literal>.</><replaceable>table</>
</synopsis>
T
Tom Lane 已提交
2351 2352 2353
    can be used too, but at present this is just for <foreignphrase>pro
    forma</> compliance with the SQL standard.  If you write a database name,
    it must be the same as the database you are connected to.
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
   </para>

   <para>
    So to create a table in the new schema, use
<programlisting>
CREATE TABLE myschema.mytable (
 ...
);
</programlisting>
   </para>

P
Peter Eisentraut 已提交
2365 2366 2367 2368 2369
   <indexterm>
    <primary>schema</primary>
    <secondary>removing</secondary>
   </indexterm>

2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
   <para>
    To drop a schema if it's empty (all objects in it have been
    dropped), use
<programlisting>
DROP SCHEMA myschema;
</programlisting>
    To drop a schema including all contained objects, use
<programlisting>
DROP SCHEMA myschema CASCADE;
</programlisting>
    See <xref linkend="ddl-depend"> for a description of the general
    mechanism behind this.
   </para>

   <para>
    Often you will want to create a schema owned by someone else
    (since this is one of the ways to restrict the activities of your
    users to well-defined namespaces).  The syntax for that is:
<programlisting>
2389
CREATE SCHEMA <replaceable>schemaname</replaceable> AUTHORIZATION <replaceable>username</replaceable>;
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
</programlisting>
    You can even omit the schema name, in which case the schema name
    will be the same as the user name.  See <xref
    linkend="ddl-schemas-patterns"> for how this can be useful.
   </para>

   <para>
    Schema names beginning with <literal>pg_</> are reserved for
    system purposes and may not be created by users.
   </para>
  </sect2>

  <sect2 id="ddl-schemas-public">
   <title>The Public Schema</title>

P
Peter Eisentraut 已提交
2405 2406 2407 2408 2409
   <indexterm zone="ddl-schemas-public">
    <primary>schema</primary>
    <secondary>public</secondary>
   </indexterm>

2410 2411
   <para>
    In the previous sections we created tables without specifying any
2412 2413 2414
    schema names.  By default, such tables (and other objects) are
    automatically put into a schema named <quote>public</quote>.  Every new
    database contains such a schema.  Thus, the following are equivalent:
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
<programlisting>
CREATE TABLE products ( ... );
</programlisting>
    and
<programlisting>
CREATE TABLE public.products ( ... );
</programlisting>
   </para>
  </sect2>

  <sect2 id="ddl-schemas-path">
   <title>The Schema Search Path</title>

   <indexterm>
    <primary>search path</primary>
   </indexterm>

   <indexterm>
P
Peter Eisentraut 已提交
2433
    <primary>unqualified name</primary>
2434 2435 2436
   </indexterm>

   <indexterm>
P
Peter Eisentraut 已提交
2437
    <primary>name</primary>
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
    <secondary>unqualified</secondary>
   </indexterm>

   <para>
    Qualified names are tedious to write, and it's often best not to
    wire a particular schema name into applications anyway.  Therefore
    tables are often referred to by <firstterm>unqualified names</>,
    which consist of just the table name.  The system determines which table
    is meant by following a <firstterm>search path</>, which is a list
    of schemas to look in.  The first matching table in the search path
    is taken to be the one wanted.  If there is no match in the search
    path, an error is reported, even if matching table names exist
    in other schemas in the database.
   </para>

P
Peter Eisentraut 已提交
2453 2454 2455 2456 2457
   <indexterm>
    <primary>schema</primary>
    <secondary>current</secondary>
   </indexterm>

2458 2459 2460 2461 2462 2463 2464
   <para>
    The first schema named in the search path is called the current schema.
    Aside from being the first schema searched, it is also the schema in
    which new tables will be created if the <command>CREATE TABLE</>
    command does not specify a schema name.
   </para>

P
Peter Eisentraut 已提交
2465 2466 2467 2468
   <indexterm>
    <primary>search_path</primary>
   </indexterm>

2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
   <para>
    To show the current search path, use the following command:
<programlisting>
SHOW search_path;
</programlisting>
    In the default setup this returns:
<screen>
 search_path
--------------
 $user,public
</screen>
    The first element specifies that a schema with the same name as
T
Tom Lane 已提交
2481 2482
    the current user is to be searched.  If no such schema exists,
    the entry is ignored.  The second element refers to the
2483 2484 2485 2486
    public schema that we have seen already.
   </para>

   <para>
P
Peter Eisentraut 已提交
2487
    The first schema in the search path that exists is the default
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
    location for creating new objects.  That is the reason that by
    default objects are created in the public schema.  When objects
    are referenced in any other context without schema qualification
    (table modification, data modification, or query commands) the
    search path is traversed until a matching object is found.
    Therefore, in the default configuration, any unqualified access
    again can only refer to the public schema.
   </para>

   <para>
    To put our new schema in the path, we use
<programlisting>
SET search_path TO myschema,public;
</programlisting>
    (We omit the <literal>$user</literal> here because we have no
    immediate need for it.)  And then we can access the table without
    schema qualification:
<programlisting>
DROP TABLE mytable;
</programlisting>
    Also, since <literal>myschema</literal> is the first element in
    the path, new objects would by default be created in it.
   </para>

   <para>
    We could also have written
<programlisting>
SET search_path TO myschema;
</programlisting>
    Then we no longer have access to the public schema without
    explicit qualification.  There is nothing special about the public
    schema except that it exists by default.  It can be dropped, too.
   </para>

   <para>
T
Tom Lane 已提交
2523
    See also <xref linkend="functions-info"> for other ways to manipulate
2524 2525 2526 2527
    the schema search path.
   </para>

   <para>
P
Peter Eisentraut 已提交
2528 2529
    The search path works in the same way for data type names, function names,
    and operator names as it does for table names.  Data type and function
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
    names can be qualified in exactly the same way as table names.  If you
    need to write a qualified operator name in an expression, there is a
    special provision: you must write
<synopsis>
<literal>OPERATOR(</><replaceable>schema</><literal>.</><replaceable>operator</><literal>)</>
</synopsis>
    This is needed to avoid syntactic ambiguity.  An example is
<programlisting>
SELECT 3 OPERATOR(pg_catalog.+) 4;
</programlisting>
    In practice one usually relies on the search path for operators,
    so as not to have to write anything so ugly as that.
   </para>
  </sect2>

  <sect2 id="ddl-schemas-priv">
   <title>Schemas and Privileges</title>

P
Peter Eisentraut 已提交
2548 2549 2550 2551 2552
   <indexterm zone="ddl-schemas-priv">
    <primary>privilege</primary>
    <secondary sortas="schemas">for schemas</secondary>
   </indexterm>

2553
   <para>
2554
    By default, users cannot access any objects in schemas they do not
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
    own.  To allow that, the owner of the schema needs to grant the
    <literal>USAGE</literal> privilege on the schema.  To allow users
    to make use of the objects in the schema, additional privileges
    may need to be granted, as appropriate for the object.
   </para>

   <para>
    A user can also be allowed to create objects in someone else's
    schema.  To allow that, the <literal>CREATE</literal> privilege on
    the schema needs to be granted.  Note that by default, everyone
T
Tom Lane 已提交
2565
    has <literal>CREATE</literal> and <literal>USAGE</literal> privileges on
2566
    the schema
T
Tom Lane 已提交
2567 2568 2569
    <literal>public</literal>.  This allows all users that are able to
    connect to a given database to create objects in its
    <literal>public</literal> schema.  If you do
2570 2571
    not want to allow that, you can revoke that privilege:
<programlisting>
2572
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
2573 2574 2575 2576
</programlisting>
    (The first <quote>public</quote> is the schema, the second
    <quote>public</quote> means <quote>every user</quote>.  In the
    first sense it is an identifier, in the second sense it is a
2577
    key word, hence the different capitalization; recall the
2578 2579 2580 2581
    guidelines from <xref linkend="sql-syntax-identifiers">.)
   </para>
  </sect2>

P
Peter Eisentraut 已提交
2582
  <sect2 id="ddl-schemas-catalog">
2583 2584
   <title>The System Catalog Schema</title>

P
Peter Eisentraut 已提交
2585 2586 2587 2588 2589
   <indexterm zone="ddl-schemas-catalog">
    <primary>system catalog</primary>
    <secondary>schema</secondary>
   </indexterm>

2590 2591 2592
   <para>
    In addition to <literal>public</> and user-created schemas, each
    database contains a <literal>pg_catalog</> schema, which contains
P
Peter Eisentraut 已提交
2593
    the system tables and all the built-in data types, functions, and
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
    operators.  <literal>pg_catalog</> is always effectively part of
    the search path.  If it is not named explicitly in the path then
    it is implicitly searched <emphasis>before</> searching the path's
    schemas.  This ensures that built-in names will always be
    findable.  However, you may explicitly place
    <literal>pg_catalog</> at the end of your search path if you
    prefer to have user-defined names override built-in names.
   </para>

   <para>
    In <productname>PostgreSQL</productname> versions before 7.3,
    table names beginning with <literal>pg_</> were reserved.  This is
    no longer true: you may create such a table name if you wish, in
    any non-system schema.  However, it's best to continue to avoid
    such names, to ensure that you won't suffer a conflict if some
2609
    future version defines a system table named the same as your
2610
    table.  (With the default search path, an unqualified reference to
2611 2612
    your table name would be resolved as the system table instead.)
    System tables will continue to follow the convention of having
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
    names beginning with <literal>pg_</>, so that they will not
    conflict with unqualified user-table names so long as users avoid
    the <literal>pg_</> prefix.
   </para>
  </sect2>

  <sect2 id="ddl-schemas-patterns">
   <title>Usage Patterns</title>

   <para>
    Schemas can be used to organize your data in many ways.  There are
2624
    a few usage patterns that are recommended and are easily supported by
2625 2626 2627 2628 2629 2630 2631
    the default configuration:
    <itemizedlist>
     <listitem>
      <para>
       If you do not create any schemas then all users access the
       public schema implicitly.  This simulates the situation where
       schemas are not available at all.  This setup is mainly
2632
       recommended when there is only a single user or a few cooperating
2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
       users in a database.  This setup also allows smooth transition
       from the non-schema-aware world.
      </para>
     </listitem>

     <listitem>
      <para>
       You can create a schema for each user with the same name as
       that user.  Recall that the default search path starts with
       <literal>$user</literal>, which resolves to the user name.
       Therefore, if each user has a separate schema, they access their
       own schemas by default.
      </para>

      <para>
       If you use this setup then you might also want to revoke access
       to the public schema (or drop it altogether), so users are
       truly constrained to their own schemas.
      </para>
     </listitem>

     <listitem>
      <para>
       To install shared applications (tables to be used by everyone,
       additional functions provided by third parties, etc.), put them
       into separate schemas.  Remember to grant appropriate
       privileges to allow the other users to access them.  Users can
2660
       then refer to these additional objects by qualifying the names
2661
       with a schema name, or they can put the additional schemas into
2662
       their search path, as they choose.
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
      </para>
     </listitem>
    </itemizedlist>
   </para>
  </sect2>

  <sect2 id="ddl-schemas-portability">
   <title>Portability</title>

   <para>
    In the SQL standard, the notion of objects in the same schema
    being owned by different users does not exist.  Moreover, some
2675
    implementations do not allow you to create schemas that have a
2676 2677 2678 2679 2680 2681
    different name than their owner.  In fact, the concepts of schema
    and user are nearly equivalent in a database system that
    implements only the basic schema support specified in the
    standard.  Therefore, many users consider qualified names to
    really consist of
    <literal><replaceable>username</>.<replaceable>tablename</></literal>.
B
Bruce Momjian 已提交
2682 2683
    This is how <productname>PostgreSQL</productname> will effectively
    behave if you create a per-user schema for every user.
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
   </para>

   <para>
    Also, there is no concept of a <literal>public</> schema in the
    SQL standard.  For maximum conformance to the standard, you should
    not use (perhaps even remove) the <literal>public</> schema.
   </para>

   <para>
    Of course, some SQL database systems might not implement schemas
    at all, or provide namespace support by allowing (possibly
    limited) cross-database access.  If you need to work with those
    systems, then maximum portability would be achieved by not using
    schemas at all.
   </para>
  </sect2>
P
Peter Eisentraut 已提交
2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
 </sect1>

 <sect1 id="ddl-others">
  <title>Other Database Objects</title>

  <para>
   Tables are the central objects in a relational database structure,
   because they hold your data.  But they are not the only objects
   that exist in a database.  Many other kinds of objects can be
   created to make the use and management of the data more efficient
   or convenient.  They are not discussed in this chapter, but we give
   you a list here so that you are aware of what is possible.
  </para>

  <itemizedlist>
   <listitem>
    <para>
     Views
    </para>
   </listitem>

   <listitem>
    <para>
T
Tom Lane 已提交
2723 2724 2725 2726 2727 2728 2729
     Functions and operators
    </para>
   </listitem>

   <listitem>
    <para>
     Data types and domains
P
Peter Eisentraut 已提交
2730 2731 2732 2733 2734 2735 2736 2737 2738
    </para>
   </listitem>

   <listitem>
    <para>
     Triggers and rewrite rules
    </para>
   </listitem>
  </itemizedlist>
T
Tom Lane 已提交
2739 2740 2741 2742 2743

  <para>
   Detailed information on
   these topics appears in <xref linkend="server-programming">.
  </para>
P
Peter Eisentraut 已提交
2744 2745 2746 2747 2748
 </sect1>

 <sect1 id="ddl-depend">
  <title>Dependency Tracking</title>

P
Peter Eisentraut 已提交
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
  <indexterm zone="ddl-depend">
   <primary>CASCADE</primary>
   <secondary sortas="DROP">with DROP</secondary>
  </indexterm>

  <indexterm zone="ddl-depend">
   <primary>RESTRICT</primary>
   <secondary sortas="DROP">with DROP</secondary>
  </indexterm>

P
Peter Eisentraut 已提交
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
  <para>
   When you create complex database structures involving many tables
   with foreign key constraints, views, triggers, functions, etc. you
   will implicitly create a net of dependencies between the objects.
   For instance, a table with a foreign key constraint depends on the
   table it references.
  </para>

  <para>
   To ensure the integrity of the entire database structure,
   <productname>PostgreSQL</productname> makes sure that you cannot
   drop objects that other objects still depend on.  For example,
   attempting to drop the products table we had considered in <xref
   linkend="ddl-constraints-fk">, with the orders table depending on
   it, would result in an error message such as this:
<screen>
2775 2776
DROP TABLE products;

2777
NOTICE:  constraint orders_product_no_fkey on table orders depends on table products
2778 2779
ERROR:  cannot drop table products because other objects depend on it
HINT:  Use DROP ... CASCADE to drop the dependent objects too.
P
Peter Eisentraut 已提交
2780
</screen>
2781
   The error message contains a useful hint: if you do not want to
P
Peter Eisentraut 已提交
2782 2783 2784 2785
   bother deleting all the dependent objects individually, you can run
<screen>
DROP TABLE products CASCADE;
</screen>
2786
   and all the dependent objects will be removed.  In this case, it
P
Peter Eisentraut 已提交
2787
   doesn't remove the orders table, it only removes the foreign key
2788 2789
   constraint.  (If you want to check what <literal>DROP ... CASCADE</> will do,
   run <command>DROP</> without <literal>CASCADE</> and read the <literal>NOTICE</> messages.)
P
Peter Eisentraut 已提交
2790 2791 2792 2793 2794 2795 2796
  </para>

  <para>
   All drop commands in <productname>PostgreSQL</productname> support
   specifying <literal>CASCADE</literal>.  Of course, the nature of
   the possible dependencies varies with the type of the object.  You
   can also write <literal>RESTRICT</literal> instead of
2797
   <literal>CASCADE</literal> to get the default behavior, which is to
T
Tom Lane 已提交
2798
   prevent drops of objects that other objects depend on.
P
Peter Eisentraut 已提交
2799 2800 2801 2802 2803 2804
  </para>

  <note>
   <para>
    According to the SQL standard, specifying either
    <literal>RESTRICT</literal> or <literal>CASCADE</literal> is
T
Tom Lane 已提交
2805
    required.  No database system actually enforces that rule, but
2806 2807
    whether the default behavior is <literal>RESTRICT</literal> or
    <literal>CASCADE</literal> varies across systems.
P
Peter Eisentraut 已提交
2808 2809
   </para>
  </note>
2810 2811 2812

  <note>
   <para>
2813 2814 2815
    Foreign key constraint dependencies and serial column dependencies
    from <productname>PostgreSQL</productname> versions prior to 7.3
    are <emphasis>not</emphasis> maintained or created during the
2816
    upgrade process.  All other dependency types will be properly
T
Tom Lane 已提交
2817
    created during an upgrade from a pre-7.3 database.
2818 2819
   </para>
  </note>
P
Peter Eisentraut 已提交
2820 2821 2822
 </sect1>

</chapter>