w3resource

Insert a row in the MySQL 'jobs' table to prevent duplicate values in the 'job_id' column

MySQL insert into Statement: Exercise-7 with Solution

7. Write a MySQL query to insert one row in jobs table to ensure that no duplicate value will be entered in the job_id column.

Create the table jobs.

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

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

mysql> SELECT * FROM jobs;
+--------+-----------+------------+
| JOB_ID | JOB_TITLE | MIN_SALARY |
+--------+-----------+------------+
|   1001 | OFFICER   |       8000 |
+--------+-----------+------------+

Sample Solution:

-- Inserting a new record into the 'jobs' table
INSERT INTO jobs VALUES(1001, 'OFFICER', 8000);

Let execute the above code in MySQL command prompt.

mysql> INSERT INTO jobs VALUES(1001,'OFFICER',8000);
ERROR 1062 (23000): Duplicate entry '1001' for key 'JOB_ID'

Explanation:

The above MySQL code inserts a new record into the 'jobs' table with values 1001 for 'JOB_ID', 'OFFICER' for 'JOB_TITLE', and 8000 for 'MIN_SALARY'.

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

Previous:Write a MySQL query insert rows from country_new table to countries table.
Next:Write a MySQL query to insert one row in jobs table to ensure that no duplicate value will be entered in the job_id column.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.