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:
-- This SQL statement creates a new table named 'jobs' with specified columns and constraints.
CREATE TABLE jobs (
JOB_ID integer NOT NULL UNIQUE, -- Defines the JOB_ID column as an integer type, which cannot be NULL and must be unique
JOB_TITLE varchar(35) NOT NULL, -- Defines the JOB_TITLE column as a varchar type with a maximum length of 35 characters, which cannot be NULL
MIN_SALARY decimal(6,0) -- Defines the MIN_SALARY column as a decimal type with a precision of 6 digits and 0 decimal places
);
Explanation:
- The CREATE TABLE statement is used to create a new table in the database.
- jobs is the name of the new table being created.
- (JOB_ID integer NOT NULL UNIQUE, JOB_TITLE varchar(35) NOT NULL, MIN_SALARY decimal(6,0)) specifies the columns of the table along with their data types and constraints.
- JOB_ID is defined as an integer type column that cannot contain NULL values (NOT NULL) and must have unique values (UNIQUE constraint).
- JOB_TITLE is defined as a varchar type column with a maximum length of 35 characters and cannot contain NULL values.
- MIN_SALARY is defined as a decimal type column with a precision of 6 digits and 0 decimal places.
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/postgresql-exercises/insert-record/insert-records-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics