Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
MySQL + SQL · Lesson 90

Primary Index और Secondary Index

Primary vs Secondary Index: मुख्य अंतर

InnoDB table में clustered index वह B-tree है जिसकी leaf records complete row data रखती हैं। Declared PRIMARY KEY वही clustered index बनती है। हर अन्य index secondary index है: उसकी leaf records secondary key और row की primary-key columns रखती हैं।

QuestionClustered primary indexSecondary index
Leaf में क्या?Complete InnoDB rowIndexed columns + primary-key columns
कितने?Exactly one clustered organizationEngine limits में multiple
Main purposeRow identity और direct accessAlternative access paths
UniquenessUnique और NOT NULLOrdinary index unique होना जरूरी नहीं
Typical full-row lookupOne B-tree searchSecondary फिर clustered search
सही भाषा: “Primary index” और “clustered index” इस InnoDB context में same हैं। इसे universal SQL rule की तरह न पढ़ाएँ।

Verified Orders Lab

DROP TABLE IF EXISTS orders_index_lab;
CREATE TABLE orders_index_lab (
  order_id INT PRIMARY KEY,
  customer_id INT NOT NULL,
  status VARCHAR(20) NOT NULL,
  order_date DATE NOT NULL,
  total_amount DECIMAL(10,2) NOT NULL,
  notes VARCHAR(100)
) ENGINE = InnoDB;

INSERT INTO orders_index_lab VALUES
(1,101,'PAID',     '2026-08-01',1200.00,'School books'),
(2,101,'PENDING',  '2026-08-05', 500.00,'Stationery'),
(3,102,'PAID',     '2026-08-03', 750.00,'Uniform'),
(4,103,'CANCELLED','2026-08-04', 300.00,'Art kit'),
(5,101,'PAID',     '2026-08-10',1500.00,'Lab equipment'),
(6,102,'PENDING',  '2026-08-11', 900.00,'Sports kit'),
(7,104,'PAID',     '2026-08-12',2200.00,'Computer accessory'),
(8,101,'PAID',     '2026-08-14', 650.00,'Notebooks');
SELECT order_id, status, total_amount
FROM orders_index_lab
WHERE order_id = 5;
5 | PAID | 1500.00

Result deterministic है। Tiny table meaning दिखाती है, speed नहीं: cost-based optimizer eight rows पर index मौजूद होने के बाद भी scan choose कर सकता है।

InnoDB Clustered Index कैसे चुनता है?

  1. Table में PRIMARY KEY हो तो InnoDB उसे clustered index बनाता है।
  2. न हो तो first UNIQUE index चुनता है जिसकी all key columns NOT NULL हों।
  3. दोनों न हों तो 6-byte synthetic row ID पर hidden GEN_CLUST_INDEX बनाता है।

इसलिए every InnoDB table में clustered index होता है, भले DDL में visible primary key न हो। फिर भी application को normally meaningful, stable row identifier define करना चाहिए: hidden row ID application SQL से reference नहीं होती और deliberate identity contract नहीं देती।

CREATE TABLE students (
  student_id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  admission_no VARCHAR(20) NOT NULL UNIQUE,
  full_name VARCHAR(100) NOT NULL
) ENGINE = InnoDB;

Auto-increment surrogate एक valid design है, universal requirement नहीं। Genuinely short, immutable और authoritative natural key भी suitable हो सकती है।

Two-Step Secondary-Index Lookup

CREATE INDEX idx_customer
ON orders_index_lab (customer_id);

SELECT order_id, order_date, total_amount, notes
FROM orders_index_lab
WHERE customer_id = 101
ORDER BY order_id;
1 | 2026-08-01 | 1200.00 | School books 2 | 2026-08-05 | 500.00 | Stationery 5 | 2026-08-10 | 1500.00 | Lab equipment 8 | 2026-08-14 | 650.00 | Notebooks

Conceptually InnoDB idx_customer search करता, matching primary-key values 1, 2, 5, 8 पढ़ता और उनसे full clustered records तक जाता है। इसे bookmark lookup, row lookup या double read भी कहते हैं।

यह कहना गलत है कि secondary leaf independent physical row address रखती है। InnoDB में वह primary-key columns रखती है। इससे page split या row movement के बाद reference logically valid रहता है, लेकिन primary-key width important बनती है।

Write consequence: Primary-key value बदलना costly है क्योंकि clustered location और secondary records में carried value दोनों बदलते हैं। Stable primary keys prefer करें।

Secondary Index Query को कब Cover करता है?

DROP INDEX idx_customer ON orders_index_lab;
CREATE INDEX idx_customer_status_date
ON orders_index_lab (customer_id, status, order_date);

SELECT order_id, status, order_date
FROM orders_index_lab
WHERE customer_id = 101 AND status = 'PAID'
ORDER BY order_date;
1 | PAID | 2026-08-01 5 | PAID | 2026-08-10 8 | PAID | 2026-08-14

यह query cover हो सकती है: customer_id, status और order_date explicit index parts हैं तथा order_id हर InnoDB secondary record में stored primary key है। SELECT में notes जोड़ने पर index all requested values नहीं रखता और full clustered rows चाहिए।

EXPLAIN
SELECT order_id, status, order_date
FROM orders_index_lab
WHERE customer_id = 101 AND status = 'PAID';

Traditional EXPLAIN में Extra: Using index बताता है कि required column information index tree से मिली। इसका अर्थ केवल “index chosen” नहीं; वह अलग question key field बताती है।

Good InnoDB Primary Key Design

Propertyक्यों important
Unique और NOT NULLExactly one row identify
ShortEvery secondary record में repeat
StableClustered relocation और rewrites avoid
Simple to joinKey/foreign-key complexity कम
Insertion pattern consideredRandom wide keys page-split/locality cost बढ़ा सकती हैं

Primary key केवल “natural” होने के कारण न चुनें और surrogate automatically भी न चुनें। Business stability, width, privacy exposure, distributed ID generation, insert locality और referencing tables compare करें।

  • INT/BIGINT AUTO_INCREMENT: compact और insertion-friendly; generation coordinate करें और value को business fact न मानें।
  • UUID as text: systems में easy पर wide; binary/time-ordered form storage और locality penalty reduce कर सकती है।
  • Composite natural key: true identity enforce कर सकती है, पर full width हर secondary record और foreign key में repeat होती है।

Compact surrogate clustered primary key रखते हुए UNIQUE secondary index business identifier enforce कर सकती है।

Definitions Inspect और Plan Verify करें

SHOW CREATE TABLE orders_index_lab;
SHOW INDEX FROM orders_index_lab;

EXPLAIN FORMAT=TREE
SELECT order_id, order_date
FROM orders_index_lab
WHERE customer_id = 101 AND status = 'PAID';

EXPLAIN ANALYZE FORMAT=TREE
SELECT order_id, order_date
FROM orders_index_lab
WHERE customer_id = 101 AND status = 'PAID';
  • SHOW INDEX name, uniqueness, key-part sequence और estimated cardinality confirm करता है।
  • EXPLAIN normal SELECT result run किए बिना estimated plan दिखाता है।
  • EXPLAIN ANALYZE SELECT run करके TREE में actual timing, rows और loops देता है।
Safety: EXPLAIN ANALYZE statement execute करता है। Safe representative SELECT लें; write statements controlled environment में ही test करें। Plan data volume, distribution, statistics, selected columns और settings से बदल सकता है।

Common Mistakes और Faculty Checklist

  • Storage engine बताए बिना every ordinary index को “non-clustered” कहना।
  • Physical row order को guaranteed SELECT order समझना; SQL output के लिए explicit ORDER BY चाहिए।
  • Secondary-index cost count किए बिना long mutable business string primary key बनाना।
  • Composite workload देखने की जगह every predicate के लिए single-column index बनाना।
  • Chosen index को clustered lookup elimination मानना; covering plan verify करें।
  • Representative production-like data की जगह eight-row lab पर speed judge करना।
  • INSERT, UPDATE, DELETE, memory और storage overhead ignore करना।

अभ्यास: lab चलाएँ; primary-key और customer lookup compare करें; SELECT list से notes add/remove करें; Extra inspect करें; फिर representative volume पर repeat करें। आगे composite index design और EXPLAIN query plan पढ़ें।

Official संदर्भ

Cluster selection, secondary-record contents, primary-key width और covering-plan behavior official MySQL 8.4 manual से verify किए गए हैं।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या MySQL primary key हमेशा clustered index होती है?
InnoDB table में declared PRIMARY KEY clustered index बनती है। Other storage engines data अलग तरह organize कर सकते हैं, इसलिए rule बताते समय engine स्पष्ट रखें।
InnoDB table में primary key न हो तो क्या होता है?
InnoDB first suitable UNIQUE index चुनता है जिसकी all key columns NOT NULL हों; ऐसा index न मिले तो synthetic row ID पर hidden GEN_CLUST_INDEX बनाता है।
InnoDB primary key short क्यों रखनी चाहिए?
Every secondary-index record primary-key columns रखता है। Wide primary key हर secondary index का size तथा memory और I/O cost बढ़ा सकती है।
क्या secondary-index lookup हमेशा clustered index पढ़ता है?
हमेशा नहीं। Secondary index में query की every required value हो तो covering plan वहीं से answer दे सकता है। अन्यथा stored primary key से clustered record fetch होता है।
क्या InnoDB table में एक से अधिक clustered indexes हो सकते हैं?
नहीं। Row data one clustered index से organized होता है। Engine limits और maintenance cost के भीतर table में many secondary indexes हो सकते हैं।
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.