Unique Constraint - (PostgreSQL Constraints)
A constraint is a rule that you define to enforce certain conditions for the data in a table. In PostgreSQL, you can use the UNIQUE
constraint to ensure that all data in a certain column is unique. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of the UNIQUE
constraint in PostgreSQL.
Syntax
CREATE TABLE table_name (
column1 datatype PRIMARY KEY,
column2 datatype UNIQUE,
column3 datatype
);
The UNIQUE
constraint is added to a column at the time of table creation. It ensures that any data input into the specified column is unique.
Example
Let's create a table and add the UNIQUE
constraint to one of its columns:
CREATE TABLE orders (
order_id serial PRIMARY KEY,
customer_name text,
order_date date,
order_number text UNIQUE
);
In this example, we've created a table called orders
with four columns – order_id
, customer_name
, order_date
, and order_number
. We've added the UNIQUE
constraint to the order_number
column to ensure that each order number is unique.
Explanation
The UNIQUE
constraint is used to ensure that all data in a certain column is unique. When you add the UNIQUE
constraint to a column, it creates an index on the column, which automatically enforces uniqueness.
In the example above, we created a table called orders
with four columns. We added the UNIQUE
constraint to the order_number
column to ensure that each order number is unique. This means that no two orders can have the same order number.
Use
The UNIQUE
constraint is useful when you want to ensure that the data in a certain column is unique. This can be helpful when creating key fields such as usernames or account numbers.
Important Points
- You can add the
UNIQUE
constraint to multiple columns in a table. - A
UNIQUE
constraint does not allow null values. If you want to allow null values, you should use theNULL
constraint instead. - You can also add a
UNIQUE
constraint on multiple columns at the same time by using a comma-separated list of column names in parentheses after the keywordUNIQUE
.
Summary
In this tutorial, we covered the UNIQUE
constraint in PostgreSQL. We discussed its syntax, example, output, explanation, use, and important points. With this knowledge, you can now create tables with unique constraints and ensure that the data in a certain column is unique.