EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PostgreSQL Constraints

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » PostgreSQL Constraints

postresql constaints

Definition of PostgreSQL Constraints

PostgreSQL constraints are used to enforce the rule on the table’s data columns; this is mostly useful to prevent invalid data to enter into the table. PostgreSQL constraints are beneficial to find duplicate value; they will not accept the duplicate value or invalid data into the table. PostgreSQL constraints ensure the accuracy and reliability of data into the table. We have to define constraints on table level as well as column level. Table level constraints are applied to the whole table, whereas column-level constraints are applied to only one column.

PostgreSQL Constraints with Examples

The following are the commonly used constraints available in PostgreSQL are as follows.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

1. Not Null Constraints

  • In PostgreSQL, by default, the column accepts null values; using no null constraints on the column will not accept any null values in a column.
  • Not null constraint in PostgreSQL always written as column constraints.

Syntax:

Create table table_name (
Column_name1 data type Not Null,
Column_nameN data type Not Null);

Below is the description of the above syntax.

  • Create: We have created not null constraint on a column at the time of table creation.
  • Table name: It is the name of the table.
  • Column_name1 to column_nameN: Name of column.
  • Data type: A Data type that we have defined to a column.
  • Not Null: Constraint name, which does not accept null value in the column.

Example

Below is the example of not null constraints at the time of table creation.

CREATE TABLE Employee ( emp_id INT NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), emp_salary INT NOT NULL, date_of_joining date NOT NULL);

Not Null Constraints-1.1

INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone, emp_salary, date_of_joining) VALUES (1, 'ABC', 'Pune', '1234567890', 20000, '01-01-2020');
select * from Employee;

PostgreSQL Constraints-1.2

2. Unique Constraints

  • Unique constraints are the same as its name unique; it will prevent to add two identical values in the table.
  • Unique constraints ensure that all values in the column are identical.

Syntax:

Create table table_name (
Column_name1 data type Not Null Unique,
Column_nameN data type Not Null Unique);

Below is the description of the above syntax.

  • Create: We have created a unique constraint on the column at the time of table creation.
  • Table name: It is the name of the table.
  • Column_name1 to column_nameN: Name of column.
  • Data type: Data type of column.
  • Unique: Constraint name.

Example

Below is an example of unique constraints at the time of table creation.

CREATE TABLE department ( dept_name character(10) NOT NULL UNIQUE, dept_id int NOT NULL UNIQUE, dept_code varchar(10));

Unique Constraints -2.1

INSERT INTO department (dept_name, dept_id, dept_code) VALUES ('IT', 101, 'IT101');

Unique Constraints-2.2

INSERT INTO department (dept_name, dept_id, dept_code) VALUES ('IT', 101, 'IT101');

Unique Constraints-2.3

  • In the second example, the same value insertion is not allowed in the table because we have used a unique constraint on the dept_id column.

3. Primary Key Constraints

  • Primary constraint, which uniquely identifies each record in the database table. We can define multiple primary key constraints on a single table. It will be allowed only one primary key constraint on a single table.
  • Below are the example and syntax of primary key constraints in PostgreSQL.

Syntax:

Create table table_name (
Column_name1 data type primary key Not Null,
Column_nameN data type Not Null);

Below is the description of the above syntax.

  • Create: We have created a primary constraint on a column at the time of table creation.
  • Table name: Name of the table.
  • Column_name1 to column_nameN: Name of column.
  • Data type: Data type of column.
  • Primary Key: Constraint name.

Example

Below is an example of a primary key constraint in PostgreSQL at the time of table creation.

CREATE TABLE Employee_test ( emp_id INT PRIMARY KEY NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), emp_salary INT NOT NULL);

PostgreSQL Constraints-3.1

INSERT INTO Employee_test (emp_id, emp_name, emp_address, emp_phone, emp_salary) VALUES (1, 'ABC', 'Pune', '1234567890', 20000);

PostgreSQL Constraints - 3.2

INSERT INTO Employee_test (emp_id, emp_name, emp_address, emp_phone, emp_salary) VALUES (1, 'PQR', 'MUMBAI', '1234567880', 25000);

Popular Course in this category
Sale
PostgreSQL Course (2 Courses, 1 Project)2 Online Courses | 1 Hands-on Project | 7+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,206 ratings)
Course Price

View Course

Related Courses

PostgreSQL Constraints - 3.3

  • In the second example, the same emp_id insertion is not allowed in the table because we have used the primary key constraint on the emp_id column.

4. Foreign Key Constraints

  • Foreign key constraints in PostgreSQL states that values in the first table column must appear with values with a second table column.
  • Below are the syntax and examples of foreign key constraints in PostgreSQL.

Syntax:

Create table table_name (
Column_name1 data type primary key Not Null,
Column_nameN data type references table_name (column_name));

Below is the description of the above syntax.

  • Create: Create table statement.
  • Table name: It is the name of the table.
  • Column_name1 to column_nameN: Name of the column.
  • Data type: Data type of column.

Example

Below is the example of foreign key constraints in PostgreSQL at the time of table creation.

CREATE TABLE Employee_test1 ( emp_id INT PRIMARY KEY NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), emp_salary INT NOT NULL);

Foreign Key-4.1

CREATE TABLE Employee_test2 ( emp_id INT PRIMARY KEY NOT NULL, emp_name character(10) NOT NULL, emp_salary INT NOT NULL, id int references Employee_test1(emp_id));

Foreign Key-4.2

\d+ Employee_test1;

Foreign Key-4.3

\d+ Employee_test2;

Foreign Key-4.4

5. Check Constraints

  • Check condition in PostgreSQL enables to check the condition that values being entered into the record.
  • Below is the syntax, and examples of check constraints in PostgreSQL are as follows.

Syntax:

Create table table_name (
Column_name1 data type primary key Not Null
Column_nameN data type Not Null check condition);

Below is the description of the above syntax.

  • Create: Create table statement.
  • Table name: Name of the table.
  • Column_name1 to column_nameN: Name of column.
  • Data type: Data type of column.
  • Check condition: check Constraint with the condition.

Example

CREATE TABLE EMP_TEST (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, SALARY REAL CHECK(SALARY > 1000));

PostgreSQL Constraints-5.1

INSERT into EMP_TEST (ID, NAME, SALARY) VALUES (1, 'ABC', 5000);

PostgreSQL Constraints-5.2

INSERT into EMP_TEST (ID, NAME, SALARY) VALUES (1, 'ABC', 500);

PostgreSQL Constraints-5.3

  • The second example salary less than 1000 insertion is not allowed in a table because we have used check constraints on the salary column.

Conclusion

PostgreSQL constraints are beneficial to validate data with duplicate and unwanted data from the table. We have mainly used not null, primary key, foreign key, check and unique key constraints in PostgreSQL. Constrains is most important and useful in PostgreSQL.

Recommended Articles

This is a guide to PostgreSQL Constraints. Here we discuss the commonly used constraints available in PostgreSQL along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. What are the Features of PostgreSQL?
  2. Introduction to PostgreSQL Architecture
  3. Different Versions & Features of PostgreSQL
  4. Guide to PostgreSQL Views
  5. Guide to PostgreSQL FETCH
  6. Guide to Oracle Constraints
  7. Complete Guide to MySQL Constraints
  8. Examples of Unique Key in MySQL

PostgreSQL Course (2 Courses, 1 Project)

2 Online Courses

1 Hands-on Project

7+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - PostgreSQL Course (2 Courses, 1 Project) Learn More