COUNT()
In this page:
COUNT(*)
COUNT(column_name)
COUNT(DISTINCT column_name)
सभी Rows Count करना
COUNT() function COUNT(*) की तरह call होने पर आपकी query से match करने वाली हर row count करता है। यह total में NULL values और duplicate entries वाली rows शामिल करता है, क्योंकि यह rows count कर रहा है, किसी particular column को evaluate नहीं।
उदाहरण: Counting All Rows
CREATE TABLE orders (id INT, note TEXT);
INSERT INTO orders VALUES (1, 'a'), (2, NULL), (3, 'a');
SELECT COUNT(*) AS total_rows FROM orders;
Specific Columns Count करना
अगर आप एक star की जगह COUNT() को एक column name pass करें, यह सिर्फ उन rows count करता है जहाँ वह specific column NULL नहीं है। यह किसी भी NULL values को ignore करता है, जो यह count करने के लिए उपयोगी है कि कितने records में actually एक दिया गया field भरा है।
उदाहरण: Counting Specific Columns
CREATE TABLE orders (id INT, note TEXT);
INSERT INTO orders VALUES (1, 'a'), (2, NULL), (3, 'a');
SELECT COUNT(note) AS filled_notes FROM orders;
Unique Values Count करना
duplicates count करने से बचने के लिए आप COUNT() को DISTINCT keyword के साथ combine कर सकते हैं। यह किसी column में सिर्फ unique, non-duplicate, non-NULL values count करता है, जैसे कितने distinct customers ने orders place किए बजाय कितने orders exist करते हैं।
उदाहरण: Counting Unique Values
CREATE TABLE orders (id INT, customer_id INT);
INSERT INTO orders VALUES (1, 1), (2, 1), (3, 2);
SELECT COUNT(DISTINCT customer_id) AS unique_customers FROM orders;
एक Filter के साथ Counting
आप अपनी count query को scope down करने के लिए एक WHERE clause add कर सकते हैं। यह आपको सिर्फ एक specific condition से match करने वाली rows count करने देता है, जैसे सिर्फ इस महीने placed orders count करना।
उदाहरण: Counting with a Filter
CREATE TABLE orders (id INT, order_month TEXT);
INSERT INTO orders VALUES (1, 'Jan'), (2, 'Feb'), (3, 'Jan');
SELECT COUNT(*) AS jan_orders FROM orders WHERE order_month = 'Jan';
GROUP BY के साथ COUNT()
आप एक grand total के बजाय प्रति category एक count पाने के लिए COUNT() को एक GROUP BY clause के साथ combine कर सकते हैं। यह आपको एक single query में data के अलग groups या categories के items count करने देता है।
उदाहरण: COUNT() with GROUP BY
CREATE TABLE orders (id INT, customer_id INT);
INSERT INTO orders VALUES (1, 1), (2, 1), (3, 2);
SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id;
COUNT(column)इस्तेमाल करना और surprise होना कि उस column मेंNULLवाली rows count नहीं होतीं।- unique values चाहते हुए duplicates count करना, जबकि
COUNT(DISTINCT column)चाहिए। - एक
JOINके साथCOUNT(*)इस्तेमाल करना और distinct entities के बजाय multiplied rows count करना।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: