UNIQUE Constraint
In this page:
column_name datatype UNIQUE
UNIQUE को समझना
UNIQUE guarantee करता है कि कोई दो rows उस column में same value share नहीं कर सकतीं, जो one-email-per-account जैसी चीज़ें सिर्फ application-level checks पर भरोसा किए बिना enforce करने का standard तरीका है।
उदाहरण: Understanding UNIQUE
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
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
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
ALTER TABLE users ADD UNIQUE (email);
UNIQUE Constraints हटाना
एक UNIQUE constraint behind the scenes एक index की तरह implement किया जाता है, इसलिए इसे हटाने का मतलब है specifically उस index को drop करना — MySQL कोई अलग unconstrain command offer नहीं करता।
उदाहरण: Dropping UNIQUE Constraints
ALTER TABLE users DROP INDEX email;
- यह मान लेना कि
UNIQUEकईNULLvalues रोकता है, जबकि MySQL एक unique column में कईNULLvalues allow करता है। - पहले से duplicate values वाले column में
UNIQUEadd करना, जो fail हो जाता है। - दो अलग
UNIQUEcolumns के together unique होने की उम्मीद करना, जबकि एक combined rule कोUNIQUE (a, b)चाहिए।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: