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 one row into a table to ensure that no duplicate values will be entered in the key column


7. Write a SQL statement to insert one row in the jobs table to ensure that no duplicate values will be entered into the job_id column.

Sample Solution:

Code:

Here is the code to create a sample table jobs:

CREATE TABLE jobs ( 
JOB_ID integer NOT NULL UNIQUE , 
JOB_TITLE varchar(35) NOT NULL, 
MIN_SALARY decimal(6,0)
);

Now insert a row into the table jobs :

INSERT INTO jobs VALUES(1001,'OFFICER',8000);

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

postgres=# SELECT * FROM jobs;
 job_id | job_title | min_salary
--------+-----------+------------
   1001 | OFFICER   |       8000
(1 row)

Now, try to insert the duplicate value in the key column and see what happen :

postgres=# INSERT INTO jobs VALUES(1001,'OFFICER',8000);
ERROR:  duplicate key value violates unique constraint "jobs_job_id_key"
DETAIL:  Key (job_id)=(1001) already exists.

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

Previous: Write a SQL statement insert rows from the country_new table to countries table.
Next: 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.

What is the difficulty level of this exercise?