← Back to MySQL Course | Chapter 4: Constraints | Lesson 3 of 8

UNIQUE Constraint

UNIQUE एक rule जैसा है कि class में कोई दो students same locker number नहीं रख सकते। यह किसी value को repeat होने से रोकता है।
Syntax
sql
column_name datatype UNIQUE

UNIQUE को समझना

UNIQUE guarantee करता है कि कोई दो rows उस column में same value share नहीं कर सकतीं, जो one-email-per-account जैसी चीज़ें सिर्फ application-level checks पर भरोसा किए बिना enforce करने का standard तरीका है।

उदाहरण: Understanding UNIQUE

sql
CREATE TABLE users (email VARCHAR(100) UNIQUE);

Duplicate Value Errors

एक UNIQUE column में पहले से exist करने वाली एक value insert करने की कोशिश MySQL को पूरा insert reject करवाती है और चुपचाप collision allow करने के बजाय एक duplicate-key error return करवाती है।

उदाहरण: Duplicate Value Errors

sql
CREATE TABLE users (email VARCHAR(100) UNIQUE);
INSERT INTO users VALUES ('[email protected]');
INSERT INTO users VALUES ('[email protected]'); -- duplicate-key error

कई Unique Columns

एक table एक साथ कई independent UNIQUE columns रख सकती है, और आप कई columns को एक single composite UNIQUE constraint में भी combine कर सकते हैं जो सिर्फ तभी fire होता है जब *combination* repeat हो।

उदाहरण: Multiple Unique Columns

sql
CREATE TABLE registrations (
  event_id INT,
  user_id INT,
  UNIQUE (event_id, user_id)
);

मौजूदा Tables में UNIQUE Add करना

ALTER TABLE के through एक पहले से populated column में UNIQUE add करना अगर data में पहले से कोई duplicate values हों तो तुरंत fail हो जाएगा, इसलिए cleanup आमतौर पर पहले करनी होती है।

उदाहरण: Adding UNIQUE to Existing Tables

sql
ALTER TABLE users ADD UNIQUE (email);

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

UNIQUE Constraints हटाना

एक UNIQUE constraint behind the scenes एक index की तरह implement किया जाता है, इसलिए इसे हटाने का मतलब है specifically उस index को drop करना — MySQL कोई अलग unconstrain command offer नहीं करता।

उदाहरण: Dropping UNIQUE Constraints

sql
ALTER TABLE users DROP INDEX email;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि UNIQUE कई NULL values रोकता है, जबकि MySQL एक unique column में कई NULL values allow करता है।
  2. पहले से duplicate values वाले column में UNIQUE add करना, जो fail हो जाता है।
  3. दो अलग UNIQUE columns के together unique होने की उम्मीद करना, जबकि एक combined rule को UNIQUE (a, b) चाहिए।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.