DISTINCT, Alias और ORDER BY
Clean, Predictable Report बनाएँ
DISTINCT duplicate result rows, aliases labels और ORDER BY presentation order control करते हैं। तीनों अलग problem solve करते हैं।
students में Aarav (X-A, 86.50, Active), Meera (X-A, 91.00, Active), Kabir (X-B, 74.00, Inactive) और Sana (X-B, 88.50, Active) हैं।SELECT
s.full_name AS student_name,
s.marks AS percentage
FROM students AS s
WHERE s.status = 'Active'
ORDER BY percentage DESC, s.student_id ASC;Column और Table Aliases
AS output column को नाम या table को short local name देता है। Storage नहीं बदलता।
SELECT s.full_name AS student_name,
ROUND(s.marks / 100 * 5, 2) AS score_out_of_5
FROM students AS s;Reports में clear और joins में short table aliases लें। Select alias ORDER BY में चल सकता, पर WHERE में सामान्यतः नहीं क्योंकि filtering पहले resolve होती है।
ORDER BY with ASC and DESC
SELECT full_name, class_name, marks
FROM students
ORDER BY class_name ASC,
marks DESC,
student_id ASC;पहले class ASC, फिर same class में marks DESC और exact tie में student_id ASC apply होता है।
Deterministic Ties और NULL
Same marks पर केवल ORDER BY marks DESC tied order define नहीं करता। student_id ASC जोड़ें। MySQL ascending में NULL पहले और descending में बाद आता है। Recorded marks explicitly पहले:
ORDER BY marks IS NULL ASC,
marks DESC,
student_id ASC;Boolean expression recorded के लिए 0 और NULL के लिए 1 देता है।
DISTINCT के साथ ORDER BY
SELECT DISTINCT class_name
FROM students
ORDER BY class_name ASC;Ordering expressions को DISTINCT result से compatible रखें। Complex query में derived table/CTE से needed result select करके outer order साफ लिखें।
गलतियाँ और अभ्यास
- Alias को schema rename मानना।
- Observed order पर depend करना।
- Maintainable code में ORDER BY 2 लिखना।
- Pagination में tie-breaker भूलना।
- Bad join छिपाने के लिए DISTINCT जोड़ना।
- Active students को marks DESC, ID ASC sort करें।
- Five-point score का alias बनाएँ।
- Classes uniquely और alphabetically list करें।
- Defaults पर depend किए बिना NULL last रखें।
त्वरित सारांश
- Aliases output label और table reference short करते हैं।
- ORDER BY order define करता; ASC default और DESC reverse है।
- Unique tie-breaker deterministic output देता है।
- DISTINCT और ORDER BY अलग problems solve करते हैं।
Official संदर्भ
References 14 August 2026 को review किए गए।