EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL Identity Column
Secondary 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

PostgreSQL Identity Column

By Sohel SayyadSohel Sayyad

PostgreSQL Identity Column

Definition of PostgreSQL Identity Column

In version 10 of PostgreSQL, it has introduced a new feature named GENERATED AS IDENTITY constraint. The GENERATED AS IDENTITY constraint allows user to assign a unique value to the column automatically. The SERIAL column constraint and the GENERATED AS IDENTITY constraint are kinds of similar constraints provided by PostgreSQL. PostgreSQL allows users to have multiple identity columns in a single table. The GENERATED AS IDENTITY constraint uses the SEQUENCE object same as the SERIAL constraint. We can change characteristics of existing Identity column or we can alter a table to have a column as an Identity column.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Consider the following syntax in order to illustrate the PostgreSQL Identity column:

column_name data_type
GENERATED { ALWAYS | BY DEFAULT }
AS IDENTITY
[ ( sequence_option ) ]

Explanation:

  • column_name: This defines the name of the column on which we want to apply the GENERATED AS IDENTITY constraint.
  • data_type: The data type can be any of the following:
  1. SMALLINT,
  2. INT,
  3. or BIGINT.

How does PostgreSQL Identity column works?

There are two types of instruction given to PostgreSQL when we use the GENERATED AS IDENTITY constraint, Let’s understand them as defined below.

Generated Always:

If we have GENERATED ALWAYS defined which means the PostgreSQL has to always create new value for the identity column. In case of the column with GENERATED ALWAYS constraint if we try to insert or update a value for same then PostgreSQL throws an error or exception.

Generated By Default:

If we have GENERATED BY DEFAULT defined means the PostgreSQL will create a new value for the PostgreSQL identity column. In case of the column with GENERATED BY DEFAULT constraint if we try to insert or update a value for same then PostgreSQL uses same value and do not use any system-generated value also PostgreSQL does not throw any error or exception

Examples

Let us discuss examples of PostgreSQL Identity Column.

Example #1 – GENERATED ALWAYS AS IDENTITY

Consider the following example where we will create a new table by using the CREATE TABLE statement which will store the details of the tuitions.

DROP TABLE tuitions;
CREATE TABLE tuitions (
tuition_id INT GENERATED ALWAYS AS IDENTITY,
tuition_name VARCHAR NOT NULL
);

Now we will insert a row into the tuitions table by using the INSERT INTO statement as follow:

INSERT INTO tuitions(tuition_name)
VALUES('Maths');

Illustrate the result of the tuitions table by using the following SQL statement and a snapshot.

SELECT * FROM tuitions;

PostgreSQL Identity Column 1

Now we will try to insert another record in the tuitions table by providing tuition_id and tuition_name both as follows:

INSERT INTO tuitions(tuition_id, tuition_name)
VALUES(2, 'English');

As we have used GENERATED ALWAYS AS IDENTITY constraint the PostgreSQL will throw an error or exception.

Illustrate the result of the above INSERT INTO statement by using the following snapshot.

PostgreSQL Identity Column 2

Example #2 – GENERATED BY DEFAULT AS IDENTITY

Consider the following example where we will create a new table by using the CREATE TABLE statement which will store the details of the tuitions.

DROP TABLE tuitions;
CREATE TABLE tuitions (
tuition_id INT GENERATED BY DEFAULT AS IDENTITY,
tuition_name VARCHAR NOT NULL
);

Now we will insert a row into the tuitions table by using the INSERT INTO statement as follow:

INSERT INTO tuitions(tuition_name)
VALUES('Maths');

Illustrate the result of the tuitions table by using the following SQL statement and a snapshot.

SELECT * FROM tuitions;

PostgreSQL Identity Column 3

Now we will try to insert another record in the tuitions table by providing tuition_id and tuition_name both as follows:

INSERT INTO tuitions(tuition_id, tuition_name)
VALUES(2, 'English');

As we have seen in case of the GENERATED ALWAYS AS IDENTITY constraint the PostgreSQL was throwing an error or exception by for GENERATED BY DEFAULT AS IDENTITY constraint it will work as expected.

Illustrate the result of the above INSERT INTO statement by using the following SQL statement and snapshot.

SELECT * FROM tuitions;

PostgreSQL Identity Column 4

Example #3 – Add column Identity

For adding an Identity column to the existing table the PostgreSQL provides the following syntax:

ALTER TABLE
table
ALTER COLUMN
column
ADD
{ ALWAYS | BY DEFAULT }
AS IDENTITY
{ ( sequence_option ) }

Consider the following example where we will create a new table by using the CREATE TABLE statement which will store the details of the tuitions.

DROP TABLE tuitions;
CREATE TABLE tuitions (
tuition_id int NOT NULL,
tuition_name VARCHAR NOT NULL
);

Now we will describe the identity column status for table tuitions by using the following SQL statement and snapshot:

SELECT
column_name, is_identity, identity_generation
FROM
information_schema.columns
WHERE
TABLE_NAME = 'tuitions';

PostgreSQL Identity Column 5

We can change the tuition_id column to the Identity column by using the following syntax, before defining any column as an Identity column we have to make it a NOT NULL column.

ALTER TABLE
tuitions
ALTER COLUMN
tuition_id
ADD
GENERATED ALWAYS AS IDENTITY;

we will describe the identity column status for table tuitions by using the following SQL statement and snapshot:

SELECT
column_name, is_identity, identity_generation
FROM
information_schema.columns
WHERE
TABLE_NAME = 'tuitions';

PostgreSQL Identity Column 6

Example #4 – Change the characteristics of the existing Identity column

For changing the characteristics of an Identity column of the existing table the PostgreSQL provides the following syntax:

ALTER TABLE
table
ALTER COLUMN
Column
{
SET
GENERATED { ALWAYS| BY DEFAULT }
}

In order to understand this topic, consider the table created in the previous section.

We can change the Identity column tuition_id column’s constraint by using the following syntax

ALTER TABLE
tuitions
ALTER COLUMN
tuition_id
SET GENERATED BY DEFAULT;

we will describe the identity column status for table tuitions by using the following SQL statement and snapshot:

SELECT
column_name, is_identity, identity_generation
FROM
information_schema.columns
WHERE
TABLE_NAME = 'tuitions';

Example #4

Example #5 – Drop the column Identity

For deleting an Identity column of the existing table the PostgreSQL provides the following syntax:

ALTER TABLE
table
ALTER COLUMN
column
DROP
IDENTITY [ IF EXISTS ]

In order to understand this topic, consider the table created in the previous section.

We can drop the identity of the tuition_id column by using the following syntax:

ALTER TABLE
tuitions
ALTER COLUMN
tuition_id
DROP
IDENTITY IF EXISTS;

we will describe the identity column status for table tuitions by using the following SQL statement and snapshot:

SELECT
column_name, is_identity, identity_generation
FROM
information_schema.columns
WHERE
TABLE_NAME = 'tuitions';

Example 5

Conclusion

We hope from the above article you have understood how to use the PostgreSQL Identity column and how the PostgreSQL Identity column works. Also, we have added several examples of PostgreSQL Identity column to understand it in detail.

Recommended Articles

This is a guide to PostgreSQL Identity Column. Here we discuss the definition, How does PostgreSQL Identity column works? and examples with code implementation respectively. You may also have a look at the following articles to learn more –

  1. PostgreSQL Roles
  2. PostgreSQL MIN()
  3. PostgreSQL Current Date
  4. PostgreSQL SET
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
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

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA

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

Let’s Get Started

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

EDUCBA

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

*Please provide your correct email id. Login details for this Free course will be emailed to you
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

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more