head	1.97;
access;
symbols
	REL9_0_0:1.93.2.3
	REL9_1_ALPHA1:1.97
	REL9_0_RC1:1.93.2.3
	REL9_0_BETA4:1.93.2.1
	REL9_0_STABLE:1.93.0.2
	REL9_0_BETA3:1.93
	REL9_0_BETA2:1.93
	REL7_4_29:1.21.2.2
	REL8_0_25:1.38.4.1
	REL8_1_21:1.50
	REL8_2_17:1.69.2.2
	REL8_3_11:1.81
	REL8_4_4:1.87
	REL9_0_BETA1:1.93
	REL9_0_ALPHA5_BRANCH:1.91.0.2
	REL9_0_ALPHA5:1.91
	REL7_4_28:1.21.2.2
	REL8_0_24:1.38.4.1
	REL8_1_20:1.50
	REL8_2_16:1.69.2.2
	REL8_3_10:1.81
	REL8_4_3:1.87
	REL9_0_ALPHA4:1.88
	REL9_0_ALPHA4_BRANCH:1.88.0.4
	REL8_5_ALPHA3:1.88
	REL8_5_ALPHA3_BRANCH:1.88.0.2
	REL7_4_27:1.21.2.2
	REL8_0_23:1.38.4.1
	REL8_1_19:1.50
	REL8_2_15:1.69.2.2
	REL8_3_9:1.81
	REL8_4_2:1.87
	REL8_5_ALPHA2:1.87
	REL8_5_ALPHA2_BRANCH:1.87.0.6
	REL7_4_26:1.21.2.2
	REL8_0_22:1.38.4.1
	REL8_1_18:1.50
	REL8_2_14:1.69.2.2
	REL8_3_8:1.81
	REL8_4_1:1.87
	REL8_5_ALPHA1:1.87
	REL8_5_ALPHA1_BRANCH:1.87.0.4
	REL8_4_STABLE:1.87.0.2
	REL8_4_0:1.87
	REL8_4_RC2:1.87
	REL8_4_RC1:1.86
	REL8_4_BETA2:1.86
	REL8_4_BETA1:1.85
	REL7_4_25:1.21.2.2
	REL8_0_21:1.38.4.1
	REL8_1_17:1.50
	REL8_2_13:1.69.2.2
	REL8_3_7:1.81
	REL7_4_24:1.21.2.2
	REL8_0_20:1.38.4.1
	REL8_1_16:1.50
	REL8_2_12:1.69.2.2
	REL8_3_6:1.81
	REL7_4_23:1.21.2.2
	REL8_0_19:1.38.4.1
	REL8_1_15:1.50
	REL8_2_11:1.69.2.2
	REL8_3_5:1.81
	REL7_4_22:1.21.2.2
	REL8_0_18:1.38.4.1
	REL8_1_14:1.50
	REL8_2_10:1.69.2.2
	REL8_3_4:1.81
	REL7_4_21:1.21.2.2
	REL8_0_17:1.38.4.1
	REL8_1_13:1.50
	REL8_2_9:1.69.2.2
	REL8_3_3:1.81
	REL7_4_20:1.21.2.2
	REL8_0_16:1.38.4.1
	REL8_1_12:1.50
	REL8_2_8:1.69.2.2
	REL8_3_2:1.81
	REL8_2_7:1.69.2.2
	REL8_3_1:1.81
	REL8_3_STABLE:1.81.0.2
	REL8_3_0:1.81
	REL8_3_RC2:1.81
	REL7_3_21:1.8.2.1
	REL7_4_19:1.21.2.2
	REL8_0_15:1.38.4.1
	REL8_1_11:1.50
	REL8_2_6:1.69.2.2
	REL8_3_RC1:1.80
	REL8_3_BETA4:1.78
	REL8_3_BETA3:1.76
	REL8_3_BETA2:1.76
	REL8_3_BETA1:1.76
	REL7_3_20:1.8.2.1
	REL7_4_18:1.21.2.2
	REL8_0_14:1.38.4.1
	REL8_1_10:1.50
	REL8_2_5:1.69.2.2
	REL7_3_19:1.8.2.1
	REL7_4_17:1.21.2.2
	REL8_0_13:1.38.4.1
	REL8_1_9:1.50
	REL8_2_4:1.69
	REL8_0_12:1.38.4.1
	REL8_1_8:1.50
	REL8_2_3:1.69
	REL7_3_18:1.8.2.1
	REL7_4_16:1.21.2.2
	REL8_0_11:1.38.4.1
	REL8_1_7:1.50
	REL8_2_2:1.69
	REL8_0_10:1.38.4.1
	REL8_1_6:1.50
	REL8_2_1:1.69
	REL7_4_15:1.21.2.2
	REL7_3_17:1.8.2.1
	REL8_2_STABLE:1.69.0.2
	REL8_2_0:1.69
	REL8_2_RC1:1.68
	REL8_2_BETA3:1.67
	REL8_2_BETA2:1.67
	REL8_1_5:1.50
	REL8_0_9:1.38.4.1
	REL7_4_14:1.21.2.2
	REL7_3_16:1.8.2.1
	REL8_2_BETA1:1.63
	REL7_3_15:1.8.2.1
	REL7_4_13:1.21.2.2
	REL8_0_8:1.38.4.1
	REL8_1_4:1.50
	REL7_3_14:1.8.2.1
	REL7_4_12:1.21.2.2
	REL8_0_7:1.38.4.1
	REL8_1_3:1.50
	REL7_3_13:1.8.2.1
	REL7_4_11:1.21.2.2
	REL8_0_6:1.38.4.1
	REL8_1_2:1.50
	REL7_3_12:1.8.2.1
	REL7_4_10:1.21.2.2
	REL8_0_5:1.38.4.1
	REL8_1_1:1.50
	REL8_1_STABLE:1.50.0.2
	REL8_1_0:1.50
	REL8_1_0RC1:1.45
	REL8_1_0BETA4:1.44
	REL8_1_0BETA3:1.44
	REL7_3_11:1.8.2.1
	REL7_4_9:1.21.2.2
	REL8_0_4:1.38.4.1
	REL8_1_0BETA2:1.44
	REL8_1_0BETA1:1.44
	REL7_3_10:1.8.2.1
	REL7_4_8:1.21.2.2
	REL8_0_3:1.38.4.1
	REL8_0_2:1.38.4.1
	REL7_3_9:1.8.2.1
	REL7_4_7:1.21.2.2
	REL8_0_1:1.38.4.1
	REL8_0_STABLE:1.38.0.4
	REL8_0_0:1.38.0.2
	REL8_0_0RC5:1.37
	REL8_0_0RC4:1.35
	REL8_0_0RC3:1.35
	REL8_0_0RC2:1.34
	REL8_0_0RC1:1.33
	REL8_0_0BETA5:1.32
	REL8_0_0BETA4:1.31
	REL7_4_6:1.21.2.2
	REL7_3_8:1.8.2.1
	REL8_0_0BETA3:1.30
	REL8_0_0BETA2:1.30
	REL7_4_5:1.21.2.2
	REL7_3_7:1.8.2.1
	REL7_4_4:1.21.2.2
	REL8_0_0BETA1:1.30
	REL7_4_3:1.21.2.2
	REL7_4_2:1.21.2.2
	REL7_3_6:1.8.2.1
	REL7_4_1:1.21.2.2
	REL7_3_5:1.8.2.1
	REL7_4:1.21.2.2
	REL7_4_RC2:1.21.2.2
	REL7_4_STABLE:1.21.0.2
	REL7_4_RC1:1.21
	REL7_4_BETA5:1.19
	REL7_4_BETA4:1.19
	REL7_4_BETA3:1.19
	REL7_4_BETA2:1.17
	WIN32_DEV:1.17.0.2
	REL7_4_BETA1:1.15
	REL7_3_4:1.8.2.1
	REL7_3_2:1.8.2.1
	REL7_3_STABLE:1.8.0.2;
locks; strict;
comment	@# @;


1.97
date	2010.08.26.21.08.35;	author tgl;	state Exp;
branches;
next	1.96;

1.96
date	2010.08.23.02.43.25;	author tgl;	state Exp;
branches;
next	1.95;

1.95
date	2010.08.20.13.59.45;	author tgl;	state Exp;
branches;
next	1.94;

1.94
date	2010.07.29.19.34.40;	author petere;	state Exp;
branches;
next	1.93;

1.93
date	2010.04.06.02.18.04;	author momjian;	state Exp;
branches
	1.93.2.1;
next	1.92;

1.92
date	2010.04.03.07.22.53;	author petere;	state Exp;
branches;
next	1.91;

1.91
date	2010.04.01.01.18.17;	author momjian;	state Exp;
branches;
next	1.90;

1.90
date	2010.02.24.15.54.31;	author momjian;	state Exp;
branches;
next	1.89;

1.89
date	2010.02.24.03.33.48;	author momjian;	state Exp;
branches;
next	1.88;

1.88
date	2009.10.23.05.24.52;	author petere;	state Exp;
branches;
next	1.87;

1.87
date	2009.06.17.21.58.49;	author tgl;	state Exp;
branches;
next	1.86;

1.86
date	2009.04.27.16.27.35;	author momjian;	state Exp;
branches;
next	1.85;

1.85
date	2009.01.08.12.47.58;	author petere;	state Exp;
branches;
next	1.84;

1.84
date	2009.01.07.22.40.49;	author tgl;	state Exp;
branches;
next	1.83;

1.83
date	2008.09.08.00.47.40;	author tgl;	state Exp;
branches;
next	1.82;

1.82
date	2008.05.09.23.32.03;	author tgl;	state Exp;
branches;
next	1.81;

1.81
date	2008.01.13.17.58.54;	author tgl;	state Exp;
branches;
next	1.80;

1.80
date	2007.12.03.23.49.50;	author tgl;	state Exp;
branches;
next	1.79;

1.79
date	2007.12.03.04.59.55;	author tgl;	state Exp;
branches;
next	1.78;

1.78
date	2007.12.02.19.20.32;	author tgl;	state Exp;
branches;
next	1.77;

1.77
date	2007.11.28.15.42.31;	author petere;	state Exp;
branches;
next	1.76;

1.76
date	2007.06.20.23.11.38;	author tgl;	state Exp;
branches;
next	1.75;

1.75
date	2007.05.15.19.43.50;	author neilc;	state Exp;
branches;
next	1.74;

1.74
date	2007.05.03.15.05.56;	author neilc;	state Exp;
branches;
next	1.73;

1.73
date	2007.02.01.00.28.16;	author momjian;	state Exp;
branches;
next	1.72;

1.72
date	2007.01.31.20.56.16;	author momjian;	state Exp;
branches;
next	1.71;

1.71
date	2006.12.30.20.31.11;	author momjian;	state Exp;
branches;
next	1.70;

1.70
date	2006.12.28.20.02.38;	author tgl;	state Exp;
branches;
next	1.69;

1.69
date	2006.11.28.01.09.01;	author tgl;	state Exp;
branches
	1.69.2.1;
next	1.68;

1.68
date	2006.11.21.03.44.55;	author momjian;	state Exp;
branches;
next	1.67;

1.67
date	2006.10.23.18.10.30;	author petere;	state Exp;
branches;
next	1.66;

1.66
date	2006.10.22.03.03.40;	author tgl;	state Exp;
branches;
next	1.65;

1.65
date	2006.10.16.17.28.03;	author momjian;	state Exp;
branches;
next	1.64;

1.64
date	2006.10.13.21.43.17;	author tgl;	state Exp;
branches;
next	1.63;

1.63
date	2006.09.20.21.30.20;	author tgl;	state Exp;
branches;
next	1.62;

1.62
date	2006.09.20.01.20.38;	author neilc;	state Exp;
branches;
next	1.61;

1.61
date	2006.09.05.21.08.33;	author tgl;	state Exp;
branches;
next	1.60;

1.60
date	2006.07.14.00.13.05;	author neilc;	state Exp;
branches;
next	1.59;

1.59
date	2006.07.03.16.43.14;	author tgl;	state Exp;
branches;
next	1.58;

1.58
date	2006.07.02.01.58.36;	author momjian;	state Exp;
branches;
next	1.57;

1.57
date	2006.04.30.21.15.32;	author tgl;	state Exp;
branches;
next	1.56;

1.56
date	2006.04.23.03.39.50;	author momjian;	state Exp;
branches;
next	1.55;

1.55
date	2006.02.18.23.14.45;	author neilc;	state Exp;
branches;
next	1.54;

1.54
date	2006.02.12.19.11.00;	author momjian;	state Exp;
branches;
next	1.53;

1.53
date	2006.02.11.22.17.18;	author momjian;	state Exp;
branches;
next	1.52;

1.52
date	2006.02.04.23.03.19;	author tgl;	state Exp;
branches;
next	1.51;

1.51
date	2005.12.23.00.38.03;	author momjian;	state Exp;
branches;
next	1.50;

1.50
date	2005.11.04.23.53.18;	author tgl;	state Exp;
branches;
next	1.49;

1.49
date	2005.11.04.23.13.59;	author petere;	state Exp;
branches;
next	1.48;

1.48
date	2005.11.04.02.56.30;	author tgl;	state Exp;
branches;
next	1.47;

1.47
date	2005.11.03.00.51.43;	author neilc;	state Exp;
branches;
next	1.46;

1.46
date	2005.11.01.23.19.05;	author neilc;	state Exp;
branches;
next	1.45;

1.45
date	2005.10.23.19.29.49;	author tgl;	state Exp;
branches;
next	1.44;

1.44
date	2005.08.13.01.55.41;	author momjian;	state Exp;
branches;
next	1.43;

1.43
date	2005.08.12.01.35.53;	author tgl;	state Exp;
branches;
next	1.42;

1.42
date	2005.07.14.06.17.35;	author neilc;	state Exp;
branches;
next	1.41;

1.41
date	2005.06.13.02.40.01;	author neilc;	state Exp;
branches;
next	1.40;

1.40
date	2005.03.13.09.36.30;	author neilc;	state Exp;
branches;
next	1.39;

1.39
date	2005.01.22.22.56.35;	author momjian;	state Exp;
branches;
next	1.38;

1.38
date	2005.01.17.01.29.02;	author tgl;	state Exp;
branches
	1.38.4.1;
next	1.37;

1.37
date	2005.01.09.17.47.30;	author tgl;	state Exp;
branches;
next	1.36;

1.36
date	2005.01.08.01.44.05;	author tgl;	state Exp;
branches;
next	1.35;

1.35
date	2004.12.23.05.37.39;	author tgl;	state Exp;
branches;
next	1.34;

1.34
date	2004.12.13.18.05.08;	author petere;	state Exp;
branches;
next	1.33;

1.33
date	2004.11.27.21.27.06;	author petere;	state Exp;
branches;
next	1.32;

1.32
date	2004.11.15.06.32.13;	author neilc;	state Exp;
branches;
next	1.31;

1.31
date	2004.10.21.21.33.59;	author tgl;	state Exp;
branches;
next	1.30;

1.30
date	2004.08.08.21.33.11;	author tgl;	state Exp;
branches;
next	1.29;

1.29
date	2004.08.07.20.44.49;	author tgl;	state Exp;
branches;
next	1.28;

1.28
date	2004.08.07.19.53.48;	author tgl;	state Exp;
branches;
next	1.27;

1.27
date	2004.08.03.20.32.30;	author tgl;	state Exp;
branches;
next	1.26;

1.26
date	2004.03.07.04.31.01;	author neilc;	state Exp;
branches;
next	1.25;

1.25
date	2003.11.29.19.51.36;	author pgsql;	state Exp;
branches;
next	1.24;

1.24
date	2003.11.24.19.08.01;	author petere;	state Exp;
branches;
next	1.23;

1.23
date	2003.11.05.00.05.32;	author tgl;	state Exp;
branches;
next	1.22;

1.22
date	2003.11.04.09.55.38;	author petere;	state Exp;
branches;
next	1.21;

1.21
date	2003.11.01.01.56.29;	author petere;	state Exp;
branches
	1.21.2.1;
next	1.20;

1.20
date	2003.10.28.20.18.09;	author tgl;	state Exp;
branches;
next	1.19;

1.19
date	2003.09.12.22.17.22;	author tgl;	state Exp;
branches;
next	1.18;

1.18
date	2003.08.31.17.32.18;	author petere;	state Exp;
branches;
next	1.17;

1.17
date	2003.08.14.23.13.27;	author tgl;	state Exp;
branches
	1.17.2.1;
next	1.16;

1.16
date	2003.08.10.01.20.34;	author tgl;	state Exp;
branches;
next	1.15;

1.15
date	2003.05.07.03.41.31;	author tgl;	state Exp;
branches;
next	1.14;

1.14
date	2003.03.25.16.15.35;	author petere;	state Exp;
branches;
next	1.13;

1.13
date	2003.03.13.01.30.28;	author petere;	state Exp;
branches;
next	1.12;

1.12
date	2003.02.19.04.06.27;	author momjian;	state Exp;
branches;
next	1.11;

1.11
date	2003.02.19.03.13.24;	author momjian;	state Exp;
branches;
next	1.10;

1.10
date	2002.11.15.03.11.15;	author momjian;	state Exp;
branches;
next	1.9;

1.9
date	2002.11.11.20.14.02;	author petere;	state Exp;
branches;
next	1.8;

1.8
date	2002.10.24.21.10.58;	author tgl;	state Exp;
branches
	1.8.2.1;
next	1.7;

1.7
date	2002.10.24.17.48.54;	author petere;	state Exp;
branches;
next	1.6;

1.6
date	2002.10.20.05.05.46;	author tgl;	state Exp;
branches;
next	1.5;

1.5
date	2002.09.21.18.32.52;	author petere;	state Exp;
branches;
next	1.4;

1.4
date	2002.09.12.22.05.35;	author petere;	state Exp;
branches;
next	1.3;

1.3
date	2002.09.05.21.32.23;	author petere;	state Exp;
branches;
next	1.2;

1.2
date	2002.08.28.20.17.44;	author momjian;	state Exp;
branches;
next	1.1;

1.1
date	2002.08.05.19.44.57;	author petere;	state Exp;
branches;
next	;

1.8.2.1
date	2002.11.10.12.45.42;	author petere;	state Exp;
branches;
next	;

1.17.2.1
date	2003.09.07.04.36.41;	author momjian;	state Exp;
branches;
next	;

1.21.2.1
date	2003.11.04.09.45.29;	author petere;	state Exp;
branches;
next	1.21.2.2;

1.21.2.2
date	2003.11.05.00.05.37;	author tgl;	state Exp;
branches;
next	;

1.38.4.1
date	2005.01.22.23.05.47;	author momjian;	state Exp;
branches;
next	;

1.69.2.1
date	2007.05.03.15.06.13;	author neilc;	state Exp;
branches;
next	1.69.2.2;

1.69.2.2
date	2007.05.15.19.43.59;	author neilc;	state Exp;
branches;
next	;

1.93.2.1
date	2010.07.29.19.34.36;	author petere;	state Exp;
branches;
next	1.93.2.2;

1.93.2.2
date	2010.08.23.02.43.35;	author tgl;	state Exp;
branches;
next	1.93.2.3;

1.93.2.3
date	2010.08.26.21.08.43;	author tgl;	state Exp;
branches;
next	;


desc
@@


1.97
log
@Explain automatic creation (or lack of it) of indexes for the various types
of constraints.

Kevin Grittner
@
text
@<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.96 2010/08/23 02:43:25 tgl Exp $ -->

<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
  schemas, and how privileges can be assigned to tables.  Finally,
  we will briefly look at other features that affect the data storage,
  such as inheritance, views, functions, and triggers.
 </para>

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

  <indexterm zone="ddl-basics">
   <primary>table</primary>
  </indexterm>

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

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

  <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 &mdash; 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 an unspecified 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>

  <indexterm>
   <primary>table</primary>
   <secondary>creating</secondary>
  </indexterm>

  <para>
   To create a table, you use the aptly named <xref
   linkend="sql-createtable"> command.
   In this command you specify at least a 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
   usually also identifiers, but there are some exceptions.  Note that the
   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
    consistent naming pattern for the tables and columns.  For
    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>

  <indexterm>
   <primary>table</primary>
   <secondary>removing</secondary>
  </indexterm>

  <para>
   If you no longer need a table, you can remove it using the <xref
   linkend="sql-droptable"> command.
   For example:
<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 any error
   messages, so that the script works whether or not the table exists.
   (If you like, you can use the <literal>DROP TABLE IF EXISTS</> variant
   to avoid the error messages, but this is not standard SQL.)
  </para>

  <para>
   If you need to modify a table that already exists, see <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>

 <sect1 id="ddl-default">
  <title>Default Values</title>

  <indexterm zone="ddl-default">
   <primary>default value</primary>
  </indexterm>

  <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, those
   columns will be filled with their respective default values.  A
   data manipulation command can also request explicitly that a column
   be set to its default value, without having to know what that value is.
   (Details about data manipulation commands are in <xref linkend="dml">.)
  </para>

  <para>
   <indexterm><primary>null value</primary><secondary>default value</secondary></indexterm>
   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.
  </para>

  <para>
   In a table definition, default values are listed after the column
   data type.  For example:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric <emphasis>DEFAULT 9.99</emphasis>
);
</programlisting>
  </para>

  <para>
   The default value can be an expression, which will be
   evaluated whenever the default value is inserted
   (<emphasis>not</emphasis> when the table is created).  A common example
   is for a <type>timestamp</type> column to have a default of <literal>CURRENT_TIMESTAMP</>,
   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">.
  </para>
 </sect1>

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

  <indexterm zone="ddl-constraints">
   <primary>constraint</primary>
  </indexterm>

  <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
   standard data type that accepts only positive numbers.  Another issue is
   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 be only 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>

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

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

   <para>
    A check constraint is the most generic constraint type.  It allows
    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:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric <emphasis>CHECK (price &gt; 0)</emphasis>
);
</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>

   <indexterm>
    <primary>constraint</primary>
    <secondary>name</secondary>
   </indexterm>

   <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,
    price numeric <emphasis>CONSTRAINT positive_price</emphasis> CHECK (price &gt; 0)
);
</programlisting>
    So, to specify a named constraint, use the key word
    <literal>CONSTRAINT</literal> followed by an identifier followed
    by the constraint definition.  (If you don't specify a constraint
    name in this way, the system chooses a name for you.)
   </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,
    price numeric CHECK (price &gt; 0),
    discounted_price numeric CHECK (discounted_price &gt; 0),
    <emphasis>CHECK (price &gt; discounted_price)</emphasis>
);
</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
    column list.  Column definitions and these constraint
    definitions can be listed in mixed order.
   </para>

   <para>
    We say that the first two constraints are column constraints, whereas the
    third one is a table constraint because it is written separately
    from any one column definition.  Column constraints can also be
    written as table constraints, while the reverse is not necessarily
    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:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    CHECK (price &gt; 0),
    discounted_price numeric,
    CHECK (discounted_price &gt; 0),
    CHECK (price &gt; discounted_price)
);
</programlisting>
    or even:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price &gt; 0),
    discounted_price numeric,
    CHECK (discounted_price &gt; 0 AND price &gt; discounted_price)
);
</programlisting>
    It's a matter of taste.
   </para>

   <para>
    Names can be assigned to table constraints in the same way as
    column constraints:
<programlisting>
CREATE TABLE products (
    product_no integer,
    name text,
    price numeric,
    CHECK (price &gt; 0),
    discounted_price numeric,
    CHECK (discounted_price &gt; 0),
    <emphasis>CONSTRAINT valid_discount</> CHECK (price &gt; discounted_price)
);
</programlisting>
   </para>

   <indexterm>
    <primary>null value</primary>
    <secondary sortas="check constraints">with check constraints</secondary>
   </indexterm>

   <para>
    It should be noted that a check constraint is satisfied if the
    check expression evaluates to true or the null value.  Since most
    expressions will evaluate to the null value if any operand is null,
    they will not prevent null values in the constrained columns.  To
    ensure that a column does not contain null values, the not-null
    constraint described in the next section can be used.
   </para>
  </sect2>

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

   <indexterm>
    <primary>not-null constraint</primary>
   </indexterm>

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

   <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
    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
    cannot give explicit names to not-null constraints created this
    way.
   </para>

   <para>
    Of course, a column can have more than one constraint.  Just write
    the constraints one after another:
<programlisting>
CREATE TABLE products (
    product_no integer NOT NULL,
    name text NOT NULL,
    price numeric NOT NULL CHECK (price &gt; 0)
);
</programlisting>
    The order doesn't matter.  It does not necessarily determine in which
    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
    simply selects the default behavior that the column might be null.
    The <literal>NULL</literal> constraint is not present in the SQL
    standard and should not be used in portable applications.  (It was
    only added to <productname>PostgreSQL</productname> to be
    compatible with some other database systems.)  Some users, however,
    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>

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

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

   <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>
    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.
   </para>

   <para>
    You can assign your own name for a unique constraint, in the usual way:
<programlisting>
CREATE TABLE products (
    product_no integer <emphasis>CONSTRAINT must_be_different</emphasis> UNIQUE,
    name text,
    price numeric
);
</programlisting>
   </para>

   <para>
    Adding a unique constraint will automatically create a unique btree
    index on the column or group of columns used in the constraint.
   </para>

   <indexterm>
    <primary>null value</primary>
    <secondary sortas="unique constraints">with unique constraints</secondary>
   </indexterm>

   <para>
    In general, a unique constraint is violated when there is more than
    one row in the table where the values of all of the
    columns included in the constraint are equal.
    However, two null values are not considered equal in this
    comparison.  That means even in the presence of a
    unique constraint it is possible to store duplicate
    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 might not follow this rule.  So be
    careful when developing applications that are intended to be
    portable.
   </para>
  </sect2>

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

   <indexterm>
    <primary>primary key</primary>
   </indexterm>

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

   <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
    a unique constraint does not, by itself, provide a unique identifier
    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>
    Adding a primary key will automatically create a unique btree index
    on the column or group of columns used in the primary key.
   </para>

   <para>
    A table can have at most one primary key.  (There can be any number
    of unique and not-null constraints, which are functionally the same
    thing, but only one can be identified as the primary key.)
    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>

   <indexterm>
    <primary>foreign key</primary>
   </indexterm>

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

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

   <para>
    A foreign key constraint specifies that the values in a column (or
    a group of columns) must match the values appearing in some row
    of another table.
    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
    <structfield>product_no</structfield> entries that do not appear in the
    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,
    product_no integer <emphasis>REFERENCES products</emphasis>,
    quantity integer
);
</programlisting>
    because in absence of a column list the primary key of the
    referenced table is used as the referenced column(s).
   </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>
    Of course, the number and type of the constrained columns need to
    match the number and type of the referenced columns.
   </para>

   <para>
    You can assign your own name for a foreign key constraint,
    in the usual way.
   </para>

   <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>
    Notice that the primary key overlaps with the foreign keys in
    the last table.
   </para>

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

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

   <para>
    We know that the foreign keys disallow creation of orders that
    do not relate to any products.  But what if a product is removed
    after an order is created that references it?  SQL allows you to
    handle that as well.  Intuitively, we have a few options:
    <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
    many-to-many relationship example above: when someone wants to
    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.
    <literal>RESTRICT</literal> prevents deletion of a
    referenced row. <literal>NO ACTION</literal> means that if any
    referencing rows still exist when the constraint is checked, an error
    is raised; this is the default behavior if you do not specify anything.
    (The essential difference between these two choices is that
    <literal>NO ACTION</literal> allows the check to be deferred until
    later in the transaction, whereas <literal>RESTRICT</literal> does not.)
    <literal>CASCADE</> specifies that when a referenced row is deleted,
    row(s) referencing it should be automatically deleted as well.
    There are two other options:
    <literal>SET NULL</literal> and <literal>SET DEFAULT</literal>.
    These cause the referencing columns to be set to nulls or default
    values, respectively, when the referenced row is deleted.
    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
    operation will fail.
   </para>

   <para>
    Analogous to <literal>ON DELETE</literal> there is also
    <literal>ON UPDATE</literal> which is invoked when a referenced
    column is changed (updated).  The possible actions are the same.
   </para>

   <para>
    Since a <command>DELETE</command> of a row from the referenced table
    or an <command>UPDATE</command> of a referenced column will require
    a scan of the referencing table for rows matching the old value, it
    is often a good idea to index the referencing columns.  Because this
    is not always needed, and there are many choices available on how
    to index, declaration of a foreign key constraint does not
    automatically create an index on the referencing columns.
   </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
    columns that either are a primary key or form a unique constraint.
    If the foreign key references a unique constraint, there are some
    additional possibilities regarding how null values are matched.
    These are explained in the reference documentation for
    <xref linkend="sql-createtable">.
   </para>
  </sect2>

  <sect2 id="ddl-constraints-exclusion">
   <title>Exclusion constraints</title>

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

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

   <para>
    Exclusion constraints ensure that if any two rows are compared on
    the specified columns or expressions using the specified operators,
    at least one of these operator comparisons will return false or null.
    The syntax is:
<programlisting>
CREATE TABLE circles (
    c circle,
    EXCLUDE USING gist (c WITH &amp;&amp;)
);
</programlisting>
   </para>

   <para>
    See also <link linkend="SQL-CREATETABLE-EXCLUDE"><command>CREATE
    TABLE ... CONSTRAINT ... EXCLUDE</></link> for details.
   </para>

   <para>
    Adding an exclusion constraint will automatically create an index
    of the type specified in the constraint declaration.
   </para>
  </sect2>
 </sect1>

 <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>
      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">
      configuration variable was set at the time. This column is of type
      <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 (see <xref linkend="ddl-inherit">), 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 if 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
       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
       might suffer.)
      </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>
       Of course, the tables in question must be created <literal>WITH
       OIDS</literal>.  As of <productname>PostgreSQL</productname> 8.1,
       <literal>WITHOUT OIDS</> is the default.
      </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 the number of
    <acronym>SQL</acronym> commands, not the number of rows processed.
    Also, as of <productname>PostgreSQL</productname> 8.3, only commands
    that actually modify the database contents will consume a command
    identifier.
   </para>
 </sect1>

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

  <indexterm zone="ddl-alter">
   <primary>table</primary>
   <secondary>modifying</secondary>
  </indexterm>

  <para>
   When you create a table and you realize that you made a mistake, or
   the requirements of the application change, you can drop the
   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>
   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.
  </para>

  <para>
   You can:
   <itemizedlist spacing="compact">
    <listitem>
     <para>Add columns</para>
    </listitem>
    <listitem>
     <para>Remove columns</para>
    </listitem>
    <listitem>
     <para>Add constraints</para>
    </listitem>
    <listitem>
     <para>Remove constraints</para>
    </listitem>
    <listitem>
     <para>Change default values</para>
    </listitem>
    <listitem>
     <para>Change column data types</para>
    </listitem>
    <listitem>
     <para>Rename columns</para>
    </listitem>
    <listitem>
     <para>Rename tables</para>
    </listitem>
   </itemizedlist>

   All these actions are performed using the
   <xref linkend="sql-altertable">
   command, whose reference page contains details beyond those given
   here.
  </para>

  <sect2>
   <title>Adding a Column</title>

   <indexterm>
    <primary>column</primary>
    <secondary>adding</secondary>
   </indexterm>

   <para>
    To add a column, use a command like:
