Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

PostgreSQL Insert Record: Insert rows into the table to ensure that the value of the key column will be unique and auto incremented


9. Write a SQL statement to insert rows into the table countries in which the value of country_id column will be unique and auto incremented.

Sample Solution:

Code:

Here is the code to create a sample table countries:

CREATE TABLE countries ( 
COUNTRY_ID SERIAL PRIMARY KEY,
COUNTRY_NAME varchar(40) NOT NULL,
REGION_ID integer NOT NULL
);

Now insert one record into the table:

INSERT INTO countries(COUNTRY_NAME,REGION_ID) VALUES('India',185);

Here is the command to see the list of inserting rows:

postgres=# SELECT * FROM countries;
 country_id | country_name | region_id
------------+--------------+-----------
          1 | India        |       185
(1 row)

Now insert another record into the table :

INSERT INTO countries(COUNTRY_NAME,REGION_ID) VALUES('Japan',102);

Now see the value of the key field incremented automatically :

postgres=# SELECT * FROM countries;
 country_id | country_name | region_id
------------+--------------+-----------
          1 | India        |       185
          2 | Japan        |       102
(2 rows)

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a SQL statement to insert a record into the table countries to ensure that, at country_id and the region_id combination will be entered once in the table.
Next: Write a SQL statement to insert records into the table countries to ensure that the country_id column will not contain any duplicate data and this will be automatically incremented and the column country_name will be filled up by 'N/A' if no value assigned to that column.

What is the difficulty level of this exercise?