SQL insert duplicate | SoloLearn: Learn to code for FREE!


SQL insert duplicate

Hello so I have INSERT INTO CITY_T( City,Population) Values (Miami, 100000); My primary key is City and I don’t want to be able to add duplicates.

11/28/2018 4:36:05 AM


4 Answers

New Answer


You should declare city as primary key when creating the table create table `a`(city varchar(30) primary key) But because the table already created you'll need to alter the column to act as PK alter table `city_t` add primary key(`city`) If error happen maybe the column nees to be set to not null Alter table `city_t` modify `city` varchar(30) not null


Taste... Nice, solid answer. I'd also recommend applying a unique index on City and adding an autoincrementing integer column as the PK. It's generally not a good practice to use columns with meaningful data as primary keys for various reasons.


If your City attribute has PK constraint. So you have nothing to worry about. You cannot add a duplicate, - you will receive an error message. However, I agree with the guys. Better when you have an integer field PK with auto increment. And so that you cannot add duplicates in the City field, set UNIQUE constraints to it.