<programlisting>
ALTER TABLE products ADD COLUMN description text;
</programlisting>
    The new column is initially filled with whatever default
    value is given (null if you don't specify a <literal>DEFAULT</> clause).
   </para>

   <para>
    You can also define constraints on the column at the same time,
    using the usual syntax:
<programlisting>
ALTER TABLE products ADD COLUMN description text CHECK (description &lt;&gt; '');
</programlisting>
    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.
   </para>

  <tip>
   <para>
    Adding a column with a default requires updating each row of the
    table (to store the new column value).  However, if no default is
    specified, <productname>PostgreSQL</productname> is able to avoid
    the physical update.  So if you intend to fill the column with
    mostly nondefault values, it's best to add the column with no default,
    insert the correct values using <command>UPDATE</>, and then add any
    desired default as described below.
   </para>
  </tip>
  </sect2>

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

   <indexterm>
    <primary>column</primary>
    <secondary>removing</secondary>
   </indexterm>

   <para>
    To remove a column, use a command like:
<programlisting>
ALTER TABLE products DROP COLUMN description;
</programlisting>
    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.
   </para>
  </sect2>

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

   <indexterm>
    <primary>constraint</primary>
    <secondary>adding</secondary>
   </indexterm>

   <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>

   <indexterm>
    <primary>constraint</primary>
    <secondary>removing</secondary>
   </indexterm>

   <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>
    (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>

   <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>

   <para>
    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>
   <title>Changing a Column's Default Value</title>

   <indexterm>
    <primary>default value</primary>
    <secondary>changing</secondary>
   </indexterm>

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

   <para>
    To remove any default value, use:
<programlisting>
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
</programlisting>
    This is effectively the same as setting the default to null.
    As a consequence, it is not an error
    to drop a default where one hadn't been defined, because the
    default is implicitly the null value.
   </para>
  </sect2>

  <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:
<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 might fail, or might
    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>

  <sect2>
   <title>Renaming a Column</title>

   <indexterm>
    <primary>column</primary>
    <secondary>renaming</secondary>
   </indexterm>

   <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>

   <indexterm>
    <primary>table</primary>
    <secondary>renaming</secondary>
   </indexterm>

   <para>
    To rename a table:
<programlisting>
ALTER TABLE products RENAME TO items;
</programlisting>
   </para>
  </sect2>
 </sect1>

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

  <indexterm zone="ddl-priv">
   <primary>privilege</primary>
  </indexterm>

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

  <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,
   <firstterm>privileges</firstterm> must be granted.  (However,
   users that have the superuser attribute can always
   access any object.)
  </para>

  <para>
   There are several different privileges: <literal>SELECT</>,
   <literal>INSERT</>, <literal>UPDATE</>, <literal>DELETE</>,
   <literal>TRUNCATE</>, <literal>REFERENCES</>, <literal>TRIGGER</>,
   <literal>CREATE</>, <literal>CONNECT</>, <literal>TEMPORARY</>,
   <literal>EXECUTE</>, and <literal>USAGE</>.
   The privileges applicable to a particular
   object vary depending on the object's type (table, function, etc).
   For complete information on the different types of privileges
   supported by <productname>PostgreSQL</productname>, refer to the
   <xref linkend="sql-grant"> reference
   page.  The following sections and chapters will also show you how
   those privileges are used.
  </para>

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

  <note>
   <para>
    To change the owner of a table, index, sequence, or view, use the
    <xref linkend="sql-altertable">
    command.  There are corresponding <literal>ALTER</> commands for
    other object types.
   </para>
  </note>

  <para>
   To assign privileges, the <command>GRANT</command> command is
   used. For example, if <literal>joe</literal> is an existing user, and
   <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>
   Writing <literal>ALL</literal> in place of a specific privilege grants all
   privileges that are relevant for the object type.
  </para>

  <para>
   The special <quote>user</quote> name <literal>PUBLIC</literal> can
   be used to grant a privilege to every user on the system.  Also,
   <quote>group</> roles can be set up to help manage privileges when
   there are many users of a database &mdash; for details see
   <xref linkend="user-manag">.
  </para>

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

  <para>
   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"> and
   <xref linkend="sql-revoke"> reference pages.
  </para>
 </sect1>

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

  <indexterm zone="ddl-schemas">
   <primary>schema</primary>
  </indexterm>

  <para>
   A <productname>PostgreSQL</productname> database cluster
   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</> can
   contain tables named <literal>mytable</>.  Unlike databases,
   schemas are not rigidly separated: a user can 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 do not collide with the names of other objects.
     </para>
    </listitem>
   </itemizedlist>

   Schemas are analogous to directories at the operating system level,
   except that schemas cannot be nested.
  </para>

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

   <indexterm zone="ddl-schemas-create">
    <primary>schema</primary>
    <secondary>creating</secondary>
   </indexterm>

   <para>
    To create a schema, use the <xref linkend="sql-createschema">
    command.  Give the schema a name
    of your choice.  For example:
<programlisting>
CREATE SCHEMA myschema;
</programlisting>
   </para>

   <indexterm>
    <primary>qualified name</primary>
   </indexterm>

   <indexterm>
    <primary>name</primary>
    <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>
    This works anywhere a table name is expected, including the table
    modification commands and the data access commands discussed in
    the following chapters.
    (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>
    Actually, the even more general syntax
<synopsis>
<replaceable>database</><literal>.</><replaceable>schema</><literal>.</><replaceable>table</>
</synopsis>
    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.
   </para>

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

   <indexterm>
    <primary>schema</primary>
    <secondary>removing</secondary>
   </indexterm>

   <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>
CREATE SCHEMA <replaceable>schemaname</replaceable> AUTHORIZATION <replaceable>username</replaceable>;
</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 cannot be created by users.
   </para>
  </sect2>

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

   <indexterm zone="ddl-schemas-public">
    <primary>schema</primary>
    <secondary>public</secondary>
   </indexterm>

   <para>
    In the previous sections we created tables without specifying any
    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:
<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>
    <primary>unqualified name</primary>
   </indexterm>

   <indexterm>
    <primary>name</primary>
    <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>

   <indexterm>
    <primary>schema</primary>
    <secondary>current</secondary>
   </indexterm>

   <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>

   <indexterm>
    <primary>search_path</primary>
   </indexterm>

   <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
    the current user is to be searched.  If no such schema exists,
    the entry is ignored.  The second element refers to the
    public schema that we have seen already.
   </para>

   <para>
    The first schema in the search path that exists is the default
    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>
    See also <xref linkend="functions-info"> for other ways to manipulate
    the schema search path.
   </para>

   <para>
    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
    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>

   <indexterm zone="ddl-schemas-priv">
    <primary>privilege</primary>
    <secondary sortas="schemas">for schemas</secondary>
   </indexterm>

   <para>
    By default, users cannot access any objects in schemas they do not
    own.  To allow that, the owner of the schema must grant the
    <literal>USAGE</literal> privilege on the schema.  To allow users
    to make use of the objects in the schema, additional privileges
    might 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
    has <literal>CREATE</literal> and <literal>USAGE</literal> privileges on
    the schema
    <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
    not want to allow that, you can revoke that privilege:
<programlisting>
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
</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
    key word, hence the different capitalization; recall the
    guidelines from <xref linkend="sql-syntax-identifiers">.)
   </para>
  </sect2>

  <sect2 id="ddl-schemas-catalog">
   <title>The System Catalog Schema</title>

   <indexterm zone="ddl-schemas-catalog">
    <primary>system catalog</primary>
    <secondary>schema</secondary>
   </indexterm>

   <para>
    In addition to <literal>public</> and user-created schemas, each
    database contains a <literal>pg_catalog</> schema, which contains
    the system tables and all the built-in data types, functions, and
    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 can 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 can 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
    future version defines a system table named the same as your
    table.  (With the default search path, an unqualified reference to
    your table name would then be resolved as the system table instead.)
    System tables will continue to follow the convention of having
    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
    a few usage patterns that are recommended and are easily supported by
    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
       recommended when there is only a single user or a few cooperating
       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
       then refer to these additional objects by qualifying the names
       with a schema name, or they can put the additional schemas into
       their search path, as they choose.
      </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
    implementations do not allow you to create schemas that have a
    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>.
    This is how <productname>PostgreSQL</productname> will effectively
    behave if you create a per-user schema for every user.
   </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>
 </sect1>

 <sect1 id="ddl-inherit">
  <title>Inheritance</title>

  <indexterm>
   <primary>inheritance</primary>
  </indexterm>

  <indexterm>
   <primary>table</primary>
   <secondary>inheritance</secondary>
  </indexterm>

  <para>
   <productname>PostgreSQL</productname> implements table inheritance,
   which can be a useful tool for database designers.  (SQL:1999 and
   later define a type inheritance feature, which differs in many
   respects from the features described here.)
  </para>

  <para>
   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
   <structname>capitals</structname> table so that it inherits from
   <structname>cities</structname>:

<programlisting>
CREATE TABLE cities (
    name            text,
    population      float,
    altitude        int     -- in feet
);

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

   In this case, the <structname>capitals</> table <firstterm>inherits</>
   all the columns of its parent table, <structname>cities</>. State
   capitals also have an extra column, <structfield>state</>, that shows
   their state.
  </para>

  <para>
   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 descendant tables.
   The latter behavior is the default.
   For example, the following query finds the names of all cities,
   including state capitals, that are located at an altitude over
   500 feet:

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

   Given the sample data from the <productname>PostgreSQL</productname>
   tutorial (see <xref linkend="tutorial-sql-intro">), this returns:

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

  <para>
   On the other hand, the following query finds all the cities that
   are not state capitals and are situated at an altitude over 500 feet:

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

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

  <para>
   Here the <literal>ONLY</literal> keyword indicates that the query
   should apply only to <structname>cities</structname>, and not any tables
   below <structname>cities</structname> 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.
  </para>

  <para>
   In some cases you might 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:

<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>

   (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:

<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>

  <para>
   Inheritance does not automatically propagate 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 somehow be routed to the
   <structname>capitals</structname> table, but this does not happen:
   <command>INSERT</command> always inserts into exactly the table
   specified.  In some cases it is possible to redirect the insertion
   using a rule (see <xref linkend="rules">).  However that does not
   help for the above case because the <structname>cities</> table
   does not contain the column <structfield>state</>, and so the
   command will be rejected before the rule can be applied.
  </para>

  <para>
   All check constraints and not-null constraints on a parent table are
   automatically inherited by its children.  Other types of constraints
   (unique, primary key, and foreign key constraints) are not inherited.
  </para>

  <para>
   A table can inherit from more than one parent table, in which case it has
   the union of the columns defined by the parent tables.  Any columns
   declared in the child table's definition are added to these.  If the
   same column name appears in multiple parent tables, or in both a parent
   table and the child's definition, then these columns are <quote>merged</>
   so that there is only one such column in the child table.  To be merged,
   columns must have the same data types, else an error is raised.  The
   merged column will have copies of all the check constraints coming from
   any one of the column definitions it came from, and will be marked not-null
   if any of them are.
  </para>

  <para>
   Table inheritance is typically established when the child table is
   created, using the <literal>INHERITS</> clause of the
   <xref linkend="sql-createtable">
   statement.
   Alternatively, a table which is already defined in a compatible way can
   have a new parent relationship added, using the <literal>INHERIT</literal>
   variant of <xref linkend="sql-altertable">.
   To do this the new child table must already include columns with
   the same names and types as the columns of the parent. It must also include
   check constraints with the same names and check expressions as those of the
   parent. Similarly an inheritance link can be removed from a child using the
   <literal>NO INHERIT</literal> variant of <command>ALTER TABLE</>.
   Dynamically adding and removing inheritance links like this can be useful
   when the inheritance relationship is being used for table
   partitioning (see <xref linkend="ddl-partitioning">).
  </para>

  <para>
   One convenient way to create a compatible table that will later be made
   a new child is to use the <literal>LIKE</literal> clause in <command>CREATE
   TABLE</command>. This creates a new table with the same columns as
   the source table. If there are any <literal>CHECK</literal>
   constraints defined on the source table, the <literal>INCLUDING
   CONSTRAINTS</literal> option to <literal>LIKE</literal> should be
   specified, as the new child must have constraints matching the parent
   to be considered compatible.
  </para>

  <para>
   A parent table cannot be dropped while any of its children remain. Neither
   can columns or check constraints of child tables be dropped or altered
   if they are inherited
   from any parent tables. If you wish to remove a table and all of its
   descendants, one easy way is to drop the parent table with the
   <literal>CASCADE</literal> option.
  </para>

  <para>
   <xref linkend="sql-altertable"> will
   propagate any changes in column data definitions and check
   constraints down the inheritance hierarchy.  Again, dropping
   columns that are depended on by other 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>.
  </para>

  <para>
   Note how table access permissions are handled.  Querying a parent
   table can automatically access data in child tables without further
   access privilege checking.  This preserves the appearance that the
   data is (also) in the parent table.  Accessing the child tables
   directly is, however, not automatically allowed and would require
   further privileges to be granted.
  </para>

 <sect2 id="ddl-inherit-caveats">
  <title>Caveats</title>

  <para>
   Note that not all SQL commands are able to work on
   inheritance hierarchies.  Commands that are used for data querying,
   data modification, or schema modification
   (e.g., <literal>SELECT</literal>, <literal>UPDATE</literal>, <literal>DELETE</literal>,
   most variants of <literal>ALTER TABLE</literal>, but
   not <literal>INSERT</literal> and <literal>ALTER TABLE ...
   RENAME</literal>) typically default to including child tables and
   support the <literal>ONLY</literal> notation to exclude them.
   Commands that do database maintenance and tuning
   (e.g., <literal>REINDEX</literal>, <literal>VACUUM</literal>)
   typically only work on individual, physical tables and do no
   support recursing over inheritance hierarchies.  The respective
   behavior of each individual command is documented in the reference
   part (<xref linkend="sql-commands">).
  </para>

  <para>
   A serious limitation of the inheritance feature is that indexes (including
   unique constraints) and foreign key constraints only apply to single
   tables, not to their inheritance children. This is true on both the
   referencing and referenced sides of a foreign key constraint. Thus,
   in the terms of the above example:

   <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
      default show up in queries from <structname>cities</>.  In fact, by
      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
      <structname>capitals</>.  In this case you could work around it by
      manually adding the same <literal>REFERENCES</> constraint to
      <structname>capitals</>.
     </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 application.
  </para>

  <note>
   <title>Deprecated</title>
   <para>
     In releases of <productname>PostgreSQL</productname> prior to 7.1, the
     default behavior was not to include child tables in queries. This was
     found to be error prone and also in violation of the SQL
     standard.  You can get the pre-7.1 behavior by turning off the
     <xref linkend="guc-sql-inheritance"> configuration
     option.
   </para>
  </note>

   </sect2>
  </sect1>

  <sect1 id="ddl-partitioning">
   <title>Partitioning</title>

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

   <indexterm>
    <primary>table</primary>
    <secondary>partitioning</secondary>
   </indexterm>

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

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

   <para>
    Partitioning refers to splitting what is logically one large table
    into smaller physical pieces.
    Partitioning can provide several benefits:
   <itemizedlist>
    <listitem>
     <para>
      Query performance can be improved dramatically in certain situations,
      particularly when most of the heavily accessed rows of the table are in a
      single partition or a small number of partitions.  The partitioning
      substitutes for leading columns of indexes, reducing index size and
      making it more likely that the heavily-used parts of the indexes
      fit in memory.
     </para>
    </listitem>

    <listitem>
     <para>
      When queries or updates access a large percentage of a single
      partition, performance can be improved by taking advantage
      of sequential scan of that partition instead of using an
      index and random access reads scattered across the whole table.
     </para>
    </listitem>

    <listitem>
     <para>
      Bulk loads and deletes can be accomplished by adding or removing
      partitions, if that requirement is planned into the partitioning design.
      <command>ALTER TABLE</> is far faster than a bulk operation.
      It also entirely avoids the <command>VACUUM</command>
      overhead caused by a bulk <command>DELETE</>.
     </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 table would
    otherwise be very large. The exact point at which a table will
    benefit from partitioning depends on the application, although a
    rule of thumb is that the size of the table should exceed the physical
    memory of the database server.
   </para>

   <para>
    Currently, <productname>PostgreSQL</productname> supports partitioning
    via table inheritance.  Each partition must be created as a child
    table of a single parent table.  The parent table itself is normally
    empty; it exists just to represent the entire data set.  You should be
    familiar with inheritance (see <xref linkend="ddl-inherit">) before
    attempting to set up partitioning.
   </para>

   <para>
    The following forms of partitioning can be implemented in
    <productname>PostgreSQL</productname>:

    <variablelist>
     <varlistentry>
      <term>Range Partitioning</term>

      <listitem>
       <para>
        The table is partitioned into <quote>ranges</quote> defined
        by a key column or set of columns, with no overlap between
        the ranges of values assigned to different partitions.  For
        example one might partition by date ranges, or by ranges of
        identifiers for particular business objects.
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>List Partitioning</term>

      <listitem>
       <para>
        The table is partitioned by explicitly listing which key values
        appear in each partition.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
   </para>
   </sect2>

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

    <para>
     To set up a partitioned table, 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 check
        constraints on this table, unless you intend them to
        be applied equally to all partitions.  There is no point
        in defining any indexes or unique constraints on it, either.
       </para>
      </listitem>

      <listitem>
       <para>
        Create several <quote>child</quote> tables that each inherit from
        the master table.  Normally, these tables will not add any columns
        to the set inherited from the master.
       </para>

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

      <listitem>
       <para>
        Add table constraints to the partition tables to define the
        allowed key values in each partition.
       </para>

       <para>
        Typical examples would be:
<programlisting>
CHECK ( x = 1 )
CHECK ( county IN ( 'Oxfordshire', 'Buckinghamshire', 'Warwickshire' ))
CHECK ( outletID &gt;= 100 AND outletID &lt; 200 )
</programlisting>
        Ensure that the constraints guarantee that there is no overlap
        between the key values permitted in different partitions.  A common
        mistake is to set up range constraints like:
<programlisting>
CHECK ( outletID BETWEEN 100 AND 200 )
CHECK ( outletID BETWEEN 200 AND 300 )
</programlisting>
        This is wrong since it is not clear which partition the key value
        200 belongs in.
       </para>

       <para>
        Note that there is no difference in
        syntax between range and list partitioning; those terms are
        descriptive only.
       </para>
      </listitem>

      <listitem>
       <para>
        For each partition, create an index on the key column(s),
        as well as any other indexes you might want.  (The key index is
        not strictly necessary, but in most scenarios it is helpful.
        If you intend the key values to be unique then you should
        always create a unique or primary-key constraint for each
        partition.)
       </para>
      </listitem>

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

      <listitem>
       <para>
        Ensure that the <xref linkend="guc-constraint-exclusion">
        configuration parameter is not disabled in
        <filename>postgresql.conf</>.
        If it is, queries will not be optimized as desired.
       </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. Conceptually,
     we want a table like:

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

     We know that most queries will access just the last week's, month's or
     quarter's data, since the main use of this table will be to prepare
     online reports for management.
     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 will remove the oldest month's data.
    </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 set up as follows:
    </para>

    <para>
     <orderedlist spacing="compact">
      <listitem>
       <para>
        The master table is the <structname>measurement</> table, declared
        exactly as above.
       </para>
      </listitem>

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

<programlisting>
CREATE TABLE measurement_y2006m02 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2006m03 ( ) INHERITS (measurement);
...
CREATE TABLE measurement_y2007m11 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2007m12 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2008m01 ( ) INHERITS (measurement);
</programlisting>

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

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

      <listitem>
       <para>
        We must provide non-overlapping table constraints.  Rather than
        just creating the partition tables as above, the table creation
        script should really be:

<programlisting>
CREATE TABLE measurement_y2006m02 (
    CHECK ( logdate &gt;= DATE '2006-02-01' AND logdate &lt; DATE '2006-03-01' )
) INHERITS (measurement);
CREATE TABLE measurement_y2006m03 (
    CHECK ( logdate &gt;= DATE '2006-03-01' AND logdate &lt; DATE '2006-04-01' )
) INHERITS (measurement);
...
CREATE TABLE measurement_y2007m11 (
    CHECK ( logdate &gt;= DATE '2007-11-01' AND logdate &lt; DATE '2007-12-01' )
) INHERITS (measurement);
CREATE TABLE measurement_y2007m12 (
    CHECK ( logdate &gt;= DATE '2007-12-01' AND logdate &lt; DATE '2008-01-01' )
) INHERITS (measurement);
CREATE TABLE measurement_y2008m01 (
    CHECK ( logdate &gt;= DATE '2008-01-01' AND logdate &lt; DATE '2008-02-01' )
) INHERITS (measurement);
</programlisting>
       </para>
      </listitem>

      <listitem>
       <para>
        We probably need indexes on the key columns too:

<programlisting>
CREATE INDEX measurement_y2006m02_logdate ON measurement_y2006m02 (logdate);
CREATE INDEX measurement_y2006m03_logdate ON measurement_y2006m03 (logdate);
...
CREATE INDEX measurement_y2007m11_logdate ON measurement_y2007m11 (logdate);
CREATE INDEX measurement_y2007m12_logdate ON measurement_y2007m12 (logdate);
CREATE INDEX measurement_y2008m01_logdate ON measurement_y2008m01 (logdate);
</programlisting>

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

      <listitem>
       <para>
        We want our application to be able to say <literal>INSERT INTO
        measurement ...</> and have the data be redirected into the
        appropriate partition table.  We can arrange that by attaching
        a suitable trigger function to the master table.
        If data will be added only to the latest partition, we can
        use a very simple trigger function:

<programlisting>
CREATE OR REPLACE FUNCTION measurement_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO measurement_y2008m01 VALUES (NEW.*);
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;
</programlisting>

        After creating the function, we create a trigger which
        calls the trigger function:

<programlisting>
CREATE TRIGGER insert_measurement_trigger
    BEFORE INSERT ON measurement
    FOR EACH ROW EXECUTE PROCEDURE measurement_insert_trigger();
</programlisting>

        We must redefine the trigger function each month so that it always
        points to the current partition.  The trigger definition does
        not need to be updated, however.
       </para>

       <para>
        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 trigger function, for example:

<programlisting>
CREATE OR REPLACE FUNCTION measurement_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    IF ( NEW.logdate &gt;= DATE '2006-02-01' AND
         NEW.logdate &lt; DATE '2006-03-01' ) THEN
        INSERT INTO measurement_y2006m02 VALUES (NEW.*);
    ELSIF ( NEW.logdate &gt;= DATE '2006-03-01' AND
            NEW.logdate &lt; DATE '2006-04-01' ) THEN
        INSERT INTO measurement_y2006m03 VALUES (NEW.*);
    ...
    ELSIF ( NEW.logdate &gt;= DATE '2008-01-01' AND
            NEW.logdate &lt; DATE '2008-02-01' ) THEN
        INSERT INTO measurement_y2008m01 VALUES (NEW.*);
    ELSE
        RAISE EXCEPTION 'Date out of range.  Fix the measurement_insert_trigger() function!';
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;
</programlisting>

        The trigger definition is the same as before.
        Note that each <literal>IF</literal> test must exactly match the
        <literal>CHECK</literal> constraint for its partition.
       </para>

       <para>
        While this function is more complex than the single-month case,
        it doesn't need to be updated as often, since branches can be
        added in advance of being needed.
       </para>

       <note>
        <para>
         In practice it might be best to check the newest partition first,
         if most inserts go into that partition.  For simplicity we have
         shown the trigger's tests in the same order as in other parts
         of this example.
        </para>
       </note>
      </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 might be wise to write a
     script that generates the required DDL automatically.
    </para>

   </sect2>

   <sect2 id="ddl-partitioning-managing-partitions">
   <title>Managing Partitions</title>

   <para>
     Normally the set of partitions established when initially
     defining the table are not intended to remain static. It is
     common to want to remove old partitions of data and periodically
     add new partitions for new data. One of the most important
     advantages of partitioning is precisely that it allows this
     otherwise painful task to be executed nearly instantaneously by
     manipulating the partition structure, rather than physically moving large
     amounts of data around.
   </para>

   <para>
     The simplest option for removing old data is simply to drop the partition
     that is no longer necessary:
<programlisting>
DROP TABLE measurement_y2006m02;
</programlisting>
     This can very quickly delete millions of records because it doesn't have
     to individually delete every record.
   </para>

   <para>
     Another option that is often preferable is to remove the partition from
     the partitioned table but retain access to it as a table in its own
     right:
<programlisting>
ALTER TABLE measurement_y2006m02 NO INHERIT measurement;
</programlisting>
     This allows further operations to be performed on the data before
     it is dropped. For example, this is often a useful time to back up
     the data using <command>COPY</>, <application>pg_dump</>, or
     similar tools. It might also be a useful time to aggregate data
     into smaller formats, perform other data manipulations, or run
     reports.
   </para>

   <para>
     Similarly we can add a new partition to handle new data. We can create an
     empty partition in the partitioned table just as the original partitions
     were created above:

<programlisting>
CREATE TABLE measurement_y2008m02 (
    CHECK ( logdate &gt;= DATE '2008-02-01' AND logdate &lt; DATE '2008-03-01' )
) INHERITS (measurement);
</programlisting>

     As an alternative, it is sometimes more convenient to create the
     new table outside the partition structure, and make it a proper
     partition later. This allows the data to be loaded, checked, and
     transformed prior to it appearing in the partitioned table:

<programlisting>
CREATE TABLE measurement_y2008m02
  (LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
   CHECK ( logdate &gt;= DATE '2008-02-01' AND logdate &lt; DATE '2008-03-01' );
\copy measurement_y2008m02 from 'measurement_y2008m02'
-- possibly some other data preparation work
ALTER TABLE measurement_y2008m02 INHERIT measurement;
</programlisting>
    </para>
   </sect2>

   <sect2 id="ddl-partitioning-constraint-exclusion">
   <title>Partitioning and Constraint Exclusion</title>

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

   <para>
    <firstterm>Constraint exclusion</> is a query optimization technique
    that improves performance for partitioned tables defined in the
    fashion described above.  As an example:

<programlisting>
SET constraint_exclusion = on;
SELECT count(*) FROM measurement WHERE logdate &gt;= DATE '2008-01-01';
</programlisting>

    Without constraint exclusion, the above query would scan each of
    the partitions of the <structname>measurement</> table. With constraint
    exclusion enabled, the planner will examine the constraints of each
    partition and try to prove that the partition need not
    be scanned because it could not contain any rows meeting the query's
    <literal>WHERE</> clause.  When the planner can prove this, 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.  A typical unoptimized plan for this type of table setup is:

<programlisting>
SET constraint_exclusion = off;
EXPLAIN SELECT count(*) FROM measurement WHERE logdate &gt;= DATE '2008-01-01';

                                          QUERY PLAN
-----------------------------------------------------------------------------------------------
 Aggregate  (cost=158.66..158.68 rows=1 width=0)
   -&gt;  Append  (cost=0.00..151.88 rows=2715 width=0)
         -&gt;  Seq Scan on measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2008-01-01'::date)
         -&gt;  Seq Scan on measurement_y2006m02 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2008-01-01'::date)
         -&gt;  Seq Scan on measurement_y2006m03 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2008-01-01'::date)
...
         -&gt;  Seq Scan on measurement_y2007m12 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2008-01-01'::date)
         -&gt;  Seq Scan on measurement_y2008m01 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2008-01-01'::date)
</programlisting>

    Some or all of the partitions might use index scans instead of
    full-table sequential scans, but the point here is that there
    is no need to scan the older partitions at all to answer this query.
    When we enable constraint exclusion, we get a significantly
    cheaper plan that will deliver the same answer:

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

   <para>
    Note that constraint exclusion is driven only by <literal>CHECK</>
    constraints, not by the presence of indexes.  Therefore it isn't
    necessary to define indexes on the key columns.  Whether an index
    needs to be created for a given partition depends on whether you
    expect that queries that scan the partition will generally scan
    a large part of the partition or just a small part.  An index will
    be helpful in the latter case but not the former.
   </para>

   <para>
    The default (and recommended) setting of
    <xref linkend="guc-constraint-exclusion"> is actually neither
    <literal>on</> nor <literal>off</>, but an intermediate setting
    called <literal>partition</>, which causes the technique to be
    applied only to queries that are likely to be working on partitioned
    tables.  The <literal>on</> setting causes the planner to examine
    <literal>CHECK</> constraints in all queries, even simple ones that
    are unlikely to benefit.
   </para>

   </sect2>

   <sect2 id="ddl-partitioning-alternatives">
   <title>Alternative Partitioning Methods</title>

    <para>
     A different approach to redirecting inserts into the appropriate
     partition table is to set up rules, instead of a trigger, on the
     master table.  For example:

<programlisting>
CREATE RULE measurement_insert_y2006m02 AS
ON INSERT TO measurement WHERE
    ( logdate &gt;= DATE '2006-02-01' AND logdate &lt; DATE '2006-03-01' )
DO INSTEAD
    INSERT INTO measurement_y2006m02 VALUES (NEW.*);
...
CREATE RULE measurement_insert_y2008m01 AS
ON INSERT TO measurement WHERE
    ( logdate &gt;= DATE '2008-01-01' AND logdate &lt; DATE '2008-02-01' )
DO INSTEAD
    INSERT INTO measurement_y2008m01 VALUES (NEW.*);
</programlisting>

     A rule has significantly more overhead than a trigger, but the overhead
     is paid once per query rather than once per row, so this method might be
     advantageous for bulk-insert situations.  In most cases, however, the
     trigger method will offer better performance.
    </para>

    <para>
     Be aware that <command>COPY</> ignores rules.  If you want to
     use <command>COPY</> to insert data, you'll need to copy into the correct
     partition table rather than into the master.  <command>COPY</> does fire
     triggers, so you can use it normally if you use the trigger approach.
    </para>

    <para>
     Another disadvantage of the rule approach is that there is no simple
     way to force an error if the set of rules doesn't cover the insertion
     date; the data will silently go into the master table instead.
    </para>

    <para>
     Partitioning can also be arranged using a <literal>UNION ALL</literal>
     view, instead of table inheritance.  For example,

<programlisting>
CREATE VIEW measurement AS
          SELECT * FROM measurement_y2006m02
UNION ALL SELECT * FROM measurement_y2006m03
...
UNION ALL SELECT * FROM measurement_y2007m11
UNION ALL SELECT * FROM measurement_y2007m12
UNION ALL SELECT * FROM measurement_y2008m01;
</programlisting>

     However, the need to recreate the view adds an extra step to adding and
     dropping individual partitions of the data set.  In practice this
     method has little to recommend it compared to using inheritance.
    </para>

   </sect2>

   <sect2 id="ddl-partitioning-caveats">
   <title>Caveats</title>

   <para>
    The following caveats apply to partitioned tables:
   <itemizedlist>
    <listitem>
     <para>
      There is no automatic way to verify that all of the
      <literal>CHECK</literal> constraints are mutually
      exclusive.  It is safer to create code that generates
      partitions and creates and/or modifies associated objects than
      to write each by hand.
     </para>
    </listitem>

    <listitem>
     <para>
      The schemes shown here assume that the partition key column(s)
      of a row never change, or at least do not change enough to require
      it to move to another partition.  An <command>UPDATE</> that attempts
      to do that will fail because of the <literal>CHECK</> constraints.
      If you need to handle such cases, you can put suitable update triggers
      on the partition tables, but it makes management of the structure
      much more complicated.
     </para>
    </listitem>

    <listitem>
     <para>
      If you are using manual <command>VACUUM</command> or
      <command>ANALYZE</command> commands, don't forget that
      you need to run them on each partition individually. A command like:
<programlisting>
ANALYZE measurement;
</programlisting>
      will only process the master table.
     </para>
    </listitem>

   </itemizedlist>
   </para>

   <para>
    The following caveats apply to constraint exclusion:

   <itemizedlist>
    <listitem>
     <para>
      Constraint exclusion only works when the query's <literal>WHERE</>
      clause contains constants.  A parameterized query will not be
      optimized, since the planner cannot know which partitions the
      parameter value might select at run time.  For the same reason,
      <quote>stable</> functions such as <function>CURRENT_DATE</function>
      must be avoided.
     </para>
    </listitem>

    <listitem>
     <para>
      Keep the partitioning constraints simple, else the planner may not be
      able to prove that partitions don't need to be visited.  Use simple
      equality conditions for list partitioning, or simple
      range tests for range partitioning, as illustrated in the preceding
      examples.  A good rule of thumb is that partitioning constraints should
      contain only comparisons of the partitioning column(s) to constants
      using B-tree-indexable operators.
     </para>
    </listitem>

    <listitem>
     <para>
      All constraints on all partitions of the master table are examined
      during constraint exclusion, so large numbers of partitions are likely
      to increase query planning time considerably.  Partitioning using
      these techniques will work well with up to perhaps a hundred partitions;
      don't try to use many thousands of partitions.
     </para>
    </listitem>

   </itemizedlist>
   </para>
  </sect2>
 </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>
     Functions and operators
    </para>
   </listitem>

   <listitem>
    <para>
     Data types and domains
    </para>
   </listitem>

   <listitem>
    <para>
     Triggers and rewrite rules
    </para>
   </listitem>
  </itemizedlist>

  <para>
   Detailed information on
   these topics appears in <xref linkend="server-programming">.
  </para>
 </sect1>

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

  <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>

  <para>
   When you create complex database structures involving many tables
   with foreign key constraints, views, triggers, functions, etc. you
   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>
DROP TABLE products;

NOTICE:  constraint orders_product_no_fkey on table orders depends on table products
ERROR:  cannot drop table products because other objects depend on it
HINT:  Use DROP ... CASCADE to drop the dependent objects too.
</screen>
   The error message contains a useful hint: if you do not want to
   bother deleting all the dependent objects individually, you can run:
<screen>
DROP TABLE products CASCADE;
</screen>
   and all the dependent objects will be removed.  In this case, it
   doesn't remove the orders table, it only removes the foreign key
   constraint.  (If you want to check what <command>DROP ... CASCADE</> will do,
   run <command>DROP</> without <literal>CASCADE</> and read the <literal>NOTICE</> messages.)
  </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
   <literal>CASCADE</literal> to get the default behavior, which is to
   prevent the dropping of objects that other objects depend on.
  </para>

  <note>
   <para>
    According to the SQL standard, specifying either
    <literal>RESTRICT</literal> or <literal>CASCADE</literal> is
    required.  No database system actually enforces that rule, but
    whether the default behavior is <literal>RESTRICT</literal> or
    <literal>CASCADE</literal> varies across systems.
   </para>
  </note>

  <note>
   <para>
    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
    upgrade process.  All other dependency types will be properly
    created during an upgrade from a pre-7.3 database.
   </para>
  </note>
 </sect1>

</chapter>
@


1.96
log
@Make an editorial pass over the 9.0 release notes.

This is mostly about grammar, style, and presentation, though I did find
a few small factual errors.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.95 2010/08/20 13:59:45 tgl Exp $ -->
d547 5
d631 5
d845 10
d898 5
@


1.95
log
@Avoid saying "random" when randomness is not actually meant.
Per Thom Brown.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.94 2010/07/29 19:34:40 petere Exp $ -->
d849 1
a849 1
  <sect2>
@


1.94
log
@Fix indentation of verbatim block elements

Block elements with verbatim formatting (literallayout, programlisting,
screen, synopsis) should be aligned at column 0 independent of the surrounding
SGML, because whitespace is significant, and indenting them creates erratic
whitespace in the output.  The CSS stylesheets already take care of indenting
the output.

Assorted markup improvements to go along with it.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.93 2010/04/06 02:18:04 momjian Exp $ -->
d39 1
a39 1
   table.  When a table is read, the rows will appear in random order,
@


1.93
log
@Reword exclusion constriants to mention that the operator can return
false or null, per Tom.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.92 2010/04/03 07:22:53 petere Exp $ -->
d2523 1
a2523 1
 <programlisting>
d2548 1
a2548 1
 <programlisting>
@


1.93.2.1
log
@Fix indentation of verbatim block elements

Block elements with verbatim formatting (literallayout, programlisting,
screen, synopsis) should be aligned at column 0 independent of the surrounding
SGML, because whitespace is significant, and indenting them creates erratic
whitespace in the output.  The CSS stylesheets already take care of indenting
the output.

Assorted markup improvements to go along with it.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.93 2010/04/06 02:18:04 momjian Exp $ -->
d2523 1
a2523 1
<programlisting>
d2548 1
a2548 1
<programlisting>
@


1.93.2.2
log
@Make an editorial pass over the 9.0 release notes.

This is mostly about grammar, style, and presentation, though I did find
a few small factual errors.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.95 2010/08/20 13:59:45 tgl Exp $ -->
d39 1
a39 1
   table.  When a table is read, the rows will appear in an unspecified order,
d849 1
a849 1
  <sect2 id="ddl-constraints-exclusion">
@


1.93.2.3
log
@Explain automatic creation (or lack of it) of indexes for the various types
of constraints.

Kevin Grittner
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.93.2.2 2010/08/23 02:43:35 tgl Exp $ -->
a546 5
   <para>
    Adding a unique constraint will automatically create a unique btree
    index on the column or group of columns used in the constraint.
   </para>

a625 5
    Adding a primary key will automatically create a unique btree index
    on the column or group of columns used in the primary key.
   </para>

   <para>
a834 10
    Since a <command>DELETE</command> of a row from the referenced table
    or an <command>UPDATE</command> of a referenced column will require
    a scan of the referencing table for rows matching the old value, it
    is often a good idea to index the referencing columns.  Because this
    is not always needed, and there are many choices available on how
    to index, declaration of a foreign key constraint does not
    automatically create an index on the referencing columns.
   </para>

   <para>
a877 5

   <para>
    Adding an exclusion constraint will automatically create an index
    of the type specified in the constraint declaration.
   </para>
@


1.92
log
@Remove unnecessary xref endterm attributes and title ids

The endterm attribute is mainly useful when the toolchain does not support
automatic link target text generation for a particular situation.  In  the
past, this was required by the man page tools for all reference page links,
but that is no longer the case, and it now actually gets in the way of
proper automatic link text generation.  The only remaining use cases are
currently xrefs to refsects.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.91 2010/04/01 01:18:17 momjian Exp $ -->
d864 2
a865 1
    at least one of these operator comparisons will be false. The syntax is:
@


1.91
log
@Add contraint exclusion section to contraint docs.

Takahiro Itagaki
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.90 2010/02/24 15:54:31 momjian Exp $ -->
d81 1
a81 1
   linkend="sql-createtable" endterm="sql-createtable-title"> command.
d141 1
a141 1
   linkend="sql-droptable" endterm="sql-droptable-title"> command.
d845 1
a845 1
    <xref linkend="sql-createtable" endterm="sql-createtable-title">.
d1129 1
a1129 1
   <xref linkend="sql-altertable" endterm="sql-altertable-title">
d1396 1
a1396 1
   <xref linkend="sql-grant" endterm="sql-grant-title"> reference
d1409 1
a1409 1
    <xref linkend="sql-altertable" endterm="sql-altertable-title">
d1456 2
a1457 3
   privilege.  For details see the <xref linkend="sql-grant"
   endterm="sql-grant-title"> and <xref linkend="sql-revoke"
   endterm="sql-revoke-title"> reference pages.
d1538 2
a1539 2
    To create a schema, use the <xref linkend="sql-createschema"
    endterm="sql-createschema-title"> command.  Give the schema a name
d2111 1
a2111 1
   <xref linkend="sql-createtable" endterm="sql-createtable-title">
d2115 1
a2115 1
   variant of <xref linkend="sql-altertable" endterm="sql-altertable-title">.
d2147 1
a2147 1
   <xref linkend="sql-altertable" endterm="sql-altertable-title"> will
@


1.90
log
@Revert removal of pre-7.4 documenation behavior mentions.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.88 2009/10/23 05:24:52 petere Exp $ -->
d848 30
@


1.89
log
@Remove pre-7.4 documentaiton mentions, now that 8.0 is the oldest
supported release.
@
text
@d1798 12
a1809 6
    It is best to avoid table names beginning with <literal>pg_</>
    because they might someday conflict with system catalogs of the
    same name.  (<productname>PostgreSQL</productname> system catalog
    table names always start with <literal>pg_</>).  Of course, table
    names can always be schema-qualified to avoid conflicting with
    system catalog table names.
d3043 9
@


1.88
log
@When querying a table with child tables, do not check permissions on the
child tables.  This was found to be useless and confusing in virtually all
cases, and also contrary to the SQL standard.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.87 2009/06/17 21:58:49 tgl Exp $ -->
d1798 6
a1803 12
    In <productname>PostgreSQL</productname> versions before 7.3,
    table names beginning with <literal>pg_</> were reserved.  This is
    no longer true: you can 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
    future version defines a system table named the same as your
    table.  (With the default search path, an unqualified reference to
    your table name would then be resolved as the system table instead.)
    System tables will continue to follow the convention of having
    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.
a3036 9
  <note>
   <para>
    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
    upgrade process.  All other dependency types will be properly
    created during an upgrade from a pre-7.3 database.
   </para>
  </note>
@


1.87
log
@Proofreading for Bruce's recent round of documentation proofreading.
Most of those changes were good, but some not so good ...
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.86 2009/04/27 16:27:35 momjian Exp $ -->
d2127 9
d2140 1
a2140 10
   Table access permissions are not automatically inherited.  Therefore,
   a user attempting to access a parent table must either have permissions
   to do the same operation on all its child tables as well, or must use the
   <literal>ONLY</literal> notation.  When adding a new child table to
   an existing inheritance hierarchy, be careful to grant all the needed
   permissions on it.
  </para>

  <para>
   More generally, note that not all SQL commands are able to work on
@


1.86
log
@Proofreading adjustments for first two parts of documentation (Tutorial
and SQL).
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.85 2009/01/08 12:47:58 petere Exp $ -->
d560 2
a561 2
    columns.  This behavior conforms to the SQL standard, but there
    might be other SQL databases might not follow this rule.  So be
d1805 1
a1805 1
    your table name would be resolved as a system table instead.)
d2574 1
a2574 1
    IF ( NEW.logdate &gt;= DATE '2006-02-01' AND 
d2577 1
a2577 1
    ELSIF ( NEW.logdate &gt;= DATE '2006-03-01' AND 
d2581 1
a2581 1
    ELSIF ( NEW.logdate &gt;= DATE '2008-01-01' AND 
d2712 3
a2714 3
    partition and try to determine which partitions need not
    be scanned because they cannot not contain any rows meeting the query's
    <literal>WHERE</> clause.  When the planner can determine this, it
d2909 1
a2909 1
      Keep the partitioning constraints simple or else the planner may not be
@


1.85
log
@Add note that not all SQL commands support ONLY in the same way.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.84 2009/01/07 22:40:49 tgl Exp $ -->
d156 1
a156 1
   If you need to modify a table that already exists look into <xref
d209 1
a209 1
   is that a <type>timestamp</type> column can have a default of <literal>now()</>,
d377 2
a378 2
    Names can be assigned to table constraints in just the same way as
    for column constraints:
d553 2
a554 2
    In general, a unique constraint is violated when there are two or
    more rows in the table where the values of all of the
d560 2
a561 2
    columns.  This behavior conforms to the SQL standard, but we have
    heard that other SQL databases might not follow this rule.  So be
d860 1
a860 1
   columns, just know they exist.
d1040 2
a1041 2
    problem &mdash; note that the limit is on number of
    <acronym>SQL</acronym> commands, not number of rows processed.
d1058 1
a1058 1
   the requirements of the application change, then you can drop the
d1070 1
a1070 1
   You can
d1073 1
a1073 1
     <para>Add columns,</para>
d1076 1
a1076 1
     <para>Remove columns,</para>
d1079 1
a1079 1
     <para>Add constraints,</para>
d1082 1
a1082 1
     <para>Remove constraints,</para>
d1085 1
a1085 1
     <para>Change default values,</para>
d1088 1
a1088 1
     <para>Change column data types,</para>
d1091 1
a1091 1
     <para>Rename columns,</para>
d1094 1
a1094 1
     <para>Rename tables.</para>
d1113 1
a1113 1
    To add a column, use a command like this:
d1157 1
a1157 1
    To remove a column, use a command like this:
d1253 1
a1253 1
    To set a new default for a column, use a command like this:
d1282 1
a1282 1
    To convert a column to a different data type, use a command like this:
d1491 1
a1491 1
      they cannot collide with the names of other objects.
d1606 1
a1606 1
    schema names.  By default, such tables (and other objects) are
d1749 1
a1749 1
    own.  To allow that, the owner of the schema needs to grant the
d1805 1
a1805 1
    your table name would be resolved as the system table instead.)
d2027 1
a2027 1
WHERE c.altitude &gt; 500 and c.tableoid = p.oid;
d2133 1
a2133 1
   to do the operation on all its child tables as well, or must use the
d2200 1
a2200 1
   inheritance is useful for your problem.
d2377 1
a2377 1
        mistake is to set up range constraints like this:
d2427 1
a2427 1
     we want a table like this:
d2574 2
a2575 1
    IF ( NEW.logdate &gt;= DATE '2006-02-01' AND NEW.logdate &lt; DATE '2006-03-01' ) THEN
d2577 2
a2578 1
    ELSIF ( NEW.logdate &gt;= DATE '2006-03-01' AND NEW.logdate &lt; DATE '2006-04-01' ) THEN
d2581 2
a2582 1
    ELSIF ( NEW.logdate &gt;= DATE '2008-01-01' AND NEW.logdate &lt; DATE '2008-02-01' ) THEN
d2712 3
a2714 3
    partition and try to prove that the partition need not
    be scanned because it could not contain any rows meeting the query's
    <literal>WHERE</> clause.  When the planner can prove this, it
d2881 1
a2881 1
      you need to run them on each partition individually. A command like
d2909 1
a2909 1
      Keep the partitioning constraints simple, else the planner may not be
d2943 1
a2943 1
   you a list here so that you are aware of what is possible.
d2994 1
a2994 1
   will implicitly create a net of dependencies between the objects.
d3014 1
a3014 1
   bother deleting all the dependent objects individually, you can run
d3030 1
a3030 1
   prevent drops of objects that other objects depend on.
@


1.84
log
@Create a third option named "partition" for constraint_exclusion, and make it
the default.  This setting enables constraint exclusion checks only for
appendrel members (ie, inheritance children and UNION ALL arms), which are
the cases in which constraint exclusion is most likely to be useful.  Avoiding
the overhead for simple queries that are unlikely to benefit should bring
the cost down to the point where this is a reasonable default setting.
Per today's discussion.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.83 2008/09/08 00:47:40 tgl Exp $ -->
d2140 17
@


1.83
log
@Create a separate grantable privilege for TRUNCATE, rather than having it be
always owner-only.  The TRUNCATE privilege works identically to the DELETE
privilege so far as interactions with the rest of the system go.

Robert Haas
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.82 2008/05/09 23:32:03 tgl Exp $ -->
d2138 1
a2138 1
 
d2397 3
a2399 3
        configuration
        parameter is enabled in <filename>postgresql.conf</>.  Without
        this, queries will not be optimized as desired.
d2701 1
a2701 1
    with it off.  A typical default plan for this type of table setup is:
d2728 1
a2728 1
    reduced plan that will deliver the same answer:
d2754 11
d2831 1
a2831 1
 
@


1.82
log
@Change the rules for inherited CHECK constraints to be essentially the same
as those for inherited columns; that is, it's no longer allowed for a child
table to not have a check constraint matching one that exists on a parent.
This satisfies the principle of least surprise (rows selected from the parent
will always appear to meet its check constraints) and eliminates some
longstanding bogosity in pg_dump, which formerly had to guess about whether
check constraints were really inherited or not.

The implementation involves adding conislocal and coninhcount columns to
pg_constraint (paralleling attislocal and attinhcount in pg_attribute)
and refactoring various ALTER TABLE actions to be more like those for
columns.

Alex Hunsaker, Nikhil Sontakke, Tom Lane
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.81 2008/01/13 17:58:54 tgl Exp $ -->
d1359 1
a1359 1
   <literal>REFERENCES</>, <literal>TRIGGER</>,
@


1.81
log
@Add note pointing out that read-only commands no longer consume
command IDs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.80 2007/12/03 23:49:50 tgl Exp $ -->
d2110 2
a2111 1
   can columns of child tables be dropped or altered if they are inherited
d2121 1
a2121 1
   columns or constraints on parent tables is only possible when using
@


1.80
log
@Entity-ify a passel of & < > characters.  Per gripe from Devrim.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.79 2007/12/03 04:59:55 tgl Exp $ -->
d1037 1
a1037 2
    Command
    identifiers are also 32-bit quantities.  This creates a hard limit
d1042 3
@


1.79
log
@Improve partitioning example, per Itagaki Takahiro.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.78 2007/12/02 19:20:32 tgl Exp $ -->
d2315 1
a2315 1
     <orderedlist spacing=compact>
d2433 1
a2433 1
     <orderedlist spacing=compact>
@


1.78
log
@Improve the manual's discussion of partitioning.  Recommend using a
trigger instead of a rule to redirect insertions, use NEW.* notation
where appropriate, some other updates and adjustments.  David Fetter
and Tom Lane
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.77 2007/11/28 15:42:31 petere Exp $ -->
d2469 3
a2471 2
        We must add non-overlapping table constraints, so that our
        table creation script becomes:
d2554 1
a2554 1
    IF ( logdate &gt;= DATE '2006-02-01' AND logdate &lt; DATE '2006-03-01' ) THEN
d2556 1
a2556 1
    ELSIF ( logdate &gt;= DATE '2006-03-01' AND logdate &lt; DATE '2006-04-01' ) THEN
d2559 1
a2559 1
    ELSIF ( logdate &gt;= DATE '2008-01-01' AND logdate &lt; DATE '2008-02-01' ) THEN
d2580 9
@


1.77
log
@spell checker run
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.76 2007/06/20 23:11:38 tgl Exp $ -->
d2386 2
a2387 2
        Optionally, define a rule or trigger to redirect modifications
        of the master table to the appropriate partition.
d2446 2
a2447 2
CREATE TABLE measurement_y2004m02 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2004m03 ( ) INHERITS (measurement);
d2449 3
a2451 3
CREATE TABLE measurement_y2005m11 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2005m12 ( ) INHERITS (measurement);
CREATE TABLE measurement_y2006m01 ( ) INHERITS (measurement);
d2455 1
a2455 1
        but they inherit their definition from the
d2473 2
a2474 2
CREATE TABLE measurement_y2004m02 (
    CHECK ( logdate &gt;= DATE '2004-02-01' AND logdate &lt; DATE '2004-03-01' )
d2476 2
a2477 2
CREATE TABLE measurement_y2004m03 (
    CHECK ( logdate &gt;= DATE '2004-03-01' AND logdate &lt; DATE '2004-04-01' )
d2480 2
a2481 2
CREATE TABLE measurement_y2005m11 (
    CHECK ( logdate &gt;= DATE '2005-11-01' AND logdate &lt; DATE '2005-12-01' )
d2483 2
a2484 2
CREATE TABLE measurement_y2005m12 (
    CHECK ( logdate &gt;= DATE '2005-12-01' AND logdate &lt; DATE '2006-01-01' )
d2486 2
a2487 2
CREATE TABLE measurement_y2006m01 (
    CHECK ( logdate &gt;= DATE '2006-01-01' AND logdate &lt; DATE '2006-02-01' )
d2498 2
a2499 2
CREATE INDEX measurement_y2004m02_logdate ON measurement_y2004m02 (logdate);
CREATE INDEX measurement_y2004m03_logdate ON measurement_y2004m03 (logdate);
d2501 3
a2503 3
CREATE INDEX measurement_y2005m11_logdate ON measurement_y2005m11 (logdate);
CREATE INDEX measurement_y2005m12_logdate ON measurement_y2005m12 (logdate);
CREATE INDEX measurement_y2006m01_logdate ON measurement_y2006m01 (logdate);
d2512 4
d2517 15
a2531 3
        set up a very simple rule to insert data. We must
        redefine this each month so that it always points to the
        current partition:
d2534 3
a2536 7
CREATE OR REPLACE RULE measurement_current_partition AS
ON INSERT TO measurement
DO INSTEAD
    INSERT INTO measurement_y2006m01 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
d2539 6
d2547 1
a2547 1
        could do this with a more complex set of rules as shown below:
d2550 17
a2566 25
CREATE RULE measurement_insert_y2004m02 AS
ON INSERT TO measurement WHERE
    ( logdate &gt;= DATE '2004-02-01' AND logdate &lt; DATE '2004-03-01' )
DO INSTEAD
    INSERT INTO measurement_y2004m02 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
...
CREATE RULE measurement_insert_y2005m12 AS
ON INSERT TO measurement WHERE
    ( logdate &gt;= DATE '2005-12-01' AND logdate &lt; DATE '2006-01-01' )
DO INSTEAD
    INSERT INTO measurement_y2005m12 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
CREATE RULE measurement_insert_y2006m01 AS
ON INSERT TO measurement WHERE
    ( logdate &gt;= DATE '2006-01-01' AND logdate &lt; DATE '2006-02-01' )
DO INSTEAD
    INSERT INTO measurement_y2006m01 VALUES ( NEW.city_id,
                                              NEW.logdate,
                                              NEW.peaktemp,
                                              NEW.unitsales );
d2569 9
a2577 3
        Note that the <literal>WHERE</literal> clause in each rule
        exactly matches the <literal>CHECK</literal>
        constraint for its partition.
a2589 18
   <para>
    Partitioning can also be arranged using a <literal>UNION ALL</literal>
    view:

<programlisting>
CREATE VIEW measurement AS
          SELECT * FROM measurement_y2004m02
UNION ALL SELECT * FROM measurement_y2004m03
...
UNION ALL SELECT * FROM measurement_y2005m11
UNION ALL SELECT * FROM measurement_y2005m12
UNION ALL SELECT * FROM measurement_y2006m01;
</programlisting>

    However, the need to
    recreate the view adds an extra step to adding and dropping
    individual partitions of the data set.
   </para>
d2610 1
a2610 1
DROP TABLE measurement_y2003m02;
d2621 1
a2621 1
ALTER TABLE measurement_y2003m02 NO INHERIT measurement;
d2637 2
a2638 2
CREATE TABLE measurement_y2006m02 (
    CHECK ( logdate &gt;= DATE '2006-02-01' AND logdate &lt; DATE '2006-03-01' )
d2648 1
a2648 1
CREATE TABLE measurement_y2006m02
d2650 3
a2652 3
ALTER TABLE measurement_y2006m02 ADD CONSTRAINT y2006m02
   CHECK ( logdate &gt;= DATE '2006-02-01' AND logdate &lt; DATE '2006-03-01' );
\copy measurement_y2006m02 from 'measurement_y2006m02'
d2654 1
a2654 1
ALTER TABLE measurement_y2006m02 INHERIT measurement;
d2673 1
a2673 1
SELECT count(*) FROM measurement WHERE logdate &gt;= DATE '2006-01-01';
d2692 1
a2692 1
EXPLAIN SELECT count(*) FROM measurement WHERE logdate &gt;= DATE '2006-01-01';
d2699 5
a2703 5
               Filter: (logdate &gt;= '2006-01-01'::date)
         -&gt;  Seq Scan on measurement_y2004m02 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2006-01-01'::date)
         -&gt;  Seq Scan on measurement_y2004m03 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2006-01-01'::date)
d2705 4
a2708 4
         -&gt;  Seq Scan on measurement_y2005m12 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2006-01-01'::date)
         -&gt;  Seq Scan on measurement_y2006m01 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2006-01-01'::date)
d2719 1
a2719 1
EXPLAIN SELECT count(*) FROM measurement WHERE logdate &gt;= DATE '2006-01-01';
d2725 3
a2727 3
               Filter: (logdate &gt;= '2006-01-01'::date)
         -&gt;  Seq Scan on measurement_y2006m01 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate &gt;= '2006-01-01'::date)
d2740 63
d2813 1
a2813 1
      There is currently no way to verify that all of the
d2815 15
a2829 1
      exclusive. Care is required by the database designer.
d2835 7
a2841 8
      There is currently no simple way to specify that rows must not be
      inserted into the master table. A <literal>CHECK (false)</literal>
      constraint on the master table would be inherited by all child
      tables, so that cannot be used for this purpose.  One possibility is
      to set up an <literal>ON INSERT</> trigger on the master table that
      always raises an error.  (Alternatively, such a trigger could be
      used to redirect the data into the proper child table, instead of
      using a set of rules as suggested above.)
d2844 1
d2879 3
a2881 12
      to increase query planning time considerably.
     </para>
    </listitem>

    <listitem>
     <para>
      Don't forget that you still need to run <command>ANALYZE</command>
      on each partition individually. A command like:
<programlisting>
ANALYZE measurement;
</programlisting>
      will only process the master table.
@


1.76
log
@Add a caveat pointing out that constraint exclusion doesn't work with
constraints the planner is unable to disprove, hence simple btree-compatible
conditions should be used.  We've seen people try to get cute with stuff
like date_part(something) = something at least twice now.  Even if we
wanted to try to teach predtest.c about the properties of date_part,
most of the useful variants aren't immutable so nothing could be proved.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.75 2007/05/15 19:43:50 neilc Exp $ -->
d2796 1
a2796 1
      using btree-indexable operators.
@


1.75
log
@Fix a bunch of bad grammar in the docs: "<link>, which see for more
information" is un-good English.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.74 2007/05/03 15:05:56 neilc Exp $ -->
d2781 1
a2781 1
      optimized, since the planner cannot know what partitions the
d2790 15
a2804 3
      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.
@


1.74
log
@Fix some typos in the documentation. Patch from Brian Gough. Backport
the relevant fixes to 8.2 as well.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.73 2007/02/01 00:28:16 momjian Exp $ -->
d1098 2
a1099 1
   command, which see for details beyond those given here.
@


1.73
log
@Consistenly use colons before '<programlisting>' blocks, where
appropriate.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.72 2007/01/31 20:56:16 momjian Exp $ -->
d2236 1
a2236 1
      When queries or updates access a large percentage of a a single
d2559 1
a2559 1
        exactly matches the the <literal>CHECK</literal>
@


1.72
log
@Update documentation on may/can/might:

Standard English uses "may", "can", and "might" in different ways:

        may - permission, "You may borrow my rake."

        can - ability, "I can lift that log."

        might - possibility, "It might rain today."

Unfortunately, in conversational English, their use is often mixed, as
in, "You may use this variable to do X", when in fact, "can" is a better
choice.  Similarly, "It may crash" is better stated, "It might crash".

Also update two error messages mentioned in the documenation to match.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.71 2006/12/30 20:31:11 momjian Exp $ -->
d213 1
a213 1
   something like
d322 1
a322 1
    ensure that the discounted price is lower than the regular price.
d351 1
a351 1
    also be written as
d363 1
a363 1
    or even
d466 1
a466 1
    script file.  For example, you could start with
d500 1
a500 1
    table.  The syntax is
d508 1
a508 1
    when written as a column constraint, and
d694 1
a694 1
    You can also shorten the above command to
d784 1
a784 1
    removes an order, the order items are removed as well.
d1233 1
a1233 1
    constraints. To drop a not null constraint use
d1259 1
a1259 1
    To remove any default value, use
d1386 1
a1386 1
   update the table can be granted with
d1548 1
a1548 1
    So to create a table in the new schema, use
d1563 1
a1563 1
    dropped), use
d1567 1
a1567 1
    To drop a schema including all contained objects, use
d1609 1
a1609 1
    and
d1689 1
a1689 1
    To put our new schema in the path, we use
d1704 1
a1704 1
    We could also have written
d1727 1
a1727 1
    This is needed to avoid syntactic ambiguity.  An example is
d1949 1
a1949 1
   500ft:
d1971 1
a1971 1
   are not state capitals and are situated at an altitude over 500ft:
d2514 1
a2514 1
        current partition.
d2528 1
a2528 1
        could do this with a more complex set of rules as shown below.
d2635 1
a2635 1
     were created above. 
d2646 1
a2646 1
     transformed prior to it appearing in the partitioned table.
d2798 1
a2798 1
      on each partition individually. A command like
@


1.71
log
@Clarify wording on when ctid is modified by VACUUM FULL.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.70 2006/12/28 20:02:38 tgl Exp $ -->
d206 1
a206 1
   The default value may be an expression, which will be
d209 1
a209 1
   is that a <type>timestamp</type> column may have a default of <literal>now()</>,
d460 1
a460 1
    simply selects the default behavior that the column may be null.
d561 1
a561 1
    heard that other SQL databases may not follow this rule.  So be
d1007 1
a1007 1
       may suffer.)
d1292 1
a1292 1
    that involve the column.  But these conversions may fail, or may
d1460 1
a1460 1
   example, both <literal>schema1</> and <literal>myschema</> may
d1462 1
a1462 1
   schemas are not rigidly separated: a user may access objects in any
d1589 1
a1589 1
    system purposes and may not be created by users.
d1749 1
a1749 1
    may need to be granted, as appropriate for the object.
d1789 1
a1789 1
    findable.  However, you may explicitly place
d1797 1
a1797 1
    no longer true: you may create such a table name if you wish, in
d1996 1
a1996 1
   In some cases you may wish to know which table a particular row
d2245 1
a2245 1
      Bulk loads and deletes may be accomplished by adding or removing
d2569 1
a2569 1
     creating a new partition each month, so it may be wise to write a
d2627 1
a2627 1
     similar tools. It can also be a useful time to aggregate data
@


1.70
log
@Remove caveat about avoiding cross-type operators in constraints intended
for use with constraint exclusion.  We can prove those cases now...
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.69 2006/11/28 01:09:01 tgl Exp $ -->
d977 1
a977 1
      <structfield>ctid</structfield> will change each time it is
@


1.69
log
@Fix inheritance description to note that not-null constraints are
inherited, per Taiki Yamaguchi.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.68 2006/11/21 03:44:55 momjian Exp $ -->
a2788 23
      Avoid cross-data type comparisons in the <literal>CHECK</>
      constraints, as the planner will currently fail to prove such
      conditions false.  For example, the following constraint
      will work if <varname>x</varname> is an <type>integer</type>
      column, but not if <varname>x</varname> is a
      <type>bigint</type>:
<programlisting>
CHECK ( x = 1 )
</programlisting>
      For a <type>bigint</type> column we must use a constraint like:
<programlisting>
CHECK ( x = 1::bigint )
</programlisting>
      The problem is not limited to the <type>bigint</type> data type
      &mdash; it can occur whenever the default data type of the
      constant does not match the data type of the column to which it
      is being compared.  Cross-data type comparisons in the supplied
      queries are usually OK, just not in the <literal>CHECK</> conditions.
     </para>
    </listitem>

    <listitem>
     <para>
@


1.69.2.1
log
@Fix some typos in the documentation. Patch from Brian Gough. Backport
the relevant fixes to 8.2 as well.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.69 2006/11/28 01:09:01 tgl Exp $ -->
d2236 1
a2236 1
      When queries or updates access a large percentage of a single
d2559 1
a2559 1
        exactly matches the <literal>CHECK</literal>
@


1.69.2.2
log
@Fix a bunch of bad grammar in the docs: "<link>, which see for more
information" is un-good English.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.69.2.1 2007/05/03 15:06:13 neilc Exp $ -->
d1098 1
a1098 2
   command, whose reference page contains details beyond those given
   here.
@


1.68
log
@I noticed that the Partitioning section of the docs has *two* sections
of caveats in different places, but close together. One called caveats,
one not. That looks like it just led to somebody not reading some
appropriate caveats in the second group of caveats (on -admin).

Simon Riggs
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.67 2006/10/23 18:10:30 petere Exp $ -->
d2058 3
a2060 4
   Check constraints can be defined on tables within an inheritance
   hierarchy. All check constraints on a parent table are
   automatically inherited by all of its children.  Other types of
   constraints are not inherited, however.
d2072 2
a2073 1
   any one of the column definitions it came from.
@


1.67
log
@Spellchecking and such
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.66 2006/10/22 03:03:40 tgl Exp $ -->
a2659 30
   <sect2 id="ddl-partitioning-caveats">
   <title>Caveats</title>
 
   <para>
    The following caveats apply to partitioned tables:
   <itemizedlist>
    <listitem>
     <para>
      There is currently no way to verify 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 simple way to specify that rows must not be
      inserted into the master table. A <literal>CHECK (false)</literal>
      constraint on the master table would be inherited by all child
      tables, so that cannot be used for this purpose.  One possibility is
      to set up an <literal>ON INSERT</> trigger on the master table that
      always raises an error.  (Alternatively, such a trigger could be
      used to redirect the data into the proper child table, instead of
      using a set of rules as suggested above.)
     </para>
    </listitem>
   </itemizedlist>
   </para>
   </sect2>

d2741 30
d2773 1
a2773 1
    The following caveats apply:
@


1.66
log
@Some desultory copy-editing.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.65 2006/10/16 17:28:03 momjian Exp $ -->
d2589 1
a2589 1
    individual partitions of the dataset.
d2781 1
a2781 1
      parameter value might select at runtime.  For the same reason,
d2789 1
a2789 1
      Avoid cross-datatype comparisons in the <literal>CHECK</>
d2805 1
a2805 1
      is being compared.  Cross-datatype comparisons in the supplied
@


1.65
log
@Remove use of '<' and '>' in SGML, use '&' escapes.

Update find_gt_lt to allow grep parameters to be passed into it.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.64 2006/10/13 21:43:17 tgl Exp $ -->
d149 4
a152 2
   try to drop each table before creating it, ignoring the error
   messages.
d179 1
a179 1
   created and no values are specified for some of the columns, the
d250 1
a250 1
   information, there should only be one row for each product number.
a404 5

   <para>
    Check constraints can be useful for enhancing the performance of
    partitioned tables.  For details see <xref linkend="ddl-partitioning">.
   </para>
d461 1
a461 1
    The <literal>NULL</literal> constraint is not defined in the SQL
d556 1
a556 1
    However, null values are not considered equal in this
d626 4
a629 2
    A table can have at most one primary key (while it can have many
    unique and not-null constraints).  Relational database theory
d880 1
a880 1
      configuration variable was set. This column is of type
d1019 1
a1019 1
       The tables in question should be created using <literal>WITH
d1098 1
a1098 1
   command.
d1131 12
d1390 5
a1394 4
   To grant a privilege to a group, use this syntax:
<programlisting>
GRANT SELECT ON accounts TO GROUP staff;
</programlisting>
d1396 4
a1399 3
   be used to grant a privilege to every user on the system. Writing
   <literal>ALL</literal> in place of a specific privilege grants all
   privileges that are relevant for the object type.
d1906 1
a1906 1
   <productname>PostgreSQL</productname> implements table inheritance
d2080 1
a2080 5
   statement. However the related statement <command>CREATE TABLE AS</command>
   does not allow inheritance to be specified. 
  </para>

  <para>
a2305 2

    Hash partitioning is not currently supported.
@


1.64
log
@Code and docs review for ALTER TABLE INHERIT/NO INHERIT patch.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.63 2006/09/20 21:30:20 tgl Exp $ -->
d2345 1
a2345 1
CHECK ( outletID >= 100 AND outletID < 200 )
@


1.63
log
@Fix bogus markup.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.62 2006/09/20 01:20:38 neilc Exp $ -->
d2064 5
a2068 5
   Table inheritance can be defined using the <xref linkend="sql-createtable"
   endterm="sql-createtable-title"> statement using the
   <command>INHERITS</command> keyword. However the related statement
   <command>CREATE TABLE AS</command> does not allow inheritance to be
   specified. 
d2072 6
a2077 6
   Alternatively a table which is already defined in a compatible way can have
   a new parent added with <xref linkend="sql-altertable"
   endterm="sql-altertable-title"> using the <command>INHERIT</command>
   subform. To do this the new child table must already include columns with
   the same name and type as the columns of the parent. It must also include
   check constraints with the same name and check expression as those of the
d2079 4
a2082 2
   <command>ALTER TABLE</command> using the <command>NO INHERIT</command>
   subform.
d2086 2
a2087 2
   One convenient way to create a compatible table to be a new child
   is specify the <command>LIKE</command> clause in <command>CREATE
d2089 5
a2093 8
   the source table. If there are any <command>CHECK</command>
   constraints defined on the parent table, the <command>INCLUDING
   CONSTRAINTS</command> option to <command>LIKE</command> may be
   useful, as the new child must have constraints matching the parent
   to be considered compatible. Alternatively a compatible table can
   be created by first creating a new child using <command>CREATE
   TABLE</command> then removing the inheritance link with
   <command>ALTER TABLE</command>.
d2097 3
a2099 2
   A parent table cannot be dropped while any
   of its children remain. If you wish to remove a table and all of its
d2101 1
a2101 2
   <literal>CASCADE</literal> option. Neither can columns of child tables be
   dropped or altered if they are inherited from any parent tables.
d2106 6
a2111 4
   propagate any changes in column data definitions and check constraints down
   the inheritance hierarchy. <command>ALTER TABLE</command> follows the same
   rules for duplicate column merging and rejection that apply during
   <command>CREATE TABLE</command>. 
a2165 10

    <listitem>
     <para>
      If a table is ever removed from the inheritance structure using
      <command>ALTER TABLE</command> then all its columns will be marked as
      being locally defined. This means <command>DROP COLUMN</command> on the
      parent table will never cascade to drop those columns on the child
      table. They must be dropped manually.
     </para>
    </listitem>
d2216 6
a2221 12
      Query performance can be improved when partition constraints can be
      combined with local indexes to reduce the number of records that need to
      be accessed for a query. Whereas the alternative, adding those columns
      to every index, increases space usage which can erase any
      performance gain.
     </para>

     <para>
      When most of the heavily accessed area of the table is in a single
      partition or a small number of partitions. That partition and its
      indexes are more likely to fit within memory than the index of the
      entire table.
d2228 3
a2230 3
      partition performance can be improved dramatically by taking advantage
      of sequential disk access of a single partition instead of using an
      index and random access reads across the whole table.
d2236 5
a2240 5
      Bulk loads and deletes may be accomplished by simply removing or adding
      one of the partitions. <command>ALTER TABLE</> is far faster than a bulk
      and takes the same amount of time regardless of the amount of data being
      added or removed. It also entirely avoids the <command>VACUUM</command>
      overhead caused by a bulk <command>delete</>.
d2565 19
d2596 2
a2597 2
     manipulating the partition structure, rather than moving large
     amounts of data around physically.
d2601 1
a2601 1
     The simplest option for removing old data is to simply drop the partition
d2604 1
a2604 1
DROP TABLE measurement_y2003mm02;
d2615 1
a2615 1
ALTER TABLE measurement_y2003mm02 NO INHERIT measurement;
d2618 1
a2618 1
     it is dropped. For example, this is often a useful time to backup
d2642 6
a2647 4
CREATE TABLE measurement_y2006m02 (LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
\COPY measurement_y2006m02 FROM 'measurement_y2006m02'
UPDATE ... ;
ALTER TABLE measurement_y2006m02 ADD CONSTRAINT y2006m02 CHECK ( logdate &gt;= DATE '2006-02-01' AND logdate &lt; DATE '2006-03-01' );
a2678 11

    <listitem>
     <para>
      When using the <literal>LIKE</> option above to create new
      partitions, <literal>CHECK</> constraints are not copied from
      the parent. If there are any <literal>CHECK</> constraints
      defined for the parent, they must be manually created in new
      partitions before <command>ALTER TABLE</command> will allow them
      to be added.
     </para>
    </listitem>
a2680 19

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

<programlisting>
CREATE VIEW measurement AS
          SELECT * FROM measurement_y2004m02
UNION ALL SELECT * FROM measurement_y2004m03
...
UNION ALL SELECT * FROM measurement_y2005m11
UNION ALL SELECT * FROM measurement_y2005m12
UNION ALL SELECT * FROM measurement_y2006m01;
</programlisting>

    However, the need to
    recreate the view adds an extra step to adding and dropping
    individual partitions of the dataset.
   </para>
@


1.62
log
@Improvements to the partitioning documentation. Original patch from Greg
Stark, additional fixes and editorialization by Neil Conway. Greg's patch
description:

    Some more doc patches for partitioned tables. In particular replace
    the caveat that INCLUDING CONSTRAINTS doesn't exist and replace it
    with documentation of, well, INCLUDING CONSTRAINTS.

    Also, there was an instance of "LIKE WITH DEFAULTS" which is
    actually spelled "LIKE INCLUDING DEFAULTS".
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.61 2006/09/05 21:08:33 tgl Exp $ -->
d2481 1
a2481 1
    CHECK ( logdate >= DATE '2004-02-01' AND logdate < DATE '2004-03-01' )
d2484 1
a2484 1
    CHECK ( logdate >= DATE '2004-03-01' AND logdate < DATE '2004-04-01' )
d2488 1
a2488 1
    CHECK ( logdate >= DATE '2005-11-01' AND logdate < DATE '2005-12-01' )
d2491 1
a2491 1
    CHECK ( logdate >= DATE '2005-12-01' AND logdate < DATE '2006-01-01' )
d2494 1
a2494 1
    CHECK ( logdate >= DATE '2006-01-01' AND logdate < DATE '2006-02-01' )
d2541 1
a2541 1
    ( logdate >= DATE '2004-02-01' AND logdate < DATE '2004-03-01' )
d2550 1
a2550 1
    ( logdate >= DATE '2005-12-01' AND logdate < DATE '2006-01-01' )
d2558 1
a2558 1
    ( logdate >= DATE '2006-01-01' AND logdate < DATE '2006-02-01' )
d2580 1
d2628 1
a2628 1
    CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
d2641 1
a2641 1
ALTER TABLE measurement_y2006m02 ADD CONSTRAINT y2006m02 CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' );
d2721 1
a2721 1
SELECT count(*) FROM measurement WHERE logdate >= DATE '2006-01-01';
d2740 1
a2740 1
EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2006-01-01';
d2745 7
a2751 7
   ->  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_y2004m02 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
         ->  Seq Scan on measurement_y2004m03 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
d2753 4
a2756 4
         ->  Seq Scan on measurement_y2005m12 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
         ->  Seq Scan on measurement_y2006m01 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
d2767 1
a2767 1
EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2006-01-01';
d2771 5
a2775 5
   ->  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_y2006m01 measurement  (cost=0.00..30.38 rows=543 width=0)
               Filter: (logdate >= '2006-01-01'::date)
@


1.61
log
@Get rid of the separate RULE privilege for tables: now only a table's owner
can create or modify rules for the table.  Do setRuleCheckAsUser() while
loading rules into the relcache, rather than when defining a rule.  This
ensures that permission checks for tables referenced in a rule are done with
respect to the current owner of the rule's table, whereas formerly ALTER TABLE
OWNER would fail to update the permission checking for associated rules.
Removal of separate RULE privilege is needed to prevent various scenarios
in which a grantee of RULE privilege could effectively have any privilege
of the table owner.  For backwards compatibility, GRANT/REVOKE RULE is still
accepted, but it doesn't do anything.  Per discussion here:
http://archives.postgresql.org/pgsql-hackers/2006-04/msg01138.php
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.60 2006/07/14 00:13:05 neilc Exp $ -->
d2084 8
a2091 4
   One convenient way to create a compatible table to be a new child is using
   the <command>LIKE</command> option of <command>CREATE TABLE</command>. This
   creates a table with the same columns with the same type (however note the
   caveat below regarding constraints). Alternatively a compatible table can
d2093 2
a2094 2
   TABLE</command> then removing the inheritance link with <command>ALTER
   TABLE</command>.
a2167 13
      There is no convenient way to define a table compatible with a specific
      parent including columns and constraints. The <command>LIKE</command>
      option for <command>CREATE TABLE</command> does not copy constraints
      which makes the tables it creates ineligible for being added using
      <command>ALTER TABLE</command>. Matching check constraints must be added 
      manually or the table must be created as a child immediately, then if
      needed removed from the inheritance structure temporarily to be added
      again later.
     </para>
    </listitem>

    <listitem>
     <para>
d2571 12
d2584 10
a2593 4
      <listitem>
       <para>
        When the time comes to archive and remove the old data we first remove
        it from the production table using:
d2595 3
d2599 1
a2599 1
ALTER TABLE measurement_y2003mm02 NO INHERIT measurement
d2601 3
d2605 14
a2618 8
        Then we can perform any sort of data modification necessary prior to
        archiving without impacting the data viewed by the production system.
        This could include, for example, deleting or compressing out redundant
        data.
       </para>
      </listitem>
      <listitem>
      <para>
d2620 4
a2623 7
       Similarly we can a new partition to handle new data. We can either
       create an empty partition as the original partitions were created
       above, or for some applications it's necessary to bulk load and clean
       data for the new partition. If that operation involves multiple steps
       by different processes it can be helpful to work with it in a fresh
       table outside of the master partitioned table until it's ready to be
       loaded:
d2626 3
a2628 5
CREATE TABLE measurement_y2006m02 (LIKE measurement WITH DEFAULTS);
\COPY measurement_y2006m02 FROM 'measurement_y2006m02'
UPDATE ...
ALTER TABLE measurement_y2006m02 ADD CONSTRAINT y2006m02 CHECK ( logdate &gt;= DATE '2006-02-01' AND logdate &lt DATE '2006-03-01' );
ALTER TABLE measurement_y2006m02 INHERIT MEASUREMENT;
d2631 4
a2634 2
      </para>
      </listitem>
d2636 7
a2642 8
     </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.
d2644 1
d2646 3
d2650 1
a2650 1
    The following caveats apply:
d2675 6
a2680 5
      When using the <literal>LIKE</> option above to create new partitions
      check constraints are not copied from the parent. If there are any check
      constraints defined for the parent they must be manually created in new
      partitions before <command>ALTER TABLE</command> will allow them to be
      added.
@


1.60
log
@Minor doc tweak: replace a "--" with "&mdash;".
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.59 2006/07/03 16:43:14 tgl Exp $ -->
d1345 1
a1345 1
   <literal>RULE</>, <literal>REFERENCES</>, <literal>TRIGGER</>,
@


1.59
log
@Fix broken markup.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.58 2006/07/02 01:58:36 momjian Exp $ -->
d37 1
a37 1
   variable -- it reflects how much data is stored at a given moment.
@


1.58
log
@ALTER TABLE ... ADD/DROPS INHERIT (actually INHERIT / NO INHERIT)

Open items:

There were a few tangentially related issues that have come up that I think
are TODOs. I'm likely to tackle one or two of these next so I'm interested in
hearing feedback on them as well.

. Constraints currently do not know anything about inheritance. Tom suggested
  adding a coninhcount and conislocal like attributes have to track their
  inheritance status.

. Foreign key constraints currently do not get copied to new children (and
  therefore my code doesn't verify them). I don't think it would be hard to
  add them and treat them like CHECK constraints.

. No constraints at all are copied to tables defined with LIKE. That makes it
  hard to use LIKE to define new partitions. The standard defines LIKE and
  specifically says it does not copy constraints. But the standard already has
  an option called INCLUDING DEFAULTS; we could always define a non-standard
  extension LIKE table INCLUDING CONSTRAINTS that gives the user the option to
  request a copy including constraints.

. Personally, I think the whole attislocal thing is bunk. The decision about
  whether to drop a column from children tables or not is something that
  should be up to the user and trying to DWIM based on whether there was ever
  a local definition or the column was acquired purely through inheritance is
  hardly ever going to match up with user expectations.

. And of course there's the whole unique and primary key constraint issue. I
  think to get any traction at all on this you have a prerequisite of a real
  partitioned table implementation where the system knows what the partition
  key is so it can recognize when it's a leading part of an index key.

Greg Stark
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.57 2006/04/30 21:15:32 tgl Exp $ -->
d2081 1
d2090 2
a2091 1
   TABLE</command>. </para>
d2239 1
a2239 1
     <para>
@


1.57
log
@Code review for GRANT CONNECT patch.  Spell the privilege as CONNECT not
CONNECTION, fix a number of places that were missed (eg pg_dump support),
avoid executing an extra search of pg_database during startup.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.56 2006/04/23 03:39:50 momjian Exp $ -->
d2064 33
a2096 11
   Table inheritance can currently only be defined using the <xref
   linkend="sql-createtable" endterm="sql-createtable-title">
   statement.  The related statement <command>CREATE TABLE AS</command> 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 by dropping
   the table completely.  A parent table cannot be dropped
   while any of its children remain. If you wish to remove a table and
   all of its descendants, one easy way is to drop the parent table with
   the <literal>CASCADE</literal> option.
d2101 4
a2104 6
   propagate any changes in column data definitions and 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>.
d2159 23
d2232 12
a2243 2
      Query performance can be improved dramatically for certain kinds
      of queries.
d2249 4
a2252 5
      Update performance can be improved too, since each piece of the table
      has indexes smaller than an index on the entire data set would be.
      When an index no longer fits easily
      in memory, both read and write operations on the index take
      progressively more disk accesses.
d2258 5
a2262 4
      Bulk deletes may be accomplished by simply removing one of the
      partitions, if that requirement is planned into the partitioning design.
      <command>DROP TABLE</> is far faster than a bulk <command>DELETE</>,
      to say nothing of the ensuing <command>VACUUM</> overhead.
d2460 2
a2461 2
CREATE TABLE measurement_yy04mm02 ( ) INHERITS (measurement);
CREATE TABLE measurement_yy04mm03 ( ) INHERITS (measurement);
d2463 3
a2465 3
CREATE TABLE measurement_yy05mm11 ( ) INHERITS (measurement);
CREATE TABLE measurement_yy05mm12 ( ) INHERITS (measurement);
CREATE TABLE measurement_yy06mm01 ( ) INHERITS (measurement);
d2487 1
a2487 1
CREATE TABLE measurement_yy04mm02 (
d2490 1
a2490 1
CREATE TABLE measurement_yy04mm03 (
d2494 1
a2494 1
CREATE TABLE measurement_yy05mm11 (
d2497 1
a2497 1
CREATE TABLE measurement_yy05mm12 (
d2500 1
a2500 1
CREATE TABLE measurement_yy06mm01 (
d2512 2
a2513 2
CREATE INDEX measurement_yy04mm02_logdate ON measurement_yy04mm02 (logdate);
CREATE INDEX measurement_yy04mm03_logdate ON measurement_yy04mm03 (logdate);
d2515 3
a2517 3
CREATE INDEX measurement_yy05mm11_logdate ON measurement_yy05mm11 (logdate);
CREATE INDEX measurement_yy05mm12_logdate ON measurement_yy05mm12 (logdate);
CREATE INDEX measurement_yy06mm01_logdate ON measurement_yy06mm01 (logdate);
d2535 1
a2535 1
    INSERT INTO measurement_yy06mm01 VALUES ( NEW.city_id,
d2546 1
a2546 1
CREATE RULE measurement_insert_yy04mm02 AS
d2550 1
a2550 1
    INSERT INTO measurement_yy04mm02 VALUES ( NEW.city_id,
d2555 1
a2555 1
CREATE RULE measurement_insert_yy05mm12 AS
d2559 1
a2559 1
    INSERT INTO measurement_yy05mm12 VALUES ( NEW.city_id,
d2563 1
a2563 1
CREATE RULE measurement_insert_yy06mm01 AS
d2567 1
a2567 1
    INSERT INTO measurement_yy06mm01 VALUES ( NEW.city_id,
d2578 38
d2649 10
d2668 2
a2669 2
          SELECT * FROM measurement_yy04mm02
UNION ALL SELECT * FROM measurement_yy04mm03
d2671 3
a2673 3
UNION ALL SELECT * FROM measurement_yy05mm11
UNION ALL SELECT * FROM measurement_yy05mm12
UNION ALL SELECT * FROM measurement_yy06mm01;
d2723 1
a2723 1
         ->  Seq Scan on measurement_yy04mm02 measurement  (cost=0.00..30.38 rows=543 width=0)
d2725 1
a2725 1
         ->  Seq Scan on measurement_yy04mm03 measurement  (cost=0.00..30.38 rows=543 width=0)
d2728 1
a2728 1
         ->  Seq Scan on measurement_yy05mm12 measurement  (cost=0.00..30.38 rows=543 width=0)
d2730 1
a2730 1
         ->  Seq Scan on measurement_yy06mm01 measurement  (cost=0.00..30.38 rows=543 width=0)
d2749 1
a2749 1
         ->  Seq Scan on measurement_yy06mm01 measurement  (cost=0.00..30.38 rows=543 width=0)
@


1.56
log
@Removes or minimizes some documentation mentions of backward
compatibility for release 7.2 and earlier.  I have not altered any
mentions of release 7.3 or later.  The release notes were not modified,
so the changes are still documented, just not in the main docs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.55 2006/02/18 23:14:45 neilc Exp $ -->
d1346 3
a1348 2
   <literal>CREATE</>, <literal>TEMPORARY</>, <literal>EXECUTE</>, and
   <literal>USAGE</>.  The privileges applicable to a particular
@


1.55
log
@Minor SGML style police work.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.54 2006/02/12 19:11:00 momjian Exp $ -->
d2148 1
a2148 1
     In previous versions of <productname>PostgreSQL</productname>, the
d2150 3
a2152 13
     found to be error prone and is also in violation of the SQL
     standard. Under the old syntax, to include the child 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 <literal>ONLY</literal>.  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
@


1.54
log
@Revert patch becaues of locking concerns:

Allow ALTER TABLE ... ALTER CONSTRAINT ... RENAME

Joachim Wieland
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.53 2006/02/11 22:17:18 momjian Exp $ -->
d80 5
a84 4
   To create a table, you use the aptly named <command>CREATE
   TABLE</command> command.  In this command you specify at least a
   name for the new table, the names of the columns and the data type
   of each column.  For example:
d140 3
a142 2
   If you no longer need a table, you can remove it using the
   <command>DROP TABLE</command> command.  For example:
d1492 3
a1494 3
    To create a schema, use the command <command>CREATE
    SCHEMA</command>.  Give the schema a name of your choice.  For
    example:
@


1.53
log
@Allow ALTER TABLE ... ALTER CONSTRAINT ... RENAME

Joachim Wieland
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.52 2006/02/04 23:03:19 tgl Exp $ -->
a545 4
   Since <productname>PostgreSQL</productname> implements a UNIQUE constraint by
   means of an index, the above command will also create an index with the same
   name as the constraint. If you later on change the name of one of those, the
   name of the corresponding object will be changed automatically as well.
@


1.52
log
@Fix constraint exclusion to work in inherited UPDATE/DELETE queries
... in fact, it will be applied now in any query whatsoever.  I'm still
a bit concerned about the cycles that might be expended in failed proof
attempts, but given that CE is turned off by default, it's the user's
choice whether to expend those cycles or not.  (Possibly we should
change the simple bool constraint_exclusion parameter to something
more fine-grained?)
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.51 2005/12/23 00:38:03 momjian Exp $ -->
d546 4
@


1.51
log
@Add quotes around search_path "$user" so that SHOW output can be used in
SET.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.50 2005/11/04 23:53:18 tgl Exp $ -->
d2182 1
a2182 1
    partitioning. This section describes why and how you can implement
d2240 1
a2240 1
    attempting to implement partitioning.
d2582 1
a2582 2
    However, constraint exclusion is currently not supported for
    partitioned tables defined in this manner.  Also, the need to
d2681 1
a2681 2
      must be avoided.  Joining the partition key to a column of another
      table will not be optimized, either.
a2709 7
      <command>UPDATE</command> and <command>DELETE</command> commands
      against the master table do not currently perform constraint exclusion.
     </para>
    </listitem>

    <listitem>
     <para>
@


1.50
log
@Editorial review for partitioning/constraint exclusion documentation.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.49 2005/11/04 23:13:59 petere Exp $ -->
d1653 1
a1653 1
 $user,public
@


1.49
log
@Spellchecking run, final cleanups
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.48 2005/11/04 02:56:30 tgl Exp $ -->
d15 1
a15 1
  such as views, functions, and triggers.
d402 3
a404 5
    <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">.
d896 2
a897 2
      hierarchies, since without it, it's difficult to tell which
      individual table a row came from.  The
d1045 2
a1046 2
 <sect1 id="ddl-inherit">
  <title>Inheritance</title>
d1048 4
a1051 3
   <indexterm>
    <primary>not-null constraint</primary>
   </indexterm>
d1053 12
a1064 4
   <indexterm>
    <primary>constraint</primary>
    <secondary>NOT NULL</secondary>
   </indexterm>
d1067 31
a1097 4
   <productname>PostgreSQL</productname> implements table inheritance
   which can be a useful tool for database designers.  SQL:1999 and
   later define a type inheritance feature, which differs in many
   respects from the features described here.
d1100 7
a1106 11
  <para>
   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>:
d1108 2
d1111 5
a1115 5
CREATE TABLE cities (
    name            text,
    population      float,
    altitude        int     -- in feet
);
d1117 5
a1121 3
CREATE TABLE capitals (
    state           char(2)
) INHERITS (cities);
d1123 8
d1132 2
a1133 5
   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.
  </para>
d1135 4
a1138 7
  <para>
   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:
d1140 11
d1152 1
a1152 3
SELECT name, altitude
    FROM cities
    WHERE altitude &gt; 500;
d1154 7
d1162 4
a1165 1
   which returns:
d1167 2
d1170 3
a1172 5
   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
 Madison   |      845
d1174 2
a1175 6
  </para>

  <para>
   On the other hand, the following query finds all the cities that
   are not state capitals and are situated at an altitude over 500ft:

d1177 1
a1177 8
SELECT name, altitude
    FROM ONLY cities
    WHERE altitude &gt; 500;

   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
d1179 1
a1179 1
  </para>
a1180 12
  <para>
   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.
  </para>

  <note>
   <title>Inheritance and Permissions</title>
d1182 2
a1183 6
    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.
d1185 1
a1185 1
  </note>
d1187 2
a1188 18
  <para>
   Inheritance does not automatically propagate 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>
d1190 4
a1193 5
  <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:
d1195 8
d1204 1
a1204 3
SELECT c.tableoid, c.name, c.altitude
FROM cities c
WHERE c.altitude &gt; 500;
d1206 4
d1211 6
a1216 1
   which returns:
d1218 3
d1222 1
a1222 5
 tableoid |   name    | altitude
----------+-----------+----------
   139793 | Las Vegas |     2174
   139793 | Mariposa  |     1953
   139798 | Madison   |      845
d1224 3
d1228 7
a1234 3
   (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:
d1236 2
d1239 75
a1313 3
SELECT p.relname, c.name, c.altitude
FROM cities c, pg_class p
WHERE c.altitude &gt; 500 and c.tableoid = p.oid;
d1315 43
d1359 8
a1366 1
   which returns:
d1368 9
d1378 1
a1378 5
 relname  |   name    | altitude
----------+-----------+----------
 cities   | Las Vegas |     2174
 cities   | Mariposa  |     1953
 capitals | Madison   |      845
d1380 4
d1387 11
a1397 9
   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 data type 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 data types will be merged so that only a single
   column is stored.
d1401 9
a1409 12
   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.
d1411 8
d1421 6
a1426 6
   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.
d1429 10
d1440 9
a1448 7
   <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>.
d1452 1
a1452 9
   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:
d1457 2
a1458 9
      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
      default show up in queries from <structname>cities</>.  In fact, by
      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</>.
d1464 2
a1465 8
      Similarly, if we were to specify that
      <structname>cities</>.<structfield>name</> <literal>REFERENCES</> some
      other table, this constraint would not automatically propagate to
      <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.
d1471 2
a1472 3
      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.
d1477 6
a1482 3
   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.
d1484 4
a1487 1
  </para>
a1488 2
  <note>
   <title>Deprecated</title>
d1490 3
a1492 5
     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
     standard. Under the old syntax, to get the sub-tables you append
     <literal>*</literal> to the table name. For example:
d1494 1
a1494 1
SELECT * from cities*;
a1495 8
     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.
a1496 6
  </note>

  </sect1>

  <sect1 id="ce-partitioning">
   <title>Constraint Exclusion and Partitioning</title>
d1499 1
a1499 1
    <primary>partitioning</primary>
d1503 2
a1504 1
    <primary>constraint exclusion</primary>
d1508 11
a1518 3
    <productname>PostgreSQL</productname> supports basic table
    partitioning. This section describes why and how you can implement
    this as part of your database design.
d1521 9
a1529 2
   <sect2 id="ce-partitioning-overview">
     <title>Overview</title>
d1532 6
a1537 8
    Currently, partitioning is implemented in conjunction with table
    inheritance only, though using fully SQL 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.
d1540 5
d1546 12
a1557 8
    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>
d1559 11
a1569 8
    <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>
d1571 5
a1575 6
    <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>
d1577 2
a1578 6
    <listitem>
     <para>
      Seldom-used data can be migrated to cheaper and slower storage media.
     </para>
    </listitem>
   </itemizedlist>
d1580 4
a1583 6
    The benefits will normally be worthwhile only when a table would
    otherwise be very large. The exact point at which a table will
    benefit from partitioning depends on the application, although the
    size of the table should usually exceed the physical memory of the
    database server.
   </para>
d1586 13
a1598 2
    The following partitioning types are supported by
    <productname>PostgreSQL</productname> &version;:
d1600 2
a1601 3
    <variablelist>
     <varlistentry>
      <term>Range Partitioning</term>
d1603 3
a1605 9
      <listitem>
       <para>
        The table is partitioned along a <quote>range</quote> 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>
     </varlistentry>
d1607 3
a1609 2
     <varlistentry>
      <term>List Partitioning</term>
d1611 4
a1614 8
      <listitem>
       <para>
        The table is partitioned by explicitly listing which values
        relate to each partition.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
d1616 10
a1625 1
    Hash partitioning is not currently supported.
a1626 1
   </sect2>
d1628 4
a1631 2
   <sect2 id="ce-partitioning-implementation">
     <title>Implementing Partitioning</title>
d1633 6
a1638 7
    <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>
d1640 3
a1642 14
    <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>
d1644 16
a1659 5
      <listitem>
       <para>
        Create several <quote>child</quote> tables that inherit from
        the master table.
       </para>
d1661 10
a1670 5
       <para>
        We will refer to the child tables as partitions, though they
        are in every way normal <productname>PostgreSQL</> tables.
       </para>
      </listitem>
d1672 8
a1679 7
      <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:
d1681 1
a1681 3
CHECK ( x = 1 )
CHECK ( county IN ( 'Oxfordshire','Buckinghamshire','Warwickshire' ))
CHECK ( outletID BETWEEN 1 AND 99 )
d1683 3
d1687 8
a1694 376
        These can be linked together with the Boolean operators
        <literal>AND</literal> and <literal>OR</literal> to form
        complex constraints. Note that there is no difference in
        syntax between range and list partitioning; 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 data types you must explicitly coerce the constant
      values into the data type of the column. The following constraint
      will work if <varname>x</varname> is an <type>integer</type>
      data type, but not if <varname>x</varname> is a
      <type>bigint</type>:
<programlisting>
CHECK ( x = 1 )
</programlisting>
      For <type>bigint</type> we must use a constraint like:
<programlisting>
CHECK ( x = 1::bigint )
</programlisting>
      The problem is not limited to the <type>bigint</type> data type
      &mdash; it can occur whenever the default data type of the
      constant does not match the data type 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 parameterized 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>
      <command>UPDATE</command> and <command>DELETE</command> commands
      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>
a1696 67
   </sect2>

 </sect1>

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

  <indexterm zone="ddl-alter">
   <primary>table</primary>
   <secondary>modifying</secondary>
  </indexterm>

  <para>
   When you create a table and you realize that you made a mistake, or
   the requirements of the application change, then you can drop the
   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>
   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.
  </para>

  <para>
   You can
   <itemizedlist spacing="compact">
    <listitem>
     <para>Add columns,</para>
    </listitem>
    <listitem>
     <para>Remove columns,</para>
    </listitem>
    <listitem>
     <para>Add constraints,</para>
    </listitem>
    <listitem>
     <para>Remove constraints,</para>
    </listitem>
    <listitem>
     <para>Change default values,</para>
    </listitem>
    <listitem>
     <para>Change column data types,</para>
    </listitem>
    <listitem>
     <para>Rename columns,</para>
    </listitem>
    <listitem>
     <para>Rename tables.</para>
    </listitem>
   </itemizedlist>

   All these actions are performed using the
   <xref linkend="sql-altertable" endterm="sql-altertable-title">
   command.
  </para>

  <sect2>
   <title>Adding a Column</title>

   <indexterm>
    <primary>column</primary>
    <secondary>adding</secondary>
   </indexterm>

d1698 2
a1699 6
    To add a column, use a command like this:
<programlisting>
ALTER TABLE products ADD COLUMN description text;
</programlisting>
    The new column is initially filled with whatever default
    value is given (null if you don't specify a <literal>DEFAULT</> clause).
d1703 9
a1711 2
    You can also define constraints on the column at the same time,
    using the usual syntax:
d1713 1
a1713 1
ALTER TABLE products ADD COLUMN description text CHECK (description &lt;&gt; '');
d1715 2
a1716 6
    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.
d1720 2
a1721 2
  <sect2>
   <title>Removing a Column</title>
d1723 3
a1725 3
   <indexterm>
    <primary>column</primary>
    <secondary>removing</secondary>
d1729 17
a1745 1
    To remove a column, use a command like this:
d1747 1
a1747 1
ALTER TABLE products DROP COLUMN description;
d1749 5
a1753 11
    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.
d1757 2
a1758 2
  <sect2>
   <title>Adding a Constraint</title>
d1760 3
a1762 3
   <indexterm>
    <primary>constraint</primary>
    <secondary>adding</secondary>
d1766 10
a1775 11
    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>
d1779 12
a1790 2
    The constraint will be checked immediately, so the table data must
    satisfy the constraint before it can be added.
d1794 27
a1820 2
  <sect2>
   <title>Removing a Constraint</title>
d1822 6
a1827 4
   <indexterm>
    <primary>constraint</primary>
    <secondary>removing</secondary>
   </indexterm>
d1829 12
a1840 14
   <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>
    (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.)
d1842 1
d1844 2
a1845 6
   <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>
d1848 11
a1858 6
    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.)
a1859 9
  </sect2>

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

   <indexterm>
    <primary>default value</primary>
    <secondary>changing</secondary>
   </indexterm>
d1862 3
a1864 6
    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>
    Note that this doesn't affect any existing rows in the table, it
    just changes the default for future <command>INSERT</> commands.
d1868 5
a1872 8
    To remove any default value, use
<programlisting>
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
</programlisting>
    This is effectively the same as setting the default to null.
    As a consequence, it is not an error
    to drop a default where one hadn't been defined, because the
    default is implicitly the null value.
d1875 13
d1889 6
a1894 2
  <sect2>
   <title>Changing a Column's Data Type</title>
d1896 11
a1906 4
   <indexterm>
    <primary>column data type</primary>
    <secondary>changing</secondary>
   </indexterm>
a1907 2
   <para>
    To convert a column to a different data type, use a command like this:
d1909 9
a1917 1
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
a1918 5
    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>
d1920 5
a1924 9
   <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>
d1926 8
a1933 7
  <sect2>
   <title>Renaming a Column</title>

   <indexterm>
    <primary>column</primary>
    <secondary>renaming</secondary>
   </indexterm>
a1934 2
   <para>
    To rename a column:
d1936 3
a1938 1
ALTER TABLE products RENAME COLUMN product_no TO product_number;
a1939 2
   </para>
  </sect2>
d1941 2
a1942 7
  <sect2>
   <title>Renaming a Table</title>

   <indexterm>
    <primary>table</primary>
    <secondary>renaming</secondary>
   </indexterm>
a1943 2
   <para>
    To rename a table:
d1945 5
a1949 1
ALTER TABLE products RENAME TO items;
d1951 1
a1951 3
   </para>
  </sect2>
 </sect1>
d1953 3
a1955 2
 <sect1 id="ddl-priv">
  <title>Privileges</title>
d1957 4
a1960 3
  <indexterm zone="ddl-priv">
   <primary>privilege</primary>
  </indexterm>
d1962 6
a1967 4
  <indexterm>
   <primary>permission</primary>
   <see>privilege</see>
  </indexterm>
d1970 7
a1976 6
   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,
   <firstterm>privileges</firstterm> must be granted.  (However,
   users that have the superuser attribute can always
   access any object.)
d1980 12
a1991 12
   There are several different privileges: <literal>SELECT</>,
   <literal>INSERT</>, <literal>UPDATE</>, <literal>DELETE</>,
   <literal>RULE</>, <literal>REFERENCES</>, <literal>TRIGGER</>,
   <literal>CREATE</>, <literal>TEMPORARY</>, <literal>EXECUTE</>, and
   <literal>USAGE</>.  The privileges applicable to a particular
   object vary depending on the object's type (table, function, etc).
   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.
  </para>
d1993 7
a1999 4
  <para>
   The right to modify or destroy an object is always the privilege of
   the owner only.
  </para>
d2001 3
a2003 8
  <note>
   <para>
    To change the owner of a table, index, sequence, or view, use the
    <xref linkend="sql-altertable" endterm="sql-altertable-title">
    command.  There are corresponding <literal>ALTER</> commands for
    other object types.
   </para>
  </note>
a2004 5
  <para>
   To assign privileges, the <command>GRANT</command> command is
   used. For example, if <literal>joe</literal> is an existing user, and
   <literal>accounts</literal> is an existing table, the privilege to
   update the table can be granted with
d2006 3
a2008 1
GRANT UPDATE ON accounts TO joe;
d2010 9
a2018 3
   To grant a privilege to a group, use this syntax:
<programlisting>
GRANT SELECT ON accounts TO GROUP staff;
a2019 4
   The special <quote>user</quote> name <literal>PUBLIC</literal> can
   be used to grant a privilege to every user on the system. Writing
   <literal>ALL</literal> in place of a specific privilege grants all
   privileges that are relevant for the object type.
d2023 4
a2026 2
   To revoke a privilege, use the fittingly named
   <command>REVOKE</command> command:
d2028 2
a2029 1
REVOKE ALL ON accounts FROM PUBLIC;
d2031 8
a2038 6
   The special privileges of the object owner (i.e., the right to do
   <command>DROP</>, <command>GRANT</>, <command>REVOKE</>, etc.)
   are always implicit in being the owner,
   and cannot be granted or revoked.  But the object owner can choose
   to revoke his own ordinary privileges, for example to make a
   table read-only for himself as well as others.
d2042 4
a2045 9
   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.
a2046 1
 </sect1>
d2048 11
a2058 6
 <sect1 id="ddl-schemas">
  <title>Schemas</title>

  <indexterm zone="ddl-schemas">
   <primary>schema</primary>
  </indexterm>
d2061 11
a2071 6
   A <productname>PostgreSQL</productname> database cluster
   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.
a2073 10
  <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>

d2075 7
a2081 9
   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.
d2084 3
d2088 14
a2101 1
   There are several reasons why one might want to use schemas:
d2106 9
a2114 2
      To allow many users to use one database without interfering with
      each other.
d2120 6
a2125 2
      To organize database objects into logical groups to make them
      more manageable.
d2131 3
a2133 2
      Third-party applications can be put into separate schemas so
      they cannot collide with the names of other objects.
d2138 3
a2140 2
   Schemas are analogous to directories at the operating system level,
   except that schemas cannot be nested.
d2143 2
a2144 8
  <sect2 id="ddl-schemas-create">
   <title>Creating a Schema</title>

   <indexterm zone="ddl-schemas-create">
    <primary>schema</primary>
    <secondary>creating</secondary>
   </indexterm>

d2146 5
a2150 3
    To create a schema, use the command <command>CREATE
    SCHEMA</command>.  Give the schema a name of your choice.  For
    example:
d2152 1
a2152 1
CREATE SCHEMA myschema;
d2154 8
d2163 7
d2172 1
a2172 1
    <primary>qualified name</primary>
d2176 2
a2177 2
    <primary>name</primary>
    <secondary>qualified</secondary>
d2181 51
a2231 11
    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>
    This works anywhere a table name is expected, including the table
    modification commands and the data access commands discussed in
    the following chapters.
    (For brevity we will speak of tables only, but the same ideas apply
    to other kinds of named objects, such as types and functions.)
d2235 6
a2240 7
    Actually, the even more general syntax
<synopsis>
<replaceable>database</><literal>.</><replaceable>schema</><literal>.</><replaceable>table</>
</synopsis>
    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.
d2244 31
a2274 6
    So to create a table in the new schema, use
<programlisting>
CREATE TABLE myschema.mytable (
 ...
);
</programlisting>
d2276 33
d2310 5
a2314 4
   <indexterm>
    <primary>schema</primary>
    <secondary>removing</secondary>
   </indexterm>
d2316 2
a2317 3
   <para>
    To drop a schema if it's empty (all objects in it have been
    dropped), use
d2319 3
a2321 1
DROP SCHEMA myschema;
d2323 3
a2325 1
    To drop a schema including all contained objects, use
d2327 2
a2328 1
DROP SCHEMA myschema CASCADE;
d2330 46
a2375 3
    See <xref linkend="ddl-depend"> for a description of the general
    mechanism behind this.
   </para>
a2376 4
   <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:
d2378 6
a2383 1
CREATE SCHEMA <replaceable>schemaname</replaceable> AUTHORIZATION <replaceable>username</replaceable>;
a2384 4
    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>
d2386 13
a2398 5
   <para>
    Schema names beginning with <literal>pg_</> are reserved for
    system purposes and may not be created by users.
   </para>
  </sect2>
d2400 8
a2407 2
  <sect2 id="ddl-schemas-public">
   <title>The Public Schema</title>
d2409 3
a2411 4
   <indexterm zone="ddl-schemas-public">
    <primary>schema</primary>
    <secondary>public</secondary>
   </indexterm>
a2412 5
   <para>
    In the previous sections we created tables without specifying any
    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:
d2414 6
a2419 5
CREATE TABLE products ( ... );
</programlisting>
    and
<programlisting>
CREATE TABLE public.products ( ... );
a2420 2
   </para>
  </sect2>
d2422 4
a2425 2
  <sect2 id="ddl-schemas-path">
   <title>The Schema Search Path</title>
d2427 7
a2433 3
   <indexterm>
    <primary>search path</primary>
   </indexterm>
d2435 4
a2438 3
   <indexterm>
    <primary>unqualified name</primary>
   </indexterm>
d2440 20
a2459 4
   <indexterm>
    <primary>name</primary>
    <secondary>unqualified</secondary>
   </indexterm>
d2461 3
a2463 11
   <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>
d2465 8
a2472 4
   <indexterm>
    <primary>schema</primary>
    <secondary>current</secondary>
   </indexterm>
d2474 3
a2476 6
   <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>
d2478 6
a2483 3
   <indexterm>
    <primary>search_path</primary>
   </indexterm>
a2484 2
   <para>
    To show the current search path, use the following command:
d2486 7
a2492 1
SHOW search_path;
a2493 11
    In the default setup this returns:
<screen>
 search_path
--------------
 $user,public
</screen>
    The first element specifies that a schema with the same name as
    the current user is to be searched.  If no such schema exists,
    the entry is ignored.  The second element refers to the
    public schema that we have seen already.
   </para>
d2495 3
a2497 10
   <para>
    The first schema in the search path that exists is the default
    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>
a2498 2
   <para>
    To put our new schema in the path, we use
d2500 25
a2524 1
SET search_path TO myschema,public;
a2525 9
    (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>
d2527 39
a2565 8
   <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.
d2569 2
a2570 3
    See also <xref linkend="functions-info"> for other ways to manipulate
    the schema search path.
   </para>
a2571 10
   <para>
    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
    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
d2573 7
a2579 1
SELECT 3 OPERATOR(pg_catalog.+) 4;
d2581 5
a2585 2
    In practice one usually relies on the search path for operators,
    so as not to have to write anything so ugly as that.
d2587 1
a2587 1
  </sect2>
d2589 2
a2590 2
  <sect2 id="ddl-schemas-priv">
   <title>Schemas and Privileges</title>
d2592 2
a2593 3
   <indexterm zone="ddl-schemas-priv">
    <primary>privilege</primary>
    <secondary sortas="schemas">for schemas</secondary>
d2597 16
a2612 5
    By default, users cannot access any objects in schemas they do not
    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.
d2616 4
a2619 9
    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
    has <literal>CREATE</literal> and <literal>USAGE</literal> privileges on
    the schema
    <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
    not want to allow that, you can revoke that privilege:
d2621 18
a2638 1
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
a2639 7
    (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
    key word, hence the different capitalization; recall the
    guidelines from <xref linkend="sql-syntax-identifiers">.)
   </para>
  </sect2>
d2641 5
a2645 2
  <sect2 id="ddl-schemas-catalog">
   <title>The System Catalog Schema</title>
d2647 12
a2658 16
   <indexterm zone="ddl-schemas-catalog">
    <primary>system catalog</primary>
    <secondary>schema</secondary>
   </indexterm>

   <para>
    In addition to <literal>public</> and user-created schemas, each
    database contains a <literal>pg_catalog</> schema, which contains
    the system tables and all the built-in data types, functions, and
    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.
d2662 7
a2668 12
    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
    future version defines a system table named the same as your
    table.  (With the default search path, an unqualified reference to
    your table name would be resolved as the system table instead.)
    System tables will continue to follow the convention of having
    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.
a2669 4
  </sect2>

  <sect2 id="ddl-schemas-patterns">
   <title>Usage Patterns</title>
d2672 1
a2672 14
    Schemas can be used to organize your data in many ways.  There are
    a few usage patterns that are recommended and are easily supported by
    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
       recommended when there is only a single user or a few cooperating
       users in a database.  This setup also allows smooth transition
       from the non-schema-aware world.
      </para>
     </listitem>
d2674 12
a2685 8
     <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>
d2687 22
a2708 6
      <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>
d2710 6
a2715 14
     <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
       then refer to these additional objects by qualifying the names
       with a schema name, or they can put the additional schemas into
       their search path, as they choose.
      </para>
     </listitem>
    </itemizedlist>
   </para>
  </sect2>
d2717 7
a2723 2
  <sect2 id="ddl-schemas-portability">
   <title>Portability</title>
d2725 10
a2734 13
   <para>
    In the SQL standard, the notion of objects in the same schema
    being owned by different users does not exist.  Moreover, some
    implementations do not allow you to create schemas that have a
    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>.
    This is how <productname>PostgreSQL</productname> will effectively
    behave if you create a per-user schema for every user.
   </para>
d2736 1
a2736 12
   <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.
d2827 1
a2827 1
   constraint.  (If you want to check what <literal>DROP ... CASCADE</> will do,
@


1.48
log
@Avoid referring to a specific version of the SQL standard except where
necessary, and be careful to refer to the right version where it is
useful to do so.  This partially reverts an ill-considered search and
replace from a few months ago.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.47 2005/11/03 00:51:43 neilc Exp $ -->
d205 1
a205 1
   is that a timestamp column may have a default of <literal>now()</>,
d1160 1
a1160 1
   Inheritance does not automatically propogate data from
d1224 1
a1224 1
   column cannot override the datatype of an inherited column of the
d1229 1
a1229 1
   duplicate names and datatypes will be merged so that only a single
d1501 1
a1501 1
        These can be linked together with the boolean operators
d1725 2
a1726 2
      For some datatypes you must explicitly coerce the constant
      values into the datatype of the column. The following constraint
d1728 1
a1728 1
      datatype, but not if <varname>x</varname> is a
d1737 3
a1739 3
      The problem is not limited to the <type>bigint</type> datatype
      &mdash; it can occur whenever the default datatype of the
      constant does not match the datatype of the column to which it
d1852 1
a1852 1
      a constant. A constant bound to a parameterised query will not
d1863 2
a1864 2
      UPDATEs and DELETEs against the master table do not perform
      constraint exclusion.
@


1.47
log
@Some minor improvements to the CE docs. Also fix a bit of SGML markup
elsewhere.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.46 2005/11/01 23:19:05 neilc Exp $ -->
d1061 2
a1062 2
   which can be a useful tool for database designers.  The SQL:2003
   standard optionally defines type inheritance which differs in many
d1326 1
a1326 1
     found to be error prone and is also in violation of the SQL:2003
d1367 1
a1367 1
    inheritance only, though using fully SQL:2003 compliant syntax.
@


1.46
log
@Add some documentation for constraint exclusion and basic partitioning.
From Simon Riggs; cleanup and editorialization by Neil Conway.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.45 2005/10/23 19:29:49 tgl Exp $ -->
d1409 5
a1413 3
    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.
d1417 2
a1418 2
    In <productname>PostgreSQL</productname> &version;, the following
    partitioning types are supported:
d1420 16
a1435 9
    <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>
d1437 8
a1444 7
     <listitem>
      <para>
       "List Partitioning" where the table is partitioned by
       explicitly listing which values relate to each partition.
      </para>
     </listitem>
    </itemizedlist>
d1484 1
a1484 2
        are in every way just normal <productname>PostgreSQL</>
        tables.
d1497 1
a1497 1
CHECK ( county IN ('Oxfordshire','Buckinghamshire','Warwickshire'))
d1501 6
a1506 5
        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.
d1725 5
a1729 3
      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.
d1733 1
a1733 1
      For BIGINT we must use a constraint like:
d1737 4
a1740 3
      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.
d2328 2
a2329 2
    To create a schema, use the command <literal>CREATE
    SCHEMA</literal>.  Give the schema a name of your choice.  For
@


1.45
log
@A bit of minor copy-editing.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.44 2005/08/13 01:55:41 momjian Exp $ -->
d401 7
d1050 15
a1064 2
  <remark>This section needs to be rethought.  Some of the
  information should go into the following chapters.</remark>
d1067 10
a1076 3
   Let's create two tables. The capitals  table  contains
   state  capitals  which  are also cities. Naturally, the
   capitals table should inherit from cities.
d1082 1
a1082 1
    altitude        int     -- (in ft)
d1090 4
a1093 12
   In this case, a row of capitals <firstterm>inherits</firstterm> all
   attributes (name, population, and altitude) from its parent, cities.  State
   capitals have an extra attribute, state, that shows their state.  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.

   <note>
    <para>
     The inheritance hierarchy is actually a directed acyclic graph.
    </para>
   </note>
d1097 6
a1102 3
    For example, the  following  query finds the  names  of  all  cities,
    including  state capitals, that are located at an altitude 
    over 500ft:
d1122 2
a1123 3
    On the other hand, the  following  query  finds
    all  the cities that are not state capitals and
    are situated at an altitude over 500ft:
d1134 1
a1134 1
</programlisting>         
d1138 7
a1144 6
   Here the <quote>ONLY</quote> before cities indicates that the query should
   be  run over only cities and not tables below cities in the
   inheritance hierarchy.  Many of the  commands  that  we
   have  already discussed -- <command>SELECT</command>,
   <command>UPDATE</command> and <command>DELETE</command> --
   support this <quote>ONLY</quote> notation.
a1146 11

<note>
  <title>Inheritance and Permissions</title>
  <para>
  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.
  </para>
</note>
  
d1148 1
a1148 1
   <title>Deprecated</title> 
d1150 6
a1155 20
     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, set the configuration option
     <literal>SQL_Inheritance</literal> to off, e.g.,
<programlisting>
SET SQL_Inheritance TO OFF;
</programlisting>
     or add a line in your <filename>postgresql.conf</filename> file.
d1160 23
a1182 4
  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:
a1218 1
   
d1222 43
a1264 3
   A table can inherit from more than one parent table, in which case it has
   the union of the columns defined by the parent tables (plus any columns
   declared specifically for the child table).
d1268 9
a1276 5
   A serious limitation of the inheritance feature is that indexes (including
   unique constraints) and foreign key constraints only apply to single
   tables, not to their inheritance children.  This is true on both the
   referencing and referenced sides of a foreign key constraint.  Thus,
   in the terms of the above example:
d1298 5
a1302 3
      <structname>capitals</>.  In this case you could work around it by
      manually adding the same <literal>REFERENCES</> constraint to
      <structname>capitals</>.
d1318 1
d1320 548
d2143 1
a2143 1
 
d2566 1
a2566 1
    the schema 
@


1.44
log
@Add documentation:

>>>I think a more accurate description would be "permissions not
>>>inherited by children," and that isn't necessarily a bug.
>>
>>I agree it may not be a bug - but it's more than the permissions not
>>being inherited: the parent is affected.
>
>
> Not really, once you understand what's happening.  Unless you use
> FROM ONLY, selecting from the parent selects from the parent *and*
> its children.  The parent itself isn't affected, as queries with
> FROM ONLY should demonstrate.  I understand what you're saying --
> that there's an apparent effect on the parent -- but there really
> isn't.

Sean Burlington
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.43 2005/08/12 01:35:53 tgl Exp $ -->
d243 1
a243 1
   data type that accepts only positive numbers.  Another issue is
d434 1
a434 1
    cannot give explicit names to not-null constraints created that
d554 1
a554 1
    unique constraint it is possible to store an unlimited number of
@


1.43
log
@Solve the problem of OID collisions by probing for duplicate OIDs
whenever we generate a new OID.  This prevents occasional duplicate-OID
errors that can otherwise occur once the OID counter has wrapped around.
Duplicate relfilenode values are also checked for when creating new
physical files.  Per my recent proposal.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.42 2005/07/14 06:17:35 neilc Exp $ -->
d1125 11
@


1.42
log
@This doc patch replaces all inappropriate references to SQL:1999 when it
is used as if it were the latest (and/or still valid) SQL standard.
SQL:2003 is used in its place. Patch from Simon Riggs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.41 2005/06/13 02:40:01 neilc Exp $ -->
d874 1
a874 1
      configuration variable was enabled. This column is of type
d995 7
a1001 1
       table for which the OID will be used to identify rows.
d1014 2
a1015 3
       OIDS</literal> to ensure forward compatibility with future
       releases of <productname>PostgreSQL</productname>.  It is
       planned that <literal>WITHOUT OIDS</> will become the default.
@


1.41
log
@SGML cleanup: consistently use "endterm" in <xref>s that link to the
reference page for SQL commands, so that the link text is italicized.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.40 2005/03/13 09:36:30 neilc Exp $ -->
d1125 1
a1125 1
     found to be error prone and is also in violation of the SQL:1999
@


1.40
log
@Make default_with_oids default to false -- user-created tables will now
no longer include OIDs, unless WITH OIDS is specified or the
default_with_oids configuration parameter is enabled. Update the docs
accordingly.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.39 2005/01/22 22:56:35 momjian Exp $ -->
d1543 2
a1544 2
   <literal>CREATE</>, <literal>TEMPORARY</>, <literal>EXECUTE</>,
   and <literal>USAGE</>.  The privileges applicable to a particular
d1546 5
a1550 5
   For complete
   information on the different types of privileges supported by
   <productname>PostgreSQL</productname>, refer to the
   <xref linkend="sql-grant"> reference page.  The following sections
   and chapters will also show you how those privileges are used.
d1561 3
a1563 2
    <xref linkend="sql-altertable"> command.  There are corresponding
    <literal>ALTER</> commands for other object types.
d1600 9
a1608 8
   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"> and <xref linkend="sql-revoke"> reference
   pages.
@


1.39
log
@More < and > cleanups converted to ampersands.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.38 2005/01/17 01:29:02 tgl Exp $ -->
d871 4
a874 5
      The object identifier (object ID) of a row.  This is a serial
      number that is automatically added by
      <productname>PostgreSQL</productname> to all table rows (unless
      the table was created using <literal>WITHOUT OIDS</literal>, in which
      case this column is not present).  This column is of type
@


1.38
log
@Some more copy-editing.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.37 2005/01/09 17:47:30 tgl Exp $ -->
d278 1
a278 1
    price numeric <emphasis>CHECK (price > 0)</emphasis>
d306 1
a306 1
    price numeric <emphasis>CONSTRAINT positive_price</emphasis> CHECK (price > 0)
d323 3
a325 3
    price numeric CHECK (price > 0),
    discounted_price numeric CHECK (discounted_price > 0),
    <emphasis>CHECK (price > discounted_price)</emphasis>
d353 1
a353 1
    CHECK (price > 0),
d355 2
a356 2
    CHECK (discounted_price > 0),
    CHECK (price > discounted_price)
d364 1
a364 1
    price numeric CHECK (price > 0),
d366 1
a366 1
    CHECK (discounted_price > 0 AND price > discounted_price)
d380 1
a380 1
    CHECK (price > 0),
d382 2
a383 2
    CHECK (discounted_price > 0),
    <emphasis>CONSTRAINT valid_discount</> CHECK (price > discounted_price)
d445 1
a445 1
    price numeric NOT NULL CHECK (price > 0)
@


1.38.4.1
log
@More < and > cleanups converted to ampersands.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.38 2005/01/17 01:29:02 tgl Exp $ -->
d278 1
a278 1
    price numeric <emphasis>CHECK (price &gt; 0)</emphasis>
d306 1
a306 1
    price numeric <emphasis>CONSTRAINT positive_price</emphasis> CHECK (price &gt; 0)
d323 3
a325 3
    price numeric CHECK (price &gt; 0),
    discounted_price numeric CHECK (discounted_price &gt; 0),
    <emphasis>CHECK (price &gt; discounted_price)</emphasis>
d353 1
a353 1
    CHECK (price &gt; 0),
d355 2
a356 2
    CHECK (discounted_price &gt; 0),
    CHECK (price &gt; discounted_price)
d364 1
a364 1
    price numeric CHECK (price &gt; 0),
d366 1
a366 1
    CHECK (discounted_price &gt; 0 AND price &gt; discounted_price)
d380 1
a380 1
    CHECK (price &gt; 0),
d382 2
a383 2
    CHECK (discounted_price &gt; 0),
    <emphasis>CONSTRAINT valid_discount</> CHECK (price &gt; discounted_price)
d445 1
a445 1
    price numeric NOT NULL CHECK (price &gt; 0)
@


1.37
log
@Update discussion of ALTER TABLE ADD COLUMN, per Michael Fuhr.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.36 2005/01/08 01:44:05 tgl Exp $ -->
a165 192
 <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>
      The object identifier (object ID) of a row.  This is a serial
      number that is automatically added by
      <productname>PostgreSQL</productname> to all table rows (unless
      the table was created using <literal>WITHOUT OIDS</literal>, in which
      case this column is not present).  This column is of type
      <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
       table for which the OID will be used to identify rows.
      </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
       OIDS</literal> to ensure forward compatibility with future
       releases of <productname>PostgreSQL</productname>.  It is
       planned that <literal>WITHOUT OIDS</> will become the default.
      </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>

d202 1
a202 1
   The default value may be a scalar expression, which will be
d271 3
a273 3
    you to specify that the value in a certain column must satisfy an
    arbitrary expression.  For instance, to require positive product
    prices, you could use:
d311 2
a312 1
    by the constraint definition.
d325 1
a325 1
    CHECK (price > discounted_price)
d341 1
a341 1
    from the column definitions.  Column constraints can also be
d343 5
a347 1
    possible.  The above example could also be written as
d372 16
d396 1
a396 1
    expressions will evaluate to the null value if one operand is null,
d440 1
a440 1
    the constraints after one another:
d456 1
a456 1
    simply defines the default behavior that the column may be null.
d527 3
d533 1
a533 1
    It is also possible to assign names to unique constraints:
d692 1
a692 1
    product_no integer REFERENCES products,
d712 1
a712 1
    Of course, the number and type of the constrained columns needs to
d717 5
d747 1
a747 1
    Note also that the primary key overlaps with the foreign keys in
d844 192
d1150 1
a1150 1
  <structfield>TABLEOID</structfield> in each table which can tell you the
d1255 1
a1255 1
   the requirements of the application changed, then you can drop the
d1260 4
a1263 2
   provides a family of commands to make modifications on existing
   tables.
d1309 1
a1309 1
    To add a column, use this command:
d1341 1
a1341 1
    To remove a column, use this command:
d1345 11
d1412 7
d1450 1
a1450 1
    This is equivalent to setting the default to null.
d1712 3
d1724 3
a1726 3
    can be used too, but at present this is just for 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.
a1735 3
    This works anywhere a table name is expected, including the table
    modification commands and the data access commands discussed in
    the following chapters.
d1896 1
a1896 1
    See also <xref linkend="functions-info"> for other ways to access
d2096 7
a2102 1
     Functions, operators, data types, domains
d2178 1
a2178 1
    required.  No database system actually implements it that way, but
d2190 1
a2190 1
    created during an upgrade.
@


1.36
log
@Some small docs improvements motivated by reading the comments for the
7.4 interactive docs.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.35 2004/12/23 05:37:39 tgl Exp $ -->
d1282 2
a1283 2
    The new column will initially be filled with null values in the
    existing rows of the table.
d1287 1
a1287 1
    You can also define a constraint on the column at the same time,
d1292 6
a1297 7
    A new column cannot have a not-null constraint since the column
    initially has to contain null values.  But you can add a not-null
    constraint later.  Also, you cannot define a default value on a
    new column.  According to the SQL standard, this would have to
    fill the new columns in the existing rows with the default value,
    which is not implemented yet.  But you can adjust the column
    default later on.
d1392 5
d1401 2
a1402 2
    This is equivalent to setting the default to null, at least in
    <productname>PostgreSQL</>.  As a consequence, it is not an error
@


1.35
log
@A small pass of docs review and copy-editing.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.34 2004/12/13 18:05:08 petere Exp $ -->
d398 22
a419 1
   so that it gets set to the time of row insertion.
d1163 6
@


1.34
log
@Spell checker run
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.33 2004/11/27 21:27:06 petere Exp $ -->
d263 1
a263 1
      be nonzero in a visible row version: That usually indicates that the
d332 2
a333 2
       releases of <productname>PostgreSQL</productname> in which OIDs
       are not included in all tables by default.
d370 1
a370 1
   be set to its default value, without knowing what this value is.
d376 3
a378 3
   If no default value is declared explicitly, the null value is the
   default value.  This usually makes sense because a null value can
   be thought to represent unknown data.
d396 3
a398 1
   (<emphasis>not</emphasis> when the table is created).
d549 1
a549 1
    constraint described in the next section should be used.
d696 3
a698 3
    In general, a unique constraint is violated when there are (at
    least) two rows in the table where the values of each of the
    corresponding columns that are part of the constraint are equal.
d700 1
a700 1
    consideration.  That means even in the presence of a
d844 1
a844 1
    referenced table is used as the referenced column.
d907 1
a907 1
    specify that as well.  Intuitively, we have a few options:
d945 1
a945 1
    <literal>RESTRICT</literal> prevents a statement from deleting a
d948 2
a949 2
    is raised; this is the default if you do not specify anything.
    (The essential difference between these choices is that
d952 2
d961 1
a961 1
    deletion of the primary key will fail.
d966 2
a967 2
    <literal>ON UPDATE</literal> which is invoked when a primary key
    is changed (updated).  The possible actions are the same.
d1227 3
d1237 3
a1239 2
   All these actions are performed using the <literal>ALTER
   TABLE</literal> command.
d1354 1
a1354 1
   <title>Changing the Default</title>
d1378 29
d1608 1
a1608 1
    To create a separate schema, use the command <literal>CREATE
d1870 1
a1870 1
    reserved word, hence the different capitalization; recall the
@


1.33
log
@Update of conformance information to SQL:2003
by Troels Arvin, Simon Riggs, Elein Mustain

Make spelling of SQL standard names uniform.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.32 2004/11/15 06:32:13 neilc Exp $ -->
d1151 1
a1151 1
      default show up in SELECTs from <structname>cities</>.  In fact, by
@


1.32
log
@Replace "--" and "---" with "&mdash;" as appropriate, for better-looking
output.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.31 2004/10/21 21:33:59 tgl Exp $ -->
d1072 1
a1072 1
     found to be error prone and is also in violation of the SQL99
@


1.31
log
@Disallow referential integrity actions from being deferred; only the
NO ACTION check is deferrable.  This seems to be a closer approximation
to what the SQL spec says than what we were doing before, and it prevents
some anomalous behaviors that are possible now that triggers can fire
during the execution of PL functions.
Stephan Szabo.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.30 2004/08/08 21:33:11 tgl Exp $ -->
d353 1
a353 1
    problem --- note that the limit is on number of
@


1.30
log
@Move expanded discussion of inheritance's limitations out of tutorial
and into ddl.sgml.  Rewrite for more completeness and (hopefully)
clarity.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/ddl.sgml,v 1.29 2004/08/07 20:44:49 tgl Exp $ -->
d943 8
a950 4
    <literal>RESTRICT</literal> can also be written as <literal>NO
    ACTION</literal> and it's also the default if you do not specify
    anything.  There are two other options for what should happen with
    the foreign key columns when a primary key is deleted:
d952 2
d973 1
a973 1
    columns that are either a primary key or form a unique constraint.
@


1.29
log
@Improve privileges discussion (mostly, mention grant options).
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/ddl.sgml,v 1.28 2004/08/07 19:53:48 tgl Exp $ -->
d999 6
a1004 13
   In this case, a row  of  capitals  <firstterm>inherits</firstterm>  all
   attributes  (name,  population,  and altitude) from its
   parent, cities.  The type  of  the  attribute  name  is
   <type>text</type>,  a  native  <productname>PostgreSQL</productname>  type
   for variable length character strings.  The type of the attribute
   population is
   <type>float</type>,  a  native <productname>PostgreSQL</productname> type for double precision
   floating-point numbers.  State capitals have  an  extra
   attribute, state, that shows their state.  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. 
d1061 26
a1130 26
  <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 SQL99
     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, set the configuration option
     <literal>SQL_Inheritance</literal> to off, e.g.,
<programlisting>
SET SQL_Inheritance TO OFF;
</programlisting>
     or add a line in your <filename>postgresql.conf</filename> file.
   </para>
  </note>

d1132 1
a1132 1
   A limitation of the inheritance feature is that indexes (including
d1134 42
a1175 4
   tables, not to their inheritance children.  Thus, in the above example,
   specifying that another table's column <literal>REFERENCES cities(name)</>
   would allow the other table to contain city names but not capital names.
   This deficiency will probably be fixed in some future release.
@


1.28
log
@Update a couple of example error messages to reflect the fact that we
don't generate constraint names like "$1" anymore.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/ddl.sgml,v 1.27 2004/08/03 20:32:30 tgl Exp $ -->
d1381 2
a1382 2
   <firstterm>privileges</firstterm> must be granted.  (There are also
   users that have the superuser privilege.  Those users can always
a1385 8
  <note>
   <para>
    To change the owner of a table, index, sequence, or view, use the
    <xref linkend="sql-altertable" endterm="sql-altertable-title">
    command.
   </para>
  </note>

d1391 3
a1393 1
   <literal>USAGE</>, and <literal>ALL PRIVILEGES</>. For complete
d1396 1
a1396 2
   <xref linkend="sql-grant" endterm="sql-grant-title">
   reference page.  The following sections
d1405 8
d1415 1
a1415 1
   used. So, if <literal>joe</literal> is an existing user, and
d1421 1
a1421 2
   The user executing this command must be the owner of the table. To
   grant a privilege to a group, use
d1427 2
a1428 2
   <literal>ALL</literal> in place of a specific privilege specifies that all
   privileges will be granted.
d1437 1
a1437 1
   The special privileges of the table owner (i.e., the right to do
d1440 1
a1440 1
   and cannot be granted or revoked.  But the table owner can choose
d1444 11
d1558 5
d1568 1
a1568 1
    with the SQL standard; if you write a database name it must be the
d1881 1
a1881 1
       their path, as they choose.
@


1.27
log
@Add functions pg_start_backup, pg_stop_backup to create backup label
and history files as per recent discussion.  While at it, remove
pg_terminate_backend, since we have decided we do not have time during
this release cycle to address the reliability concerns it creates.
Split the 'Miscellaneous Functions' documentation section into
'System Information Functions' and 'System Administration Functions',
which hopefully will draw the eyes of those looking for such things.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/ddl.sgml,v 1.26 2004/03/07 04:31:01 neilc Exp $ -->
d1974 1
a1974 1
NOTICE:  constraint $1 on table orders depends on table products
@


1.26
log
@Improve discussion of using OIDs for identifying rows, fix an instance of
incorrect SGML markup.
@
text
@d1 1
a1 1
<!-- $PostgreSQL: pgsql-server/doc/src/sgml/ddl.sgml,v 1.25 2003/11/29 19:51:36 pgsql Exp $ -->
d1726 1
a1726 1
    See also <xref linkend="functions-misc"> for other ways to access
@


1.25
log
@
$Header: -> $PostgreSQL Changes ...
@
text
@d1 1
a1 1
<!-- $PostgreSQL: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.24 2003/11/24 19:08:01 petere Exp $ -->
d80 2
a81 2
   To create a table, you use the aptly named <literal>CREATE
   TABLE</literal> command.  In this command you specify at least a
d305 32
a336 12
    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 they are unique.
    Recommended practice when using OIDs for row identification is to create
    a unique constraint on the OID column of each table for which the OID will
    be used.  Never assume that OIDs are unique across tables; use the
    combination of <structfield>tableoid</> and row OID if you need a
    database-wide identifier.  (Future releases of
    <productname>PostgreSQL</productname> are likely to use a separate
    OID counter for each table, so that <structfield>tableoid</>
    <emphasis>must</> be included to arrive at a globally unique identifier.)
d821 1
a821 1
    <literal>product_no</literal> entries that do not appear in the
d915 1
a915 1
    many-to-many relationship example above: When someone wants to
@


1.24
log
@Upgrade to DocBook V4.2 SGML.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.23 2003/11/05 00:05:32 tgl Exp $ -->
@


1.23
log
@Minor copy-editing.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.22 2003/11/04 09:55:38 petere Exp $ -->
d959 2
a960 2
  <comment>This section needs to be rethought.  Some of the
  information should go into the following chapters.</comment>
@


1.22
log
@Random copy-editing.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.21 2003/11/01 01:56:29 petere Exp $ -->
d15 1
a15 2
  such as views, functions, and triggers.  Detailed information on
  these topics is found in <xref linkend="server-programming">.
d524 1
a524 1
    expressions will evaluate to the null value if one operand is null
d588 1
a588 1
    compatible with other database systems.)  Some users, however,
d822 1
a822 1
    referenced table is used as referenced column.
d1096 4
a1099 3
     default was not to get access to child tables. This was found to
     be error prone and is also in violation of the SQL99 standard. Under the old
     syntax, to get the sub-tables you append <literal>*</literal> to the table name.
d1273 6
d1748 5
a1752 3
    has the <literal>CREATE</literal> privilege on the schema
    <literal>public</literal>.  This allows all users that manage to
    connect to a given database to create objects there.  If you do
d1916 5
@


1.21
log
@Spell checking, consistent terminology.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.20 2003/10/28 20:18:09 tgl Exp $ -->
d321 6
a326 6
    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.  However, it is
    unwise to depend on uniqueness of transaction IDs over the long term
    (more than one billion transactions).
@


1.21.2.1
log
@Random copy-editing.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.21 2003/11/01 01:56:29 petere Exp $ -->
d321 6
a326 6
    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).
@


1.21.2.2
log
@Minor copy-editing.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.22 2003/11/04 09:55:38 petere Exp $ -->
d15 2
a16 1
  such as views, functions, and triggers.
d525 1
a525 1
    expressions will evaluate to the null value if one operand is null,
d589 1
a589 1
    compatible with some other database systems.)  Some users, however,
d823 1
a823 1
    referenced table is used as the referenced column.
d1097 3
a1099 4
     default behavior was not to include child tables in queries. This was
     found to be error prone and is also in violation of the SQL99
     standard. Under the old syntax, to get the sub-tables you append
     <literal>*</literal> to the table name.
a1272 6
    (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>

   <para>
d1742 3
a1744 5
    has <literal>CREATE</literal> and <literal>USAGE</literal> privileges on
    the schema 
    <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
a1907 5

  <para>
   Detailed information on
   these topics appears in <xref linkend="server-programming">.
  </para>
@


1.20
log
@Adjust wording to avoid giving the impression that schema USAGE
privilege hides system catalog entries.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.19 2003/09/12 22:17:22 tgl Exp $ -->
d233 3
a235 3
      this tuple.  (Note: In this context, a tuple is an individual
      state of a row; each update of a row creates a new tuple for the
      same logical row.)
d263 2
a264 2
      zero for an undeleted tuple.  It is possible for this column to
      be nonzero in a visible tuple: That usually indicates that the
d292 1
a292 1
      The physical location of the tuple within its table.  Note that
d294 1
a294 1
      locate the tuple very quickly, a row's
d335 1
a335 1
    <acronym>SQL</acronym> commands, not number of tuples processed.
d1050 1
a1050 1
  In some cases you may wish to know which table a particular tuple
@


1.19
log
@Update obsolete examples of error messages; various other minor editing.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.18 2003/08/31 17:32:18 petere Exp $ -->
d1731 1
a1731 1
    By default, users cannot see the objects in schemas they do not
@


1.18
log
@Add/edit index entries.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.17 2003/08/14 23:13:27 tgl Exp $ -->
d1942 2
a1943 2
ERROR:  Cannot drop table products because other objects depend on it
        Use DROP ... CASCADE to drop the dependent objects too
d1961 1
a1961 1
   <literal>CASCADE</literal> to get the default behavior which is to
@


1.17
log
@Minor copy-editing.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.16 2003/08/10 01:20:34 tgl Exp $ -->
d22 12
d75 5
d134 5
d181 2
a182 2
   <primary>columns</primary>
   <secondary>system columns</secondary>
d192 1
d208 4
d227 4
d243 4
d257 4
d274 4
d287 4
d342 4
d356 1
d384 4
d410 9
d443 5
d517 5
d535 9
d613 9
d669 5
d692 9
d759 13
d872 10
d1131 5
d1180 5
d1213 5
d1229 5
d1257 5
d1285 5
d1309 5
d1325 5
d1342 9
d1423 2
a1424 6
  <indexterm>
   <primary>schemas</primary>
  </indexterm>

  <indexterm>
   <primary>namespaces</primary>
d1491 5
d1506 1
a1506 1
    <primary>qualified names</primary>
d1510 1
a1510 1
    <primary>names</primary>
d1542 5
d1582 5
d1610 1
a1610 1
    <primary>unqualified names</primary>
d1614 1
a1614 1
    <primary>names</primary>
d1630 5
d1642 4
d1725 5
d1757 1
a1757 1
  <sect2>
d1760 5
d1912 10
@


1.17.2.1
log
@Update this branch to match CVS head, includes WIN32 improvements.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.18 2003/08/31 17:32:18 petere Exp $ -->
a21 12
  <indexterm zone="ddl-basics">
   <primary>table</primary>
  </indexterm>

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

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

a62 5
  <indexterm>
   <primary>table</primary>
   <secondary>creating</secondary>
  </indexterm>

a116 5
  <indexterm>
   <primary>table</primary>
   <secondary>removing</secondary>
  </indexterm>

d159 2
a160 2
   <primary>column</primary>
   <secondary>system column</secondary>
a169 1
       <secondary>column</secondary>
a184 4
     <indexterm>
      <primary>tableoid</primary>
     </indexterm>

a199 4
     <indexterm>
      <primary>xmin</primary>
     </indexterm>

a211 4
     <indexterm>
      <primary>cmin</primary>
     </indexterm>

a221 4
     <indexterm>
      <primary>xmax</primary>
     </indexterm>

a234 4
     <indexterm>
      <primary>cmax</primary>
     </indexterm>

a243 4
     <indexterm>
      <primary>ctid</primary>
     </indexterm>

a294 4
  <indexterm zone="ddl-default">
   <primary>default value</primary>
  </indexterm>

a304 1
   <indexterm><primary>null value</primary><secondary>default value</secondary></indexterm>
a331 4
  <indexterm zone="ddl-constraints">
   <primary>constraint</primary>
  </indexterm>

a353 9
   <indexterm>
    <primary>check constraint</primary>
   </indexterm>

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

a377 5
   <indexterm>
    <primary>constraint</primary>
    <secondary>name</secondary>
   </indexterm>

a446 5
   <indexterm>
    <primary>null value</primary>
    <secondary sortas="check constraints">with check constraints</secondary>
   </indexterm>

a459 9
   <indexterm>
    <primary>not-null constraint</primary>
   </indexterm>

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

a528 9
   <indexterm>
    <primary>unique constraint</primary>
   </indexterm>

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

a575 5
   <indexterm>
    <primary>null value</primary>
    <secondary sortas="unique constraints">with unique constraints</secondary>
   </indexterm>

a593 9
   <indexterm>
    <primary>primary key</primary>
   </indexterm>

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

a651 13
   <indexterm>
    <primary>foreign key</primary>
   </indexterm>

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

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

a751 10
   <indexterm>
    <primary>CASCADE</primary>
    <secondary>foreign key action</secondary>
   </indexterm>

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

a1000 5
  <indexterm zone="ddl-alter">
   <primary>table</primary>
   <secondary>modifying</secondary>
  </indexterm>

a1044 5
   <indexterm>
    <primary>column</primary>
    <secondary>adding</secondary>
   </indexterm>

a1072 5
   <indexterm>
    <primary>column</primary>
    <secondary>removing</secondary>
   </indexterm>

a1083 5
   <indexterm>
    <primary>constraint</primary>
    <secondary>adding</secondary>
   </indexterm>

a1106 5
   <indexterm>
    <primary>constraint</primary>
    <secondary>removing</secondary>
   </indexterm>

a1129 5
   <indexterm>
    <primary>default value</primary>
    <secondary>changing</secondary>
   </indexterm>

a1148 5
   <indexterm>
    <primary>column</primary>
    <secondary>renaming</secondary>
   </indexterm>

a1159 5
   <indexterm>
    <primary>table</primary>
    <secondary>renaming</secondary>
   </indexterm>

a1171 9
  <indexterm zone="ddl-priv">
   <primary>privilege</primary>
  </indexterm>

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

d1244 6
a1249 2
  <indexterm zone="ddl-schemas">
   <primary>schema</primary>
a1315 5
   <indexterm zone="ddl-schemas-create">
    <primary>schema</primary>
    <secondary>creating</secondary>
   </indexterm>

d1326 1
a1326 1
    <primary>qualified name</primary>
d1330 1
a1330 1
    <primary>name</primary>
a1361 5
   <indexterm>
    <primary>schema</primary>
    <secondary>removing</secondary>
   </indexterm>

a1396 5
   <indexterm zone="ddl-schemas-public">
    <primary>schema</primary>
    <secondary>public</secondary>
   </indexterm>

d1420 1
a1420 1
    <primary>unqualified name</primary>
d1424 1
a1424 1
    <primary>name</primary>
a1439 5
   <indexterm>
    <primary>schema</primary>
    <secondary>current</secondary>
   </indexterm>

a1446 4
   <indexterm>
    <primary>search_path</primary>
   </indexterm>

a1525 5
   <indexterm zone="ddl-schemas-priv">
    <primary>privilege</primary>
    <secondary sortas="schemas">for schemas</secondary>
   </indexterm>

d1553 1
a1553 1
  <sect2 id="ddl-schemas-catalog">
a1555 5
   <indexterm zone="ddl-schemas-catalog">
    <primary>system catalog</primary>
    <secondary>schema</secondary>
   </indexterm>

a1702 10

  <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>
@


1.16
log
@Make various links point to specific places instead of entire parts
(doubtless these are hangovers from the old separate-books days).
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.15 2003/05/07 03:41:31 tgl Exp $ -->
d493 1
a493 1
    The order doesn't matter.  It does not necessarily affect in which
d581 1
a581 1
    consideration.  That means, in the presence of a multicolumn
d632 1
a632 1
    a unique constraint does not, in fact, provide a unique identifier
d853 3
a855 2
   <type>text</type>,  a  native  <productname>PostgreSQL</productname>  type  for variable length
   ASCII strings.  The type of the attribute population is
d968 1
a968 1
     be error prone and is also in violation of the SQL standard. Under the old
d1184 2
a1185 1
    <command>ALTER TABLE</command> command.
d1197 2
a1198 1
   <command>GRANT</command> reference page.  The following sections
d1459 2
a1460 2
    the current user is to be searched.  Since no such schema exists
    yet, this entry is ignored.  The second element refers to the
d1743 1
a1743 1
   restrict drops of objects that other objects depend on.
@


1.15
log
@Fix erroneous example, per Tim Knowles.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.14 2003/03/25 16:15:35 petere Exp $ -->
d821 2
a822 2
    These are explained in the <literal>CREATE TABLE</literal> entry
    in <xref linkend="reference">.
@


1.14
log
@Merge documentation into one book.  (Build with "make html".)  Replace
vague cross-references with real links.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.13 2003/03/13 01:30:28 petere Exp $ -->
d1540 1
a1540 1
REVOKE CREATE ON public FROM PUBLIC;
@


1.13
log
@Big editing for consistent content and presentation.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.12 2003/02/19 04:06:27 momjian Exp $ -->
d16 1
a16 1
  these topics is found in the &cite-programmer;.
d277 1
a277 1
    see the &cite-admin; for details.  However, it is
d822 1
a822 1
    in the &cite-reference;.
@


1.12
log
@This patch makes the following changes to the documentation:

- more work from the SGML police

- some grammar improvements: rewriting a paragraph or two, replacing
contractions where (IMHO) appropriate

- fix missing utility commands in lock mode docs

- improve CLUSTER, REINDEX, SET SESSION AUTHORIZATION ref pages

Neil Conway
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.11 2003/02/19 03:13:24 momjian Exp $ -->
d174 1
a174 1
      the table was created <literal>WITHOUT OIDS</literal>, in which
d176 1
a176 1
      <literal>oid</literal> (same name as the column); see <xref
d186 1
a186 1
      The OID of the table containing this row.  This attribute is
d224 1
a224 1
      zero for an undeleted tuple.  It is possible for this field to
d257 33
d292 1
a292 1
 <sect1>
d315 1
a315 1
    product_no integer PRIMARY KEY,
d1230 1
a1230 1
   <command>DROP</>, <command>GRANT</>, <command>REVOKE</>, etc)
d1250 1
a1250 1
   A <productname>PostgreSQL</productname> database cluster (installation)
d1572 1
a1572 1
    future version defines a system catalog named the same as your
d1574 2
a1575 2
    your table name would be resolved as the system catalog instead.)
    System catalogs will continue to follow the convention of having
d1717 2
a1718 1
<userinput>DROP TABLE products;</userinput>
@


1.11
log
@This patch includes more SGML markup fixes as well as a few minor
additions to the docs.

Neil Conway
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.10 2002/11/15 03:11:15 momjian Exp $ -->
d118 2
a119 2
   If you don't need a table anymore, you can remove it using the
   <literal>DROP TABLE</literal> command.  For example:
d721 1
a721 1
    don't relate to any products.  But what if a product is removed
d762 1
a762 1
    ACTION</literal> and it's also the default if you don't specify
d1605 1
a1605 1
    implementations don't allow you to create schemas that have a
d1689 1
a1689 1
   The error message contains a useful hint: If you don't want to
@


1.10
log
@SGML improvements.

Neil Conway
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.9 2002/11/11 20:14:02 petere Exp $ -->
d192 1
a192 1
      <classname>pg_class</classname> to obtain the table name.
d907 3
a909 3
   (If you try to reproduce this example, you will probably get different
   numeric OIDs.)  By doing a join with pg_class you can see the actual table
   names:
@


1.9
log
@Merge documentation updates from 7.3 branch.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.8 2002/10/24 21:10:58 tgl Exp $ -->
d1106 3
a1108 3
    PostgreSQL.  As a consequence, it is not an error to drop a
    default where one hadn't been defined, because the default is
    implicitly the null value.
d1612 2
a1613 2
    This is how PostgreSQL will effectively behave if you create a per-user
    schema for every user.
@


1.8
log
@Make link to schema inspection functions more clear.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.7 2002/10/24 17:48:54 petere Exp $ -->
d225 1
a225 1
      be nonzero in a visible tuple: that usually indicates that the
d356 1
a356 1
    To specify a named constraint, use the key word
d385 1
a385 1
    We say that the first two are column constraints, whereas the
d934 1
a934 1
     be error prone and is also in violation of SQL99. Under the old
d1612 1
a1612 1
    This is also supported by PostgreSQL if you create a per-user
d1696 2
a1697 2
   constraint.  (If you want to check what DROP ... CASCADE will do,
   run DROP without CASCADE and read the NOTICEs.)
@


1.8.2.1
log
@Cleanup pass over User's Guide.  Key word table updated.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.8 2002/10/24 21:10:58 tgl Exp $ -->
d225 1
a225 1
      be nonzero in a visible tuple: That usually indicates that the
d356 1
a356 1
    So, to specify a named constraint, use the key word
d385 1
a385 1
    We say that the first two constraints are column constraints, whereas the
d934 1
a934 1
     be error prone and is also in violation of the SQL standard. Under the old
d1612 1
a1612 1
    This is how PostgreSQL will effectively behave if you create a per-user
d1696 2
a1697 2
   constraint.  (If you want to check what <literal>DROP ... CASCADE</> will do,
   run <command>DROP</> without <literal>CASCADE</> and read the <literal>NOTICE</> messages.)
@


1.7
log
@Add introductory sections explaining what each book is about.  Remove Y2K
statement.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.6 2002/10/20 05:05:46 tgl Exp $ -->
d1465 1
a1465 1
    See also <xref linkend="set-search-path"> for other ways to access
@


1.6
log
@Update description of numeric constants to match 7.3 reality.
Miscellaneous other copy-editing.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.5 2002/09/21 18:32:52 petere Exp $ -->
d16 1
a16 1
  these topics is found in &cite-programmer;.
d789 1
a789 1
    in &cite-reference;.
@


1.5
log
@Add more appropriate markup.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.4 2002/09/12 22:05:35 petere Exp $ -->
d13 1
a13 1
  namespaces, and how privileges can be assigned to tables.  Finally,
d81 1
a81 1
   also identifiers, but there are some exceptions.  Note that the
d104 1
a104 1
    consistent naming patter for the tables and columns.  For
d290 1
a290 1
   The default value may be a scalar expression, which well be
d621 2
a622 1
    a group of columns) must match the values in some other column.
d762 1
a762 1
    ACTON</literal> and it's also the default if you don't specify
d985 1
a985 1
     <para>Remove a column,</para>
d997 1
a997 1
     <para>Rename a column,</para>
d1000 1
a1000 1
     <para>Rename the table.</para>
d1274 1
a1274 1
   but schemas cannot be nested.
d1345 1
a1345 1
CREATE SCHEMA <replaceable>schemaname</replaceable> AUTHORIZATON <replaceable>username</replaceable>;
d1363 3
a1365 3
    schema names.  Those 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:
d1554 1
a1554 1
    a few usage patterns are recommended and are easily supported by
d1562 1
a1562 1
       recommended when there is only a single user or few cooperating
d1590 1
a1590 1
       then refer to these additional object by qualifying the names
d1694 1
a1694 1
   and all the dependent objects will be removed.  Actually, this
d1696 2
a1697 1
   constraint.
d1714 2
a1715 1
    the defaults might be different.
d1724 2
a1725 1
    upgrade process.  All other dependency types survive the upgrade.
@


1.4
log
@Add more information about schemas.  Combines some previously existing
material into the new location.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.3 2002/09/05 21:32:23 petere Exp $ -->
d768 1
a768 1
    deletion of the primary key wil fail.
d1428 1
a1428 1
    The first schema in the seach path that exists is the default
d1469 2
a1470 2
    The search path works in the same way for datatype names, function names,
    and operator names as it does for table names.  Datatype and function
d1522 1
a1522 1
    the system tables and all the built-in datatypes, functions, and
@


1.3
log
@Fill in section on table modification.
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.2 2002/08/28 20:17:44 momjian Exp $ -->
d145 114
d1133 70
d1207 422
a1628 1
  <comment>to be filled in</comment>
@


1.2
log
@Add mention of foreign key dependency and SERIAL in 7.2 data restores.

Note can probably be removed after a couple of releases.

Rod Taylor
@
text
@d1 1
a1 1
<!-- $Header: /cvsroot/pgsql-server/doc/src/sgml/ddl.sgml,v 1.1 2002/08/05 19:44:57 petere Exp $ -->
d154 1
a154 1
   (Details about data manipulation commands are in the next chapter.)
d266 1
a266 1
    column list.  In general, column definitions and constraint
d302 4
a305 2
    check expression evaluates to true or the null value.  To ensure
    that a column does not contain null values, the not-null
d327 7
a333 6
    not-null constraint is 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 cannot give explicit names to not-null
    constraints created that way.
d570 2
a571 2
    Of course, the number and type of constrained columns needs to
    match the number and type of referenced columns.
d853 8
a860 7
   When you create a table and you realize that you made a mistake,
   then you can drop the 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> provides a family of commands
   to make modifications on existing tables.
d870 3
d889 2
a890 10
   In the current implementation you cannot
   <itemizedlist spacing="compact">
    <listitem>
     <para>Remove a column,</para>
    </listitem>
    <listitem>
     <para>Change the data type of a column.</para>
    </listitem>
   </itemizedlist>
   These may be possible in a future release.
d893 125
a1017 4
  <comment>
   OK, now explain how to do this.  There's currently so much activity
   on <literal>ALTER TABLE</literal> that I'm holding off a bit.
  </comment>
d1113 4
a1116 4
    Foreign Key constraint dependencies and SERIAL dependencies from
    <productname>PostgreSQL</productname> versions prior to 7.3 are
    <emphasis>not</emphasis> maintained or created during the upgrade
    process.  However, all other dependency types are created successfully.
@


1.1
log
@Forgot to add/remove files.
@
text
@d1 1
a1 1
<!-- $Header$ -->
d988 9
@
