# Group By and Having

The **group by** clause is used to group records by an attribute/set of attributes. An aggregate operation (count, max, min, avg etc.) can be performed after grouping.

```
select * from r group by attribute
```

Note that all the attributes in the select clause (that aren't part of an aggregate function) must be present in the group by clause.

```
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
```

is an erroneous query because ID isn't in the group by clause (salary can be exempted because it is part of the avg aggregate function).

The **having** clause is a predicate for grouping.

Note that the **where** clause is applied before grouping and the **having** clause is applied after grouping.

```
select * from r where P1 group by attribute having P2
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://vikram-bajaj.gitbook.io/cs-gy-6083-principles-of-database-systems/main-1/sql/dml-commands/group-by-and-having.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
