← Back to MySQL Course | Chapter 5: Inserting & Selecting Data | Lesson 4 of 6

SELECT DISTINCT

SELECT DISTINCT एक box में crayons के अलग-अलग colors की एक list माँगने जैसा है, हर color को सिर्फ एक बार mention करते हुए चाहे कितने भी crayons उसे share करें।
Syntax
sql
SELECT DISTINCT column1[, column2] FROM table_name;

DISTINCT का Introduction

SELECT DISTINCT एक result set से duplicate rows हटाता है, specified column या columns में मौजूद सिर्फ unique values return करते हुए — मान लीजिए, एक customers table में हर distinct city जल्दी list करने के लिए उपयोगी।

उदाहरण: Introduction to DISTINCT

sql
SELECT DISTINCT city FROM users;

कई Columns पर Distinct

जब DISTINCT कई columns में apply किया जाता है, MySQL *combination* को uniqueness key की तरह treat करता है, इसलिए एक row सिर्फ तभी filter out होती है जब हर listed column किसी दूसरी row से exactly match करे।

उदाहरण: Distinct on Multiple Columns

sql
SELECT DISTINCT city, country FROM users;

Unique Values Count करना

DISTINCT को COUNT के साथ pair करना (जैसे COUNT(DISTINCT column) में) आपको बताता है कि किसी column में कितनी unique values exist करती हैं, जो एक plain COUNT से अलग है जिसमें हर duplicate शामिल होगा।

उदाहरण: Counting Unique Values

sql
SELECT COUNT(DISTINCT city) FROM users;

Distinct और Null Values

MySQL DISTINCT purposes के लिए किसी column में सभी NULL values को एक-दूसरे के बराबर मानता है, किसी भी संख्या में NULLs को result set में एक single NULL row में collapse करते हुए।

उदाहरण: Distinct and Null Values

sql
SELECT DISTINCT city FROM users; -- multiple NULL rows collapse into one

Distinct बनाम Group By

DISTINCT एक result list के simple deduplication के लिए सबसे अच्छा है; एक बार आपको category से grouped aggregated calculations चाहिए हों, GROUP BY ज़्यादा उपयुक्त और ज़्यादा powerful tool है।

उदाहरण: Distinct vs Group By

sql
SELECT DISTINCT city FROM users;
SELECT city, COUNT(*) FROM users GROUP BY city;
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. यह उम्मीद करना कि DISTINCT city, country सिर्फ city को unique बनाएगा, जबकि यह combination के duplicates हटाता है।
  2. id जैसा एक non-distinct column add करना, जो हर row को unique बना देता है ताकि कुछ भी न हटे।
  3. unique cities के लिए COUNT(DISTINCT city) के बजाय COUNT(city) इस्तेमाल करना।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.