📄 ddl.sgml
字号:
<!-- $PostgreSQL: pgsql/doc/src/sgml/ddl.sgml,v 1.50 2005/11/04 23:53:18 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 -- it reflects how much data is stored at a given moment. SQL does not make any guarantees about the order of the rows in a table. When a table is read, the rows will appear in random order, unless sorting is explicitly requested. This is covered in <xref linkend="queries">. Furthermore, SQL does not assign unique identifiers to rows, so it is possible to have several completely identical rows in a table. This is a consequence of the mathematical model that underlies SQL but is usually not desirable. Later in this chapter we will see how to deal with this issue. </para> <para> Each column has a data type. The data type constrains the set of possible values that can be assigned to a column and assigns semantics to the data stored in the column so that it can be used for computations. For instance, a column declared to be of a numerical type will not accept arbitrary text strings, and the data stored in such a column can be used for mathematical computations. By contrast, a column declared to be of a character string type will accept almost any kind of data but it does not lend itself to mathematical calculations, although other operations such as string concatenation are available. </para> <para> <productname>PostgreSQL</productname> includes a sizable set of built-in data types that fit many applications. Users can also define their own data types. Most built-in data types have obvious names and semantics, so we defer a detailed explanation to <xref linkend="datatype">. Some of the frequently used data types are <type>integer</type> for whole numbers, <type>numeric</type> for possibly fractional numbers, <type>text</type> for character strings, <type>date</type> for dates, <type>time</type> for time-of-day values, and <type>timestamp</type> for values containing both date and time. </para> <indexterm> <primary>table</primary> <secondary>creating</secondary> </indexterm> <para> 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:<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 <command>DROP TABLE</command> 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 the error messages. </para> <para> If you need to modify a table that already exists look into <xref linkend="ddl-alter"> later in this chapter. </para> <para> With the tools discussed so far you can create fully functional tables. The remainder of this chapter is concerned with adding features to the table definition to ensure data integrity, security, or convenience. If you are eager to fill your tables with data now you can skip ahead to <xref linkend="dml"> and read the rest of this chapter later. </para> </sect1> <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, the 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 may 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 that a <type>timestamp</type> column may have a default of <literal>now()</>, 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 only be one row for each product number. </para> <para> To that end, SQL allows you to define constraints on columns and tables. Constraints give you as much control over the data in your tables as you wish. If a user attempts to store data in a column that would violate a constraint, an error is raised. This applies even if the value came from the default value definition. </para> <sect2> <title>Check Constraints</title> <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 > 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 > 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 > 0), discounted_price numeric CHECK (discounted_price > 0), <emphasis>CHECK (price > 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 > 0), discounted_price numeric, CHECK (discounted_price > 0), CHECK (price > discounted_price));</programlisting> or even<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));</programlisting> It's a matter of taste. </para> <para> Names can be assigned to table constraints in just the same way as for column constraints:<programlisting>CREATE TABLE products ( product_no integer, name text, price numeric, CHECK (price > 0), discounted_price numeric, CHECK (discounted_price > 0), <emphasis>CONSTRAINT valid_discount</> CHECK (price > discounted_price));</programlisting> </para> <indexterm> <primary>null value</primary> <secondary sortas="check constraints">with check constraints</secondary> </indexterm>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -