Skip to content

Commit

Permalink
copy editing constraint pages
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Loiselle committed Jan 24, 2017
1 parent b5f33a1 commit 35ece1d
Show file tree
Hide file tree
Showing 26 changed files with 285 additions and 152 deletions.
2 changes: 1 addition & 1 deletion _data/sidebar_doc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ entries:
- title: Default Value
url: /default-value.html

- title: Foreign Keys
- title: Foreign Key
url: /foreign-key.html

- title: Not Null
Expand Down
3 changes: 1 addition & 2 deletions add-constraint.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ The `ADD CONSTRAINT` [statement](sql-statements.html) is part of `ALTER TABLE` a
- [Unique](unique.html)

{{site.data.alerts.callout_info}}
The <a href="primary-key.html">Primary Key</a> constraint can only be applied through <a href="create-table.html"><code>CREATE TABLE</code></a>. The <a href="default-value.html">Default</a> constraint is managed through <a href="alter-column.html"><code>ALTER COLUMN</code>.</a>
{{site.data.alerts.end}}
The <a href="primary-key.html">Primary Key</a> and <a href="not-null.html">Not Null</a> constraints can only be applied through <a href="create-table.html"><code>CREATE TABLE</code></a>. The <a href="default-value.html">Default</a> constraint is managed through <a href="alter-column.html"><code>ALTER COLUMN</code>.</a>{{site.data.alerts.end}}

<div id="toc"></div>

Expand Down
8 changes: 4 additions & 4 deletions alter-column.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ The user must have the `CREATE` [privilege](privileges.html) on the table.

| Parameter | Description |
|-----------|-------------|
| `table_name` | The name of the table with the column whose Default value you want to modify. |
| `table_name` | The name of the table with the column whose Default Value you want to modify. |
| `name` | The name of the column you want to modify. |
| `a_expr` | The new Default value you want to use. |
| `a_expr` | The new Default Value you want to use. |

## Examples

### Set or Change a Default Value

Setting the [Default value constraint](default-value.html) inserts the value when data's written to the table without explicitly defining the value for the column. If the column already has a Default value set, you can use this statement to change it.
Setting the [Default Value constraint](default-value.html) inserts the value when data's written to the table without explicitly defining the value for the column. If the column already has a Default Value set, you can use this statement to change it.

The below example inserts the Boolean value `true` whenever you inserted data to the `subscriptions` table without defining a value for the `newsletter` column.

Expand All @@ -40,7 +40,7 @@ The below example inserts the Boolean value `true` whenever you inserted data to

### Remove Default Constraint

If the column has a defined [Default value](default-value.html), you can remove the constraint, which means the column will no longer insert a value by default if one is not explicitly defined for the column.
If the column has a defined [Default Value](default-value.html), you can remove the constraint, which means the column will no longer insert a value by default if one is not explicitly defined for the column.

``` sql
> ALTER TABLE subscriptions ALTER COLUMN newsletter DROP DEFAULT;
Expand Down
30 changes: 17 additions & 13 deletions check.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
---
title: Check Constraint
summary: The Check constraint specifies that the column value must satisfy a Boolean expression.
summary: The Check constraint specifies that values for the column in INSERT or UPDATE statements must satisfy a Boolean expression.
toc: false
---

The Check [constraints](constraints.html) specifies that the column value must satisfy a Boolean expression.
The Check [constraint](constraints.html) specifies that values for the column in [`INSERT`](insert.html) or [`UPDATE`](update.html) statements must return `TRUE` or `NULL` for a Boolean expression. If any values return `FALSE`, the entire statement is rejected.

<div id="toc"></div>

## Details

- Check constraints requires that the column values satisfy a Boolean expression within the constraint. The expression must evaluate to `TRUE` (or *NULL*) for every row affected by an `INSERT` or `UPDATE` statement. The DML statement will fail if the condition evaluates to `FALSE` for any row.
- Check constraints may be specified at the column or table level and can reference other columns within the table. Internally, all column level Check constrints are converted to table level constraints so they can be handled in a consistent fashion.
- You can have multiple Check constraints on a single column but ideally, for performance optimization, these should be combined using the logical operators. So, for example,
- If you add a Check constraint to an existing table, existing values are not checked. However, any updates to those values will be.
{{site.data.alerts.callout_info}}In the future we plan to expand the Check constraint to include a check on any existing values in the column.{{site.data.alerts.end}}
- Check constraints may be specified at the column or table-level and can reference other columns within the table. Internally, all column-level Check constraints are converted to table-level constraints so they can be handled consistently.
- You can have multiple Check constraints on a single column but ideally, for performance optimization, these should be combined using the logical operators. For example:

~~~ sql
warranty_period INT CHECK (warranty_period >= 0) CHECK (warranty_period <= 24)
~~~

should be specified as
should be specified as:

~~~ sql
warranty_period INT CHECK (warranty_period BETWEEN 0 AND 24)
~~~

## Syntax

The syntax of the Check constraint depends on whether you want the constraint to use a [single column](#single-column-column-level) or [multiple columns](#multiple-column-table-level).
Check constraints can be defined at the [table level](#table-level). However, if you only want the constraint to apply to a single column, it can be applied at the [column level](#column-level).

### Single Column (Column Level)
{{site.data.alerts.callout_info}}You can also add the Check constraint to existing tables through <a href="/add-constraint.html#add-the-check-constraint"><code>ADD CONSTRAINT</code></a>.{{site.data.alerts.end}}

### Column Level

{% include sql/diagrams/check_column_level.html %}

Expand All @@ -38,7 +41,7 @@ The syntax of the Check constraint depends on whether you want the constraint to
| `column_name` | The name of the constrained column. |
| `column_type` | The constrained column's [data type](data-types.html). |
| `check_expr` | An expression that returns a Boolean value; if the expression evaluates to `FALSE`, the value cannot be inserted.|
| `column_constraints` | Any other column-level [constraints](constraints.html) you want to apply. |
| `column_constraints` | Any other column-level [constraints](constraints.html) you want to apply to this column. |
| `column_def` | Definitions for any other columns in the table. |
| `table_constraints` | Any table-level [constraints](constraints.html) you want to apply. |

Expand All @@ -53,7 +56,7 @@ The syntax of the Check constraint depends on whether you want the constraint to
);
~~~

### Multiple Column (Table Level)
### Table Level

{% include sql/diagrams/check_table_level.html %}

Expand All @@ -63,7 +66,7 @@ The syntax of the Check constraint depends on whether you want the constraint to
| `column_def` | Definitions for any other columns in the table. |
| `name` | The name you want to use for the constraint, which must be unique to its table and follow these [identifier rules](keywords-and-identifiers.html#identifiers). |
| `check_expr` | An expression that returns a Boolean value; if the expression evaluates to `FALSE`, the value cannot be inserted.|
| `table_constraints` | Any table-level [constraints](constraints.html) you want to apply. |
| `table_constraints` | Any other table-level [constraints](constraints.html) you want to apply. |

**Example**

Expand All @@ -79,7 +82,7 @@ The syntax of the Check constraint depends on whether you want the constraint to

## Usage Example

Check constraints may be specified at the column or table level and can reference other columns within the table. Internally, all column level Check constrints are converted to table level constraints so they can be handled in a consistent fashion.
Check constraints may be specified at the column or table-level and can reference other columns within the table. Internally, all column-level Check constraints are converted to table-level constraints so they can be handled in a consistent fashion.

~~~ sql
> CREATE TABLE inventories (
Expand All @@ -89,7 +92,7 @@ Check constraints may be specified at the column or table level and can referenc
PRIMARY KEY (product_id, warehouse_id)
);

> INSERT INTO inventories (product_id, warehouse_id, quantity_on_hand) VALUES (1, 2, -20);
> INSERT INTO inventories (product_id, warehouse_id, quantity_on_hand) VALUES (1, 2, 0);
~~~
~~~
pq: failed to satisfy CHECK constraint (quantity_on_hand > 0)
Expand All @@ -98,6 +101,7 @@ pq: failed to satisfy CHECK constraint (quantity_on_hand > 0)
## See Also

- [Constraints](constraints.html)
- [`DROP CONSTRAINT`](drop-constraint.html)
- [Default Value constraint](default-value.html)
- [Foreign Key constraint](foreign-key.html)
- [Not Null constraint](not-null.html)
Expand Down
119 changes: 104 additions & 15 deletions constraints.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,116 @@
---
title: Constraints
summary: Constraints offer additional data integrity by enforcing conditions on the data within a column or row.
summary: Constraints offer additional data integrity by enforcing conditions on the data within a column.
toc: false
---

Constraints offer additional data integrity by enforcing conditions on the data within a column or row. They are checked during DML operations and restrict the data values within a column to those specified within the constraint.
Constraints offer additional data integrity by enforcing conditions on the data within a column. Whenever values are manipulated (inserted, deleted, or updated), constraints are checked and modifications that violate constraints are rejected.

If a constraint refers to only one column (column-level constraint), it can be defined against the column as part of its definition. If a constraint refers to more than one column (table-level constraint), it needs to be defined as a separate entry in the tables definition.
For example, the Unique constraint requires that all values in a column be unique from one another (except *NULL* values). If you attempt to write a duplicate value, the constraint rejects the entire statement.

The order of the constraints within the table definition is not important and does not determine the order in which the constraints are checked. Use the [`SHOW CONSTRAINTS`](show-constraints.html) or [`SHOW CREATE TABLE`](show-create-table.html) statement to show the constraints defined on a table.
<div id="toc"></div>

The different types of constraints are:
## Supported Constraints

| Constraint Type | Description |
|-----------------|-------------|
| [Check](check.html) | Specifies that the column value must satisfy a Boolean expression. |
| [Default Value](default-value.html) | Specifies a value to populate a column with if none is provided.|
| [Foreign Keys](foreign-key.html) | Specifies a column can only contain values exactly matching existing values from the column it references. |
| [Not Null](not-null.html) | Specifies the column **may not** contain *NULL* values.|
| [Primary Key](primary-key.html) | Specifies that the columns values are unique and that the columns **may not** contain *NULL* values. |
| [Unique](unique.html) | Specifies that the columns values are unique and that the columns **may** contain *NULL* values. |
| Constraint | Description |
|------------|-------------|
| [Check](check.html) | Values must return `TRUE` or `NULL` for a Boolean expression. |
| [Default Value](default-value.html) | If a value is not defined for the constrained column in an `INSERT` statement, the Default Value is written to the column. |
| [Foreign Keys](foreign-key.html) | Values must exactly match existing values from the column it references. |
| [Not Null](not-null.html) | Values may not be *NULL*. |
| [Primary Key](primary-key.html) | Values must uniquely identify each row *(one per table)*. This behaves as if the Not Null and Unique constraints are applied, as well as automatically creates an [index](indexes.html) for the table using the constrained columns. |
| [Unique](unique.html) | Each non-*NULL* value must be unique. This also automatically creates an [index](indexes.html) for the table using the constrained columns. |

## Using Constraints

### Add Constraints

How you add constraints depends on the number of columns you want to constrain, as well as whether or not the table is new.

- **One column of a new table** has its constraints defined after the column's data type. For example, this statement applies the Primary Key constraint to `foo.a`:

``` sql
> CREATE TABLE foo (a INT PRIMARY KEY);
```
- **Multiple columns of a new table** have their constraints defined after the table's columns. For example, this statement applies the Primary Key constraint to `foo`'s columns `a` and `b`:

``` sql
> CREATE TABLE bar (a INT, b INT, PRIMARY KEY (a,b));
```

{{site.data.alerts.callout_info}}The Default Value and Not Null constraints cannot be applied to multiple columns.{{site.data.alerts.end}}

- **Existing tables** can have the following constraints added:
- **Check**, **Foreign Key**, and **Unique** constraints can be added through [`ALTER TABLE...ADD CONSTRAINT`](add-constraint.html). For example, this statement adds the Unique constraint to `baz.id`:

~~~ sql
> ALTER TABLE baz ADD CONSTRAINT id_unique UNIQUE (id);
~~~

- **Default Values** can be added through [`ALTER TABLE...ALTER COLUMN`](alter-column.html#set-or-change-a-default-value). For example, this statement adds the Default Value constraint to `baz.bool`:

~~~ sql
> ALTER TABLE baz ALTER COLUMN bool SET DEFAULT true;
~~~

- **Primary Key** and **Not Null** constraints cannot be added or changed. However, you can go through [this process](#table-migrations-to-add-or-change-immutable-constraints) to migrate data from your current table to a new table with the constraints you want to apply.

#### Order of Constraints

The order in which you list constraints is not important because constraints are applied to every modification of their respective tables or columns.

#### Name Constraints on New Tables

You can name constraints applied to new tables using the `CONSTRAINT` clause before defining the constraint:

``` sql
> CREATE TABLE foo (a INT CONSTRAINT another_name PRIMARY KEY);
> CREATE TABLE bar (a INT, b INT, CONSTRAINT yet_another_name PRIMARY KEY (a,b));
```

### View Constraints

To view a table's constraints, use [`SHOW CONSTRAINTS`](show-constraints.html) or [`SHOW CREATE TABLE`](show-create-table.html).
### Remove Constraints
The procedure for removing a constraint depends on its type:
| Constraint Type | Procedure |
|-----------------|-----------|
| [Check](check.html) | Use [`DROP CONSTRAINT`](drop-constraint.html) |
| [Default Value](default-value.html) | Use [`ALTER COLUMN`](alter-column.html#remove-default-constraint) |
| [Foreign Keys](foreign-key.html) | Use [`DROP CONSTRAINT`](drop-constraint.html) |
| [Not Null](not-null.html) | Use [`ALTER COLUMN`](alter-column.html#remove-not-null-constraint) |
| [Primary Key](primary-key.html) | Primary Keys cannot be removed. However, you can move the table's data to a new table with [this process](#table-migrations-to-add-or-change-immutable-constraints). |
| [Unique](unique.html) | The Unique constraint cannot be dropped directly. However, you can use [`DROP INDEX`](drop-index.html) to remove the index automatically created by the Unique constraint (whose name ends in `_key`) to remove the constraint. |

### Change Constraints

The procedure for changing a constraint depends on its type:

| Constraint Type | Procedure |
|-----------------|-----------|
| [Check](check.html) | [Issue a transaction](transactions.html#syntax) that adds a new Check constraint ([`ADD CONSTRAINT`](add-constraint.html)), and then remove the existing one ([`DROP CONSTRAINT`](drop-constraint.html)). |
| [Default Value](default-value.html) | The Default Value can be changed through [`ALTER COLUMN`](alter-column.html). |
| [Foreign Keys](foreign-key.html) | [Issue a transaction](transactions.html#syntax) that adds a new Foreign Key constraint ([`ADD CONSTRAINT`](add-constraint.html)), and then remove the existing one ([`DROP CONSTRAINT`](drop-constraint.html)). |
| [Not Null](not-null.html) | The Not Null constraint cannot be changed, only removed. However, you can move the table's data to a new table with [this process](#table-migrations-to-add-or-change-immutable-constraints). |
| [Primary Key](primary-key.html) | Primary Keys cannot be modified. However, you can move the table's data to a new table with [this process](#table-migrations-to-add-or-change-immutable-constraints). |
| [Unique](unique.html) | [Issue a transaction](transactions.html#syntax) that adds a new Unique constraint ([`ADD CONSTRAINT`](add-constraint.html)), and then remove the existing one ([`DROP CONSTRAINT`](drop-constraint.html)). |

#### Table Migrations to Add or Change Immutable Constraints

If you want to make a change to an immutable constraint, you can use the following process:

1. [Create a new table](create-table.html) with the constraints you want to apply.
2. Move the data from the old table to the new one using [`INSERT` from a `SELECT` statement](insert.html#insert-from-a-select-statement).
3. [Issue a transaction](transactions.html#syntax) that [drops the old table](drop-table.html), and then [renames the new table to the old name](rename-table.html).

## See Also
- [`ALTER TABLE`](alter-table.html)
- [`SHOW CONSTRAINTS`](show-constraints.html)

- [`CREATE TABLE`](create-table.html)
- [`ADD CONSTRAINT`](add-constraint.html)
- [`DROP CONSTRAINT`](drop-constraint.html)
- [`SHOW CONSTRAINTS`](show-constraints.html)
- [`SHOW CREATE TABLE`](show-create-table.html)
Loading

0 comments on commit 35ece1d

Please sign in to comment.