<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title> Practical PostgreSQL</title> <meta name="keywords" content="postgresql, support, recovery, design, software, hosting, expterise, programming, postgres, pgsql, replication, mysql, firebird, database, sql, free, open source, software" /> <meta name="description" content="Command Prompt, Inc. is the largest and oldest US based commercial PostgreSQL support provider. We provide the only commercially viable integrated PostgreSQL replication solution, but also custom programming, and support. We authored the book Practical PostgreSQL, the procedural language plPHP, and adding trigger capability to plPerl. " /> <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" href="../css/layout.css" /> <link rel="stylesheet" type="text/css" href="../css/cmd4.css" /> <script language="javascript" type="text/javascript"><!-- greymenuhomewideLit = new Image(); greymenuhomewideLit.src = "/images/greymenu_homewide_lit.gif"; greymenuaboutLit = new Image(); greymenuaboutLit.src = "/images/greymenu_about_lit.gif"; greymenuproductsLit = new Image(); greymenuproductsLit.src = "/images/greymenu_products_lit.gif"; greymenuservicesLit = new Image(); greymenuservicesLit.src = "/images/greymenu_services_lit.gif"; greymenusupportLit = new Image(); greymenusupportLit.src = "/images/greymenu_support_lit.gif"; greymenucommunityLit = new Image(); greymenucommunityLit.src = "/images/greymenu_community_lit.gif"; //--></script> </head> <body> <div align="center"> <div id="widecontainer"> <div id="widetop"> <div class="throwleft" style="width: 300px; text-align: left;"><a href="http://www.commandprompt.com/"><img src="../images/cmd4logo_wide.gif" border="0" alt="Command Prompt, Inc." /></a></div> <div class="throwright" style="width: 400px; text-align: right;"> <div id="topright"> <form action="index.html" name="cmdform" method="post"> <ul> <li><input type="text" name="search" value="" /></li> <li><input type="submit" name="action" value="Search Book" /></li> </ul> </form> </div> </div> </div> <ul id="greymenu_wide"> <li><a href="http://www.commandprompt.com/home/"><img onmouseover="this.src = greymenuhomewideLit.src;" onmouseout="this.src = '/images/greymenu_homewide.gif';" src="../images/greymenu_homewide.gif" border="0" height="22" title="" alt="" /></a></li><li><img src="../images/greymenu_divider.gif" border="0" width="2" height="22" alt="|" /></li><li><a href="http://www.commandprompt.com/about/"><img onmouseover="this.src = greymenuaboutLit.src;" onmouseout="this.src = '/images/greymenu_about.gif';" src="../images/greymenu_about.gif" border="0" height="22" title="" alt="" /></a></li><li><img src="../images/greymenu_divider.gif" border="0" width="2" height="22" alt="|" /></li><li><a href="http://www.commandprompt.com/products/"><img onmouseover="this.src = greymenuproductsLit.src;" onmouseout="this.src = '/images/greymenu_products.gif';" src="../images/greymenu_products.gif" border="0" height="22" title="" alt="" /></a></li><li><img src="../images/greymenu_divider.gif" border="0" width="2" height="22" alt="|" /></li><li><a href="http://www.commandprompt.com/services/"><img onmouseover="this.src = greymenuservicesLit.src;" onmouseout="this.src = '/images/greymenu_services.gif';" src="../images/greymenu_services.gif" border="0" height="22" title="" alt="" /></a></li><li><img src="../images/greymenu_divider.gif" border="0" width="2" height="22" alt="|" /></li><li><a href="http://www.commandprompt.com/support/"><img onmouseover="this.src = greymenusupportLit.src;" onmouseout="this.src = '/images/greymenu_support.gif';" src="../images/greymenu_support.gif" border="0" height="22" title="" alt="" /></a></li><li><img src="../images/greymenu_divider.gif" border="0" width="2" height="22" alt="|" /></li><li><a href="http://www.commandprompt.com/community/"><img onmouseover="this.src = greymenucommunityLit.src;" onmouseout="this.src = '/images/greymenu_community.gif';" src="../images/greymenu_community.gif" border="0" height="22" title="" alt="" /></a></li> </ul> <div style="padding-left: 16px; width: 96%;"> <HTML ><HEAD ><TITLE >Using Tables</TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.72 "><LINK REL="HOME" TITLE="Practical PostgreSQL" href="book1"><LINK REL="UP" TITLE="Using SQL with PostgreSQL" href="c4890"><LINK REL="PREVIOUS" TITLE="Using SQL with PostgreSQL" href="c4890"><LINK REL="NEXT" TITLE="Adding Data with INSERT and COPY" href="x5504"></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" >Practical PostgreSQL</TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="bottom" ><A href="c4890" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="80%" ALIGN="center" VALIGN="bottom" >Chapter 4. Using SQL with PostgreSQL</TD ><TD WIDTH="10%" ALIGN="right" VALIGN="bottom" ><A href="x5504" ACCESSKEY="N" >Next</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="SECT1" ><H1 CLASS="SECT1" ><A NAME="USINGTABLES" >Using Tables</A ></H1 ><P >Tables are the fundamental building blocks with which to store data within your database. Before you can begin to add, retrieve, or modify data within your database, you will first have to construct your tables to house that data.</P ><P >This section covers how to create, modify and destroy tables, using the <TT CLASS="LITERAL" >CREATE TABLE</TT >, <TT CLASS="LITERAL" >ALTER TABLE</TT >, and <TT CLASS="LITERAL" >DROP TABLE</TT > SQL commands. (If you need information about creating a database within which to work, see <A href="c16573" >Chapter 9</A >.)</P ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="CREATINGTABLES" >Creating Tables with CREATE TABLE</A ></H2 ><P >The SQL command to create a table is <TT CLASS="LITERAL" >CREATE TABLE</TT >. This command requires, at a minimum, the name for the new table and a description for each column, which consists of the column name and data type. The <TT CLASS="LITERAL" >CREATE TABLE</TT > command accepts several optional parameters: <SPAN ><I CLASS="EMPHASIS" >column constraints</I ></SPAN > (rules on what data is or is not allowed within a column), and <SPAN ><I CLASS="EMPHASIS" >table constraints</I ></SPAN > (general limitations and relationships defined on the table itself).</P ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5042" >CREATE TABLE syntax</A ></H3 ><P > The following is the syntax for <TT CLASS="LITERAL" >CREATE TABLE</TT > with a detailed explanation of the terms used: </P ><PRE CLASS="SCREEN" > CREATE [ TEMPORARY | TEMP ] TABLE <TT CLASS="REPLACEABLE" ><I >table_name</I ></TT > ( { <TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > <TT CLASS="REPLACEABLE" ><I >type</I ></TT > [ <TT CLASS="REPLACEABLE" ><I >column_constraint</I ></TT > [ ... ] ] | <TT CLASS="REPLACEABLE" ><I >table_constraint</I ></TT > } [, ... ] ) [ INHERITS ( <TT CLASS="REPLACEABLE" ><I >inherited_table</I ></TT > [, ... ] ) ]</PRE ><P ></P ><DIV CLASS="VARIABLELIST" ><DL ><DT ><TT CLASS="LITERAL" >TEMPORARY | TEMP</TT ></DT ><DD ><P >The <TT CLASS="LITERAL" >TEMPORARY</TT > or <TT CLASS="LITERAL" >TEMP</TT > SQL keyword causes the created table to be automatically destroyed at the end of the active session to PostgreSQL. A temporary table may have the same name as an existing table, and until the temporary table is destroyed, any references to that table name will utilize the temporary table. Any indices placed on this table are temporary and will be destroyed in the same fashion at the end of the session.</P ></DD ><DT ><TT CLASS="REPLACEABLE" ><I >table_name</I ></TT ></DT ><DD ><P > <TT CLASS="REPLACEABLE" ><I >table_name</I ></TT > identifies your table's name (once created). </P ></DD ><DT ><TT CLASS="LITERAL" ><TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > <TT CLASS="REPLACEABLE" ><I >type</I ></TT > [ <TT CLASS="REPLACEABLE" ><I >column_constraint</I ></TT > ] | <TT CLASS="REPLACEABLE" ><I >table_constraint</I ></TT ></TT ></DT ><DD ><P >Each table column and table constraint is defined within the parentheses following the table name, separated by commas. Column definitions must contain a valid identifier for a <TT CLASS="REPLACEABLE" ><I >column_name</I ></TT >, followed by a valid data <TT CLASS="REPLACEABLE" ><I >type</I ></TT >, and may optionally include a <TT CLASS="REPLACEABLE" ><I >column_constraint</I ></TT >. The requirements of column constraint definitions are dependent on the constraints, described in <A href="x13546#CONSTRAINTS" >the Section called <I >Using Constraints</I > in Chapter 7</A >" in <A href="c13329" >Chapter 7</A >. Table constraints and columns may be mixed in this grouped list, though it is common practice to list columns first, followed by any table constraints. </P ></DD ><DT ><TT CLASS="LITERAL" >[, ... ]</TT ></DT ><DD ><P >Each column definition may be followed by a comma in order to define a subsequent column after it. The ellipses denote that you may enter as many columns as you wish (up to the limit of 1,600). Be sure that you do not follow the last column or constraint in the list with a comma, as is allowed in languages like Perl; this will cause a parsing error. </P ></DD ><DT ><TT CLASS="LITERAL" >INHERITS ( <TT CLASS="REPLACEABLE" ><I >inherited_table</I ></TT > [, ...] )</TT ></DT ><DD ><P >The object-relational capabilities of PostgreSQL allow you to specify one or more tables (in a grouped, comma-delimited list) from which your table will <SPAN ><I CLASS="EMPHASIS" >inherit</I ></SPAN >. This optional specification creates an implied parent-child relationship between tables. This relatively new technique to RDBMSs is discussed in more detail in <A href="x13546#INHERITANCE" >the Section called <I >Inheritance</I > in Chapter 7</A >" within <A href="c13329" >Chapter 7</A >. </P ></DD ></DL ></DIV ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B >The terms <TT CLASS="REPLACEABLE" ><I >column_constraint</I ></TT > and <TT CLASS="REPLACEABLE" ><I >table_constraint</I ></TT > in the above syntax definition refer to sets of potentially complex constraint definitions. The syntax for these various constraints is listed in detail in <A href="x13546#CONSTRAINTS" >the Section called <I >Using Constraints</I > in Chapter 7</A >" within <A href="c13329" >Chapter 7</A >.</P ></BLOCKQUOTE ></DIV ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="CREATINGANEXAMPLETABLE" >Creating an example table</A ></H3 ><P ><A href="x5021#CREATINGTHEBOOKSTABLE" >Example 4-6</A > demonstrates the syntax to create Book Town's <TT CLASS="LITERAL" >books</TT > table.</P ><DIV CLASS="EXAMPLE" ><A NAME="CREATINGTHEBOOKSTABLE" ></A ><P ><B >Example 4-6. Creating the books table</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >CREATE TABLE books (</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > id integer UNIQUE,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > title text NOT NULL,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > author_id integer,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > subject_id integer,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > CONSTRAINT books_id_pkey PRIMARY KEY (id));</B ></TT > NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'books_id_pkey' for table 'books' CREATE</PRE ></DIV ><P >The <TT CLASS="LITERAL" >CREATE</TT > output following the execution of the statement indicates that the table was successfully created. If you receive an error message, check your punctuation and spelling to make sure you have entered the correct syntax. Receiving no message at all means that you probably left open a quote, parenthesis, or other special character symbol.</P ><P >Additionally, the <TT CLASS="LITERAL" >NOTICE</TT > statement serves to inform you that in order to properly complete the creation of this table as described, an implicit index called <TT CLASS="LITERAL" >books_ id_ pkey</TT > will be created.</P ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="EXAMININGACREATEDTABLE" >Examining a created table</A ></H3 ><P >Once created, you may use the <TT CLASS="LITERAL" >\d</TT > describe command (followed by the table name) within <SPAN ><I CLASS="EMPHASIS" >psql</I ></SPAN > to display the structure of the table and its constraints (if any). <A href="x5021#SLASHDCOMMANDOUTPUT" >Example 4-7</A > shows the output of <TT CLASS="LITERAL" >\d</TT > when it is used to describe the <TT CLASS="LITERAL" >books</TT > table created in the last section. </P ><P >Notice that this format does not show actual row data, but instead places each column and its attributes in its own <SPAN ><I CLASS="EMPHASIS" >row</I ></SPAN >, essentially turning the table on its side. This is done for the sake of clarity, as many tables can grow too large to fit on a screen (or on a page) horizontally. We'll use this format throughout the book when examining table structure without data.</P ><DIV CLASS="EXAMPLE" ><A NAME="SLASHDCOMMANDOUTPUT" ></A ><P ><B >Example 4-7. The \d command's output</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B > \d books</B ></TT > Table "books" Attribute | Type | Modifier ------------+---------+---------- id | integer | not null title | text | not null author_id | integer | subject_id | integer | Index: books_id_pkey</PRE ></DIV ><P > The following list provides a more detailed explanation of the fields and terms shown in <A href="x5021#SLASHDCOMMANDOUTPUT" >Example 4-7</A >: </P ><P > <P ></P ><DIV CLASS="VARIABLELIST" ><DL ><DT ><TT CLASS="LITERAL" >id</TT ></DT ><DD ><P >The <TT CLASS="LITERAL" >id</TT > column is a numeric identifier unique to each book. It is defined as being of the data type <TT CLASS="LITERAL" >integer</TT >, and has on it the following constraints: <P ></P ><DIV CLASS="VARIABLELIST" ><DL ><DT ><TT CLASS="LITERAL" >UNIQUE</TT ></DT ><DD ><P >This constraint ensures that the column always has a unique value. A column with the <TT CLASS="LITERAL" >UNIQUE</TT > constraint set may ordinarily contain empty (<TT CLASS="LITERAL" >NULL</TT > values, but any attempt to insert duplicate values will fail. The <TT CLASS="LITERAL" >id</TT > column is also designed to be used as the <TT CLASS="LITERAL" >PRIMARY KEY</TT >. </P ></DD ><DT ><TT CLASS="LITERAL" >PRIMARY KEY</TT ></DT ><DD ><P >While not displayed in the <TT CLASS="LITERAL" >\d</TT > breakdown, you can see in our original <TT CLASS="LITERAL" >CREATE TABLE</TT > statement that this table's primary key is defined on the <TT CLASS="LITERAL" >id</TT > column. Placing the constraint of <TT CLASS="LITERAL" >PRIMARY KEY</TT > on a column implicitly sets both the <TT CLASS="LITERAL" >NOT NULL</TT > and <TT CLASS="LITERAL" >UNIQUE</TT > constraints as well.</P ></DD ><DT ><TT CLASS="LITERAL" >NOT NULL</TT ></DT ><DD ><P > This constraint is set automatically by setting the <TT CLASS="LITERAL" >PRIMARY KEY</TT > constraint. It ensures that the ID column always has a value. Data for this column can never be empty, and any attempt to insert <TT CLASS="LITERAL" >NULL</TT > values will fail. </P ></DD ></DL ></DIV > </P ></DD ><DT ><TT CLASS="LITERAL" >title</TT ></DT ><DD ><P >The <TT CLASS="LITERAL" >title</TT > column of the table must contain character strings of type <TT CLASS="LITERAL" >text</TT >. The <TT CLASS="LITERAL" >text</TT > type is more flexible than <TT CLASS="LITERAL" >varchar</TT >, and is a good choice for this column as it does not require that you specify the maximum number of characters allowed. This column has the <TT CLASS="LITERAL" >NOT NULL</TT > constraint set, indicating that a row's title column cannot ever be set to <TT CLASS="LITERAL" >NULL</TT >. </P ></DD ><DT ><TT CLASS="LITERAL" >author_id</TT ></DT ><DD ><P >The <TT CLASS="LITERAL" >author_id</TT > column must contain values of type <TT CLASS="LITERAL" >integer</TT >, and relates to the <TT CLASS="LITERAL" >authors</TT > table. There are no constraints placed on this column, as sometimes an author may not be known for a title (making <TT CLASS="LITERAL" >NOT NULL</TT > inappropriate), and an author may show up more than once (making <TT CLASS="LITERAL" >UNIQUE</TT > inappropriate as well).</P ></DD ><DT ><TT CLASS="LITERAL" >subject_id</TT ></DT ><DD ><P >The <TT CLASS="LITERAL" >subject_id</TT > is similar to the <TT CLASS="LITERAL" >author_id</TT > column, as it may contain values of type <TT CLASS="LITERAL" >integer</TT >, and relates to the <TT CLASS="LITERAL" >subjects</TT > table. Again, there are no constraints on the contents of this column, as many books may be uncategorized, or fall under the same subject.</P ></DD ></DL ></DIV > </P ><P >While a table's structure can be modified after it has been created, the available modifications are limited. These include, for example, renaming the table, renaming its columns, and adding new columns. PostgreSQL 7.1.x does not support dropping columns from a table. It is therefore good practice to thoughtfully and carefully plan your table structures before creating them.</P ></DIV ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="ALTERINGTABLES" >Altering Tables with ALTER TABLE</A ></H2 ><P >Most mature RDBMSs allow you to alter the properties of existing tables via the <TT CLASS="LITERAL" >ALTER TABLE</TT > command. The PostgreSQL implementation of <TT CLASS="LITERAL" >ALTER TABLE</TT > allows for six total types of table modifications as of version 7.1.x: <P ></P ><UL ><LI ><P >Adding columns</P ></LI ><LI ><P >Setting and removing default column values</P ></LI ><LI ><P >Renaming the table</P ></LI ><LI ><P >Renaming columns</P ></LI ><LI ><P >Adding constraints</P ></LI ><LI ><P >Changing ownership</P ></LI ></UL > </P ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="ADDINGCOLUMNS" >Adding columns</A ></H3 ><P > You can add a new column to a table using the <TT CLASS="LITERAL" >ALTER TABLE</TT > command's <TT CLASS="LITERAL" >ADD COLUMN</TT > clause. Here is the syntax for the <TT CLASS="LITERAL" >ALTER TABLE</TT > command's <TT CLASS="LITERAL" >ADD COLUMN</TT > clause: </P ><PRE CLASS="SCREEN" > ALTER TABLE <TT CLASS="REPLACEABLE" ><I >table</I ></TT > ADD [ COLUMN ] <TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > <TT CLASS="REPLACEABLE" ><I >column_type</I ></TT ></PRE ><P > <P ></P ><DIV CLASS="VARIABLELIST" ><DL ><DT ><TT CLASS="REPLACEABLE" ><I >table_name</I ></TT ></DT ><DD ><P >The name of the table to modify.</P ></DD ><DT ><TT CLASS="REPLACEABLE" ><I >column_name</I ></TT ></DT ><DD ><P >The name of the column to add.</P ></DD ><DT ><TT CLASS="REPLACEABLE" ><I >column_type</I ></TT ></DT ><DD ><P >The data type of the new column.</P ></DD ></DL ></DIV > </P ><P >Technically, the <TT CLASS="LITERAL" >COLUMN</TT > keyword may be omitted; it is considered a noise term and is only useful for your own readability.</P ><P >As an example of adding a column, imagine that an industrious employee at Book Town decides that the <TT CLASS="LITERAL" >books</TT > table requires another column, specifically, a date column to represent the publication date. <A href="x5021#ADDINGACOLUMN" >Example 4-8</A > demonstrates such a procedure. </P ><DIV CLASS="EXAMPLE" ><A NAME="ADDINGACOLUMN" ></A ><P ><B >Example 4-8. Adding a column</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE books</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > ADD publication date;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >\d books</B ></TT > Table "books" Attribute | Type | Modifier -------------+---------+---------- id | integer | not null title | text | not null author_id | integer | subject_id | integer | publication | date | Index: books_id_pkey</PRE ></DIV ><P ><A href="x5021#ADDINGACOLUMN" >Example 4-8</A > successfully adds a new column to Book Town's <TT CLASS="LITERAL" >books</TT > table with the name of <TT CLASS="LITERAL" >publication</TT >, and a data type of <TT CLASS="LITERAL" >date</TT >. It also demonstrates a pitfall of uncoordinated table design among developers: in our examples, the Book Town <TT CLASS="LITERAL" >editions</TT > table already stores the publication date, so the column should not have been added to the <TT CLASS="LITERAL" >books</TT > table. See <A href="x5021#RESTRUCTURINGTABLES" >the Section called <I >Restructuring Existing Tables</I ></A >" for information on how to restructure a table after such a mistake has been made. </P ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5278" >Setting and removing default values</A ></H3 ><P >The most flexible table modification pertains to the default values of columns. These values may be both set and removed from a column with relative ease via the <TT CLASS="LITERAL" >ALTER TABLE</TT > command's <TT CLASS="LITERAL" >ALTER COLUMN</TT > clause.</P ><P >The following syntax passed to PostgreSQL describes how to use <TT CLASS="LITERAL" >ALTER TABLE</TT > in order to either set, or remove a default value of <TT CLASS="REPLACEABLE" ><I >value</I ></TT > from a column named <TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > :</P ><PRE CLASS="SCREEN" > ALTER TABLE <TT CLASS="REPLACEABLE" ><I >table</I ></TT > ALTER [ COLUMN ] <TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > { SET DEFAULT <TT CLASS="REPLACEABLE" ><I >value</I ></TT > | DROP DEFAULT }</PRE ><P >Again, the <TT CLASS="LITERAL" >COLUMN</TT > keyword is considered noise, and is an optional term used only for improved readability of the statement. <A href="x5021#ALTERINGCOLUMNDEFAULTS" >Example 4-9</A > demonstrates setting and dropping a simple default sequence value on the <TT CLASS="LITERAL" >books</TT > table's <TT CLASS="LITERAL" >id</TT > column.</P ><DIV CLASS="EXAMPLE" ><A NAME="ALTERINGCOLUMNDEFAULTS" ></A ><P ><B >Example 4-9. Altering column defaults</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE books</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > ALTER COLUMN id</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > SET DEFAULT nextval('book_ids');</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >\d books</B ></TT > Table "books" Attribute | Type | Modifier ------------+---------+-------------------------------------------- id | integer | not null default nextval('book_ids'::text) title | text | not null author_id | integer | subject_id | integer | Index: books_id_pkey booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE books</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > ALTER id</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > DROP DEFAULT;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >\d books</B ></TT > Table "books" Attribute | Type | Modifier ------------+---------+---------- id | integer | not null title | text | not null author_id | integer | subject_id | integer | Index: books_id_pkey</PRE ></DIV ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5307" >Renaming a table</A ></H3 ><P > A table may be safely renamed by passing the <TT CLASS="LITERAL" >RENAME</TT > clause with the <TT CLASS="LITERAL" >ALTER TABLE</TT > command. The following is the syntax to rename a table: </P ><PRE CLASS="SCREEN" > ALTER TABLE <TT CLASS="REPLACEABLE" ><I >table</I ></TT > RENAME TO <TT CLASS="REPLACEABLE" ><I >new_table</I ></TT ></PRE ><P >A table may be arbitrarily renamed as many times as you like without affecting the data. This could, of course, be a dangerous thing to do if you are dealing with a table on which an external application relies.</P ><DIV CLASS="EXAMPLE" ><A NAME="RENAMINGATABLE" ></A ><P ><B >Example 4-10. Renaming a table</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE books RENAME TO literature;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE literature RENAME TO books;</B ></TT > ALTER</PRE ></DIV ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5321" >Renaming columns</A ></H3 ><P >A table's columns may be safely renamed in PostgreSQL without modifying the data contained in the table. Renaming a column is a dangerous thing to do because existing applications may use explicit references to column names. If an existing program references a column by name and the column is renamed, the program could cease functioning correctly.</P ><P >The following syntax describes how to rename a column:</P ><PRE CLASS="SCREEN" > ALTER TABLE <TT CLASS="REPLACEABLE" ><I >table</I ></TT > RENAME [ COLUMN ] <TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > TO <TT CLASS="REPLACEABLE" ><I >new_column_name</I ></TT >;</PRE ><P >As with the other <TT CLASS="LITERAL" >ALTER TABLE</TT > commands, the <TT CLASS="LITERAL" >COLUMN</TT > keyword is considered noise, and may be optionally omitted. The existence of two identifiers separated by the <TT CLASS="LITERAL" >TO</TT > keyword provides enough information for PostgreSQL to determine that you are renaming a column, and not a table, as demonstrated in <A href="x5021#RENAMINGACOLUMN" >Example 4-11</A >.</P ><DIV CLASS="EXAMPLE" ><A NAME="RENAMINGACOLUMN" ></A ><P ><B >Example 4-11. Renaming a column</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >\d daily_inventory</B ></TT > Table "daily_inventory" Attribute | Type | Modifier -----------+---------+---------- isbn | text | in_stock | boolean | booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE daily_inventory</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > RENAME COLUMN in_stock TO is_in_stock;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE daily_inventory</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > RENAME is_in_stock TO is_stocked;</B ></TT > ALTER</PRE ></DIV ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5342" >Adding constraints</A ></H3 ><P >Constraints may be added in a limited fashion after a table has been created. As of PostgreSQL 7.1.x, only foreign key and check constraints may be added to an existing table column with <TT CLASS="LITERAL" >ALTER TABLE</TT >. The following is the syntax to add a constraint to a table:</P ><PRE CLASS="SCREEN" > ALTER TABLE <TT CLASS="REPLACEABLE" ><I >table</I ></TT > ADD CONSTRAINT <TT CLASS="REPLACEABLE" ><I >constraint_name</I ></TT > <TT CLASS="REPLACEABLE" ><I >constraint_definition</I ></TT ></PRE ><P >The syntax of the <TT CLASS="REPLACEABLE" ><I >constraint_definition</I ></TT > is dependent on the type of constraint you wish to add. As foreign keys and checks are the only supported constraints with the <TT CLASS="LITERAL" >ADD CONSTRAINT</TT > clause (as of PostgreSQL 7.1.x), the syntax for adding a foreign key to the <TT CLASS="LITERAL" >editions</TT > table (which references the <TT CLASS="LITERAL" >books</TT > table's <TT CLASS="LITERAL" >id</TT > column) and a check condition on the <TT CLASS="LITERAL" >type</TT > column is demonstrated in <A href="x5021#ADDINGACONSTRAINTTOATABLE" >Example 4-12</A >.</P ><DIV CLASS="EXAMPLE" ><A NAME="ADDINGACONSTRAINTTOATABLE" ></A ><P ><B >Example 4-12. Adding constraints to a table</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE editions</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > ADD CONSTRAINT foreign_book</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > FOREIGN KEY (book_id) REFERENCES books (id);</B ></TT > NOTICE: ALTER TABLE ... ADD CONSTRAINT will create implicit trigger(s) for FOREIGN KEY check(s) CREATE booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE editions</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > ADD CONSTRAINT hard_or_paper_back</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > CHECK (type = 'p' OR type = 'h');</B ></TT > ALTER</PRE ></DIV ><P >Due to the foreign key constraint, any <TT CLASS="LITERAL" >book_id</TT > value in the <TT CLASS="LITERAL" >editions</TT > table will now also have to exist in the <TT CLASS="LITERAL" >books</TT > table. Additionally, due to the check constraint, the <TT CLASS="LITERAL" >type</TT > values within the <TT CLASS="LITERAL" >editions</TT > table may only be set to either <SPAN ><I CLASS="EMPHASIS" >p</I ></SPAN > or <SPAN ><I CLASS="EMPHASIS" >h</I ></SPAN >.</P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B >To implicitly add a unique constraint, a workaround is to create a unique index using the <TT CLASS="LITERAL" >CREATE INDEX</TT > command (see <A href="c13329#INDICES" >the Section called <I >Indices</I > in Chapter 7</A >" in <A href="c13329" >Chapter 7</A >).</P ></BLOCKQUOTE ></DIV ><P >See <A href="x13546#CONSTRAINTS" >the Section called <I >Using Constraints</I > in Chapter 7</A >" in <A href="c13329" >Chapter 7</A > for more detailed information about constraints, their purpose, and their syntax.</P ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5383" >Changing ownership</A ></H3 ><P >By default, the creator of a table is automatically its <SPAN ><I CLASS="EMPHASIS" >owner</I ></SPAN >. The owner has all rights that can be associated with a table, in addition to the ability to <SPAN ><I CLASS="EMPHASIS" >grant</I ></SPAN > and <SPAN ><I CLASS="EMPHASIS" >revoke</I ></SPAN > rights with the <TT CLASS="LITERAL" >GRANT</TT > and <TT CLASS="LITERAL" >REVOKE</TT > commands (for more information see <A href="c18591" >Chapter 10</A >). If ownership must be changed, you can use the <TT CLASS="LITERAL" >ALTER TABLE</TT > command's <TT CLASS="LITERAL" >OWNER</TT > clause. The syntax to change the ownership of a table from one user to another is:</P ><PRE CLASS="SCREEN" > ALTER TABLE <TT CLASS="REPLACEABLE" ><I >table</I ></TT > OWNER TO <TT CLASS="REPLACEABLE" ><I >new_owner</I ></TT ></PRE ><P > <A href="x5021#CHANGINGTABLEOWNERSHIP" >Example 4-13</A > demonstrates altering a table's ownership with the <TT CLASS="LITERAL" >ALTER TABLE</TT > command's <TT CLASS="LITERAL" >OWNER</TT > clause. In it, <TT CLASS="LITERAL" >corwin</TT > is set as the owner of the <TT CLASS="LITERAL" >employees</TT > table.</P ><DIV CLASS="EXAMPLE" ><A NAME="CHANGINGTABLEOWNERSHIP" ></A ><P ><B >Example 4-13. Changing table ownership</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE employees</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > OWNER TO corwin;</B ></TT > ALTER</PRE ></DIV ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B >In order to change the ownership of a table, you must either be the owner of that table or a PostgreSQL superuser. </P ></BLOCKQUOTE ></DIV ></DIV ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="RESTRUCTURINGTABLES" >Restructuring Existing Tables</A ></H2 ><P >While you have the ability to arbitrarily add new columns to existing tables, remember that (as of PostgreSQL 7.1.x) <SPAN ><I CLASS="EMPHASIS" >you cannot drop columns from existing tables</I ></SPAN >. There are two fairly painless workarounds for restructuring existing tables. The first involves the <TT CLASS="LITERAL" >CREATE TABLE AS</TT > command, while the second combines the <TT CLASS="LITERAL" >CREATE TABLE</TT > command with the <TT CLASS="LITERAL" >INSERT INTO</TT > command.</P ><P >Each of these methods, in essence, involves creating a new table with your desired structure, filling it up with the data from your existing table, and renaming the tables so that the new table takes the place of your old table.</P ><DIV CLASS="WARNING" ><P ></P ><TABLE CLASS="WARNING" BORDER="1" WIDTH="100%" ><TR ><TD ALIGN="CENTER" ><B >Warning</B ></TD ></TR ><TR ><TD ALIGN="LEFT" ><P >When "restructuring" a table in this fashion, it is important to notice that old indices placed on the original table will not automatically be applied to the newly created table, nor will the OIDs (object identifiers) be the same. Any indices must be dropped and recreated.</P ></TD ></TR ></TABLE ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5420" >Restructuring with CREATE TABLE AS</A ></H3 ><P >One common technique of restructuring a table is to use the <TT CLASS="LITERAL" >CREATE TABLE</TT > command in conjunction with the <TT CLASS="LITERAL" >AS</TT > clause and a valid SQL query. This allows you to restructure your existing table into a temporary table, which can then be renamed. Doing this also allows you to both remove and re-arrange columns to a table by physically re-creating it, and simultaneously re-populating it with data from the original table.</P ><P >The following syntax describes this limited version of <TT CLASS="LITERAL" >CREATE TABLE</TT >, where <TT CLASS="REPLACEABLE" ><I >query</I ></TT > is the valid <TT CLASS="LITERAL" >SELECT</TT > statement that selects the data to populate the new table with. The data type of each created column is implied by the type of each corresponding column selected by <TT CLASS="REPLACEABLE" ><I >query</I ></TT >:</P ><PRE CLASS="SCREEN" > CREATE [ TEMPORARY | TEMP ] TABLE <TT CLASS="REPLACEABLE" ><I >table</I ></TT > [ ( <TT CLASS="REPLACEABLE" ><I >column_name</I ></TT > [, ...] ) ] AS <TT CLASS="REPLACEABLE" ><I >query</I ></TT ></PRE ><P >The advantage to this technique is that you may create the new table and populate it in a single SQL command. The most notable limitation of this technique is that there is no comprehensive way to set constraints on the newly created table; the only constraints that may be added to the table after is has been created are the foreign key and check constraints. Once the new table has been created, the old one can be renamed (or destroyed), and the new one can be renamed to the name of the original table.</P ><P >Suppose, for example, that you wanted to modify the <TT CLASS="LITERAL" >books</TT > table in order to drop the superfluous <TT CLASS="LITERAL" >publication</TT > column which was created in <A href="x5021#ADDINGCOLUMNS" >the Section called <I >Adding columns</I ></A >." You can create a limited copy of the table (designating only the desired columns) by passing a valid <TT CLASS="LITERAL" >SELECT</TT > statement to the <TT CLASS="LITERAL" >AS</TT > clause of <TT CLASS="LITERAL" >CREATE TABLE</TT >, and dropping the old table with <TT CLASS="LITERAL" >DROP TABLE</TT >, as shown in <A href="x5021#RESTRUCTURINGATABLEWITHCREATETABLEAS" >Example 4-14</A >.</P ><DIV CLASS="EXAMPLE" ><A NAME="RESTRUCTURINGATABLEWITHCREATETABLEAS" ></A ><P ><B >Example 4-14. Restructuring a table with CREATE TABLE AS</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >\d books</B ></TT > Table "books" Attribute | Type | Modifier -------------+---------+---------- id | integer | not null title | text | not null author_id | integer | subject_id | integer | publication | date | Index: books_id_pkey booktown=# <TT CLASS="USERINPUT" ><B >CREATE TABLE new_books</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > (id, title, author_id, subject_id)</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > AS SELECT id, title, author_id, subject_id</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > FROM books;</B ></TT > SELECT booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE books RENAME TO old_books;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE new_books RENAME TO books;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >\d books</B ></TT > Table "books" Attribute | Type | Modifier ------------+---------+---------- id | integer | title | text | author_id | integer | subject_id | integer | booktown=# <TT CLASS="USERINPUT" ><B >DROP TABLE books;</B ></TT > DROP</PRE ></DIV ><DIV CLASS="WARNING" ><P ></P ><TABLE CLASS="WARNING" BORDER="1" WIDTH="100%" ><TR ><TD ALIGN="CENTER" ><B >Warning</B ></TD ></TR ><TR ><TD ALIGN="LEFT" ><P >As of PostgreSQL 7.1.x, if you specify the optional column list within parentheses, you cannot use the asterisk (<TT CLASS="LITERAL" >*</TT >) in the <TT CLASS="REPLACEABLE" ><I >query</I ></TT > statement. This behavior is scheduled to be corrected in PostgreSQL 7.2.</P ></TD ></TR ></TABLE ></DIV ></DIV ><DIV CLASS="SECT3" ><H3 CLASS="SECT3" ><A NAME="AEN5463" >Restructuring with CREATE TABLE and INSERT INTO</A ></H3 ><P >If you require a more specifically defined table than that created by <TT CLASS="LITERAL" >CREATE TABLE AS</TT > (e.g., one with column constraints), you can replicate the effect of the <TT CLASS="LITERAL" >CREATE TABLE AS</TT > technique by issuing two SQL statements rather than one. You can achieve this by first creating the new table as you ordinarily would with <TT CLASS="LITERAL" >CREATE TABLE</TT >, and then populating the table with data via the <TT CLASS="LITERAL" >INSERT INTO</TT > command and a valid <TT CLASS="LITERAL" >SELECT</TT > statement.</P ><DIV CLASS="EXAMPLE" ><A NAME="RESTRUCTURINGATABLEWITHCREATETABLE" ></A ><P ><B >Example 4-15. Restructuring a table with CREATE TABLE and INSERT INTO</B ></P ><PRE CLASS="SCREEN" >booktown=# <TT CLASS="USERINPUT" ><B >CREATE TABLE new_books (</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > id integer UNIQUE,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > title text NOT NULL,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > author_id integer,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > subject_id integer,</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B > CONSTRAINT books_ id_ pkey PRIMARY KEY (id)</B ></TT > booktown(# <TT CLASS="USERINPUT" ><B >);</B ></TT > NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index 'books_id_pkey' for table 'new_books' CREATE booktown=# <TT CLASS="USERINPUT" ><B >INSERT INTO new_books</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > SELECT id, title, author_id, subject_id</B ></TT > booktown-# <TT CLASS="USERINPUT" ><B > FROM books;</B ></TT > INSERT 0 12 booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE books RENAME TO old_books;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >ALTER TABLE new_books RENAME TO books;</B ></TT > ALTER booktown=# <TT CLASS="USERINPUT" ><B >\d books</B ></TT > Table "books" Attribute | Type | Modifier ------------+---------+---------- id | integer | not null title | text | not null author_id | integer | subject_id | integer | Index: books_id_pkey</PRE ></DIV ><P >See <A href="x5504#INSERTINGVALUESFROMOTHERTABLESWITHSELECT" >the Section called <I >Inserting Values from Other Tables with SELECT</I ></A >" for more information about using the <TT CLASS="LITERAL" >INSERT INTO</TT > command with a <TT CLASS="LITERAL" >SELECT</TT > statement, and <A href="x5802" >the Section called <I >Retrieving Rows with SELECT</I ></A >" for more information about valid <TT CLASS="LITERAL" >SELECT</TT > statements. </P ></DIV ></DIV ><DIV CLASS="SECT2" ><H2 CLASS="SECT2" ><A NAME="DROPPINGTABLES" >Destroying Tables with DROP TABLE</A ></H2 ><P >The SQL command to permanently destroy a table is <TT CLASS="LITERAL" >DROP TABLE</TT >. The following is the syntax for <TT CLASS="LITERAL" >DROP TABLE</TT >, where <TT CLASS="REPLACEABLE" ><I >tablename</I ></TT > is the table that you wish to destroy:</P ><PRE CLASS="SCREEN" > DROP TABLE <TT CLASS="REPLACEABLE" ><I >tablename</I ></TT ></PRE ><P >Use caution when dropping a table, as doing so destroys all data associated with the table.</P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><A NAME="IMPLICITINDICES" ></A ><P ><B >Note: </B >Destroying a table with an implicitly-created index will destroy any associated indices.</P ></BLOCKQUOTE ></DIV ></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="c4890" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A href="book1" ACCESSKEY="H" >Home</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A href="x5504" ACCESSKEY="N" >Next</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >Using SQL with PostgreSQL</TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A href="c4890" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >Adding Data with INSERT and COPY</TD ></TR ></TABLE ></DIV ></BODY ></HTML > </div> <br /> <div id="thefineprint"> <a href="http://www.commandprompt.com/products/mammothpostgresql/"><img src="../images/powered_by_mammoth.gif" alt="Powered by Mammoth PostgreSQL" title="Powered by Mammoth PostgreSQL" border="0" /></a> <br /> Copyright © 2000-2007 Command Prompt, Inc. All Rights Reserved. All trademarks property of their respective owners. </div> </div> </div> </body> </html>