<HTML ><HEAD ><TITLE >Constraints</TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.73 "><LINK REV="MADE" HREF="mailto:pgsql-docs@postgresql.org"><LINK REL="HOME" TITLE="PostgreSQL 7.3.2 Documentation" HREF="index.html"><LINK REL="UP" TITLE="Data Definition" HREF="ddl.html"><LINK REL="PREVIOUS" TITLE="Default Values" HREF="x1779.html"><LINK REL="NEXT" TITLE="Inheritance" HREF="ddl-inherit.html"><LINK REL="STYLESHEET" TYPE="text/css" HREF="stylesheet.css"><META NAME="creation" CONTENT="2003-02-03T20:17:34"></HEAD ><BODY CLASS="SECT1" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#840084" ALINK="#0000FF" ><DIV CLASS="NAVHEADER" ><TABLE SUMMARY="Header navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TH COLSPAN="3" ALIGN="center" >PostgreSQL 7.3.2 Documentation</TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="bottom" ><A HREF="x1779.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="80%" ALIGN="center" VALIGN="bottom" >Chapter 2. Data Definition</TD ><TD WIDTH="10%" ALIGN="right" VALIGN="bottom" ><A HREF="ddl-inherit.html" ACCESSKEY="N" >Next</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="SECT1" ><H1 CLASS="SECT1" ><A NAME="DDL-CONSTRAINTS" >2.4. Constraints</A ></H1 ><P > 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 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 only be one row for each product number. </P ><P > 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. </P ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN1793" >2.4.1. Check Constraints</A ></H2 ><P > A check constraint is the most generic constraint type. It allows 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: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer, name text, price numeric <B CLASS="EMPHASIS" >CHECK (price > 0)</B > );</PRE ><P> </P ><P > 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 <TT CLASS="LITERAL" >CHECK</TT > 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. </P ><P > 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: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer, name text, price numeric <B CLASS="EMPHASIS" >CONSTRAINT positive_price</B > CHECK (price > 0) );</PRE ><P> So, to specify a named constraint, use the key word <TT CLASS="LITERAL" >CONSTRAINT</TT > followed by an identifier followed by the constraint definition. </P ><P > 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. </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer, name text, price numeric CHECK (price > 0), discounted_price numeric CHECK (discounted_price > 0), CHECK (price > discounted_price) );</PRE ><P> </P ><P > 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. </P ><P > We say that the first two constraints are column constraints, whereas the third one is a table constraint because it is written separately from the column definitions. Column constraints can also be written as table constraints, while the reverse is not necessarily possible. The above example could also be written as </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer, name text, price numeric, CHECK (price > 0), discounted_price numeric, CHECK (discounted_price > 0), CHECK (price > discounted_price) );</PRE ><P> or even </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer, name text, price numeric CHECK (price > 0), discounted_price numeric, CHECK (discounted_price > 0 AND price > discounted_price) );</PRE ><P> It's a matter of taste. </P ><P > 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 one 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 should be used. </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN1811" >2.4.2. Not-Null Constraints</A ></H2 ><P > A not-null constraint simply specifies that a column must not assume the null value. A syntax example: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer <B CLASS="EMPHASIS" >NOT NULL</B >, name text <B CLASS="EMPHASIS" >NOT NULL</B >, price numeric );</PRE ><P> </P ><P > A not-null constraint is always written as a column constraint. A not-null constraint is functionally equivalent to creating a check constraint <TT CLASS="LITERAL" >CHECK (<TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > IS NOT NULL)</TT >, but in <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > 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. </P ><P > Of course, a column can have more than one constraint. Just write the constraints after one another: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer NOT NULL, name text NOT NULL, price numeric NOT NULL CHECK (price > 0) );</PRE ><P> The order doesn't matter. It does not necessarily affect in which order the constraints are checked. </P ><P > The <TT CLASS="LITERAL" >NOT NULL</TT > constraint has an inverse: the <TT CLASS="LITERAL" >NULL</TT > constraint. This does not mean that the column must be null, which would surely be useless. Instead, this simply defines the default behavior that the column may be null. The <TT CLASS="LITERAL" >NULL</TT > constraint is not defined in the SQL standard and should not be used in portable applications. (It was only added to <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > to be compatible with 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 </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer NULL, name text NULL, price numeric NULL );</PRE ><P> and then insert the <TT CLASS="LITERAL" >NOT</TT > key word where desired. </P ><DIV CLASS="TIP" ><BLOCKQUOTE CLASS="TIP" ><P ><B >Tip: </B > In most database designs the majority of columns should be marked not null. </P ></BLOCKQUOTE ></DIV ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN1832" >2.4.3. Unique Constraints</A ></H2 ><P > 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 </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer <B CLASS="EMPHASIS" >UNIQUE</B >, name text, price numeric );</PRE ><P> when written as a column constraint, and </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer, name text, price numeric, <B CLASS="EMPHASIS" >UNIQUE (product_no)</B > );</PRE ><P> when written as a table constraint. </P ><P > If a unique constraint refers to a group of columns, the columns are listed separated by commas: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE example ( a integer, b integer, c integer, <B CLASS="EMPHASIS" >UNIQUE (a, c)</B > );</PRE ><P> </P ><P > It is also possible to assign names to unique constraints: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer <B CLASS="EMPHASIS" >CONSTRAINT must_be_different</B > UNIQUE, name text, price numeric );</PRE ><P> </P ><P > 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. However, null values are not considered equal in this consideration. That means, in the presence of a multicolumn unique constraint it is possible to store an unlimited number of rows that contain a null value in at least one of the constrained columns. This behavior conforms to the SQL standard, but we have heard that other SQL databases may not follow this rule. So be careful when developing applications that are intended to be portable. </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="AEN1846" >2.4.4. Primary Keys</A ></H2 ><P > 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: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer UNIQUE NOT NULL, name text, price numeric );</PRE ><P> </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer <B CLASS="EMPHASIS" >PRIMARY KEY</B >, name text, price numeric );</PRE ><P> </P ><P > Primary keys can also constrain more than one column; the syntax is similar to unique constraints: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE example ( a integer, b integer, c integer, <B CLASS="EMPHASIS" >PRIMARY KEY (a, c)</B > );</PRE ><P> </P ><P > 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, in fact, 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. </P ><P > A table can have at most one primary key (while it can have many unique and not-null constraints). Relational database theory dictates that every table must have a primary key. This rule is not enforced by <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN >, but it is usually best to follow it. </P ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="DDL-CONSTRAINTS-FK" >2.4.5. Foreign Keys</A ></H2 ><P > 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 <I CLASS="FIRSTTERM" >referential integrity</I > between two related tables. </P ><P > Say you have the product table that we have used several times already: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE products ( product_no integer PRIMARY KEY, name text, price numeric );</PRE ><P> 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: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE orders ( order_id integer PRIMARY KEY, product_no integer <B CLASS="EMPHASIS" >REFERENCES products (product_no)</B >, quantity integer );</PRE ><P> Now it is impossible to create orders with <TT CLASS="LITERAL" >product_no</TT > entries that do not appear in the products table. </P ><P > We say that in this situation the orders table is the <I CLASS="FIRSTTERM" >referencing</I > table and the products table is the <I CLASS="FIRSTTERM" >referenced</I > table. Similarly, there are referencing and referenced columns. </P ><P > You can also shorten the above command to </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE orders ( order_id integer PRIMARY KEY, product_no integer REFERENCES products, quantity integer );</PRE ><P> because in absence of a column list the primary key of the referenced table is used as referenced column. </P ><P > 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: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE t1 ( a integer PRIMARY KEY, b integer, c integer, <B CLASS="EMPHASIS" >FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)</B > );</PRE ><P> Of course, the number and type of the constrained columns needs to match the number and type of the referenced columns. </P ><P > 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: </P><PRE CLASS="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) );</PRE ><P> Note also that the primary key overlaps with the foreign keys in the last table. </P ><P > We know that the foreign keys disallow creation of orders that don't relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to specify that as well. Intuitively, we have a few options: <P ></P ></P><UL COMPACT="COMPACT" ><LI ><P >Disallow deleting a referenced product</P ></LI ><LI ><P >Delete the orders as well</P ></LI ><LI ><P >Something else?</P ></LI ></UL ><P> </P ><P > 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 <TT CLASS="LITERAL" >order_items</TT >), we disallow it. If someone removes an order, the order items are removed as well. </P><PRE CLASS="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 <B CLASS="EMPHASIS" >ON DELETE RESTRICT</B >, order_id integer REFERENCES orders <B CLASS="EMPHASIS" >ON DELETE CASCADE</B >, quantity integer, PRIMARY KEY (product_no, order_id) );</PRE ><P> </P ><P > Restricting and cascading deletes are the two most common options. <TT CLASS="LITERAL" >RESTRICT</TT > can also be written as <TT CLASS="LITERAL" >NO ACTION</TT > and it's also the default if you don't specify anything. There are two other options for what should happen with the foreign key columns when a primary key is deleted: <TT CLASS="LITERAL" >SET NULL</TT > and <TT CLASS="LITERAL" >SET DEFAULT</TT >. Note that these do not excuse you from observing any constraints. For example, if an action specifies <TT CLASS="LITERAL" >SET DEFAULT</TT > but the default value would not satisfy the foreign key, the deletion of the primary key will fail. </P ><P > Analogous to <TT CLASS="LITERAL" >ON DELETE</TT > there is also <TT CLASS="LITERAL" >ON UPDATE</TT > which is invoked when a primary key is changed (updated). The possible actions are the same. </P ><P > More information about updating and deleting data is in <A HREF="dml.html" >Chapter 3</A >. </P ><P > Finally, we should mention that a foreign key must reference columns that are either 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 <TT CLASS="LITERAL" >CREATE TABLE</TT > entry in the <A HREF="reference.html" ><I >PostgreSQL 7.3.2 Reference Manual</I ></A >. </P ></DIV ></DIV ><DIV CLASS="NAVFOOTER" ><HR ALIGN="LEFT" WIDTH="100%"><TABLE SUMMARY="Footer navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" ><A HREF="x1779.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="index.html" ACCESSKEY="H" >Home</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A HREF="ddl-inherit.html" ACCESSKEY="N" >Next</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >Default Values</TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="ddl.html" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >Inheritance</TD ></TR ></TABLE ></DIV ></BODY ></HTML >