← Back to PostgreSQL Course | Chapter 7: Aggregations & Grouping | Lesson 2 of 7

GROUP BY का उपयोग

GROUP BY rows को groups में split करता है ताकि हर group को अपना aggregate result मिले।

In this page:

  1. GROUP BY
Syntax
sql
SELECT group_column, aggregate_function(column)
FROM table_name
GROUP BY group_column;

GROUP BY

हर selected column या तो GROUP BY में होना चाहिए या एक aggregate function के अंदर। आप कई columns और expressions से group कर सकते हैं।

Group order guaranteed नहीं है, इसलिए ORDER BY add करें।

PostgreSQL column position और alias से group करना allow करता है, हालाँकि names clearer हैं।

Note: predictable result order के लिए GROUP BY के बाद ORDER BY add करें।

उदाहरण: GROUP BY

sql
CREATE TABLE sales (id INTEGER PRIMARY KEY, item TEXT, region TEXT, qty INTEGER);
INSERT INTO sales VALUES (1,'pen','N',5),(2,'book','N',1),(3,'pen','S',10),(4,'book','S',3),(5,'lamp','N',2);
SELECT item, SUM(qty) AS total_qty, COUNT(*) AS orders FROM sales GROUP BY item ORDER BY item;
SELECT region, item, SUM(qty) AS total_qty FROM sales GROUP BY region, item ORDER BY region, item;

-- Output:
-- item | total_qty | orders
-- book | 4 | 2
-- lamp | 2 | 1
-- pen | 15 | 2
-- region | item | total_qty
-- N | book | 1
-- N | lamp | 2
-- N | pen | 5
-- S | book | 3
-- S | pen | 10
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. ऐसे columns select करना जो grouped या aggregated नहीं हैं
  2. sorted output की उम्मीद करना
  3. बहुत सारे columns से group करना
चैप्टर सारांश
  • GROUP BY प्रति group एक row बनाता है
  • Selected columns grouped या aggregated होने चाहिए
  • कई columns finer groups देते हैं
  • Order के लिए ORDER BY add करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

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