> For the complete documentation index, see [llms.txt](https://dev117uday.gitbook.io/databases/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dev117uday.gitbook.io/databases/sql/tables/aggregation.md).

# Aggregation

* `COUNT (column)`
* `SUM (column)`
* `MIN & MAX`
* `LEAST & GREATEST`
* `AVG`

## `count`

```sql
SELECT COUNT(DISTINCT (movie_lang))
from movies;

 count 
-------
     8

-- with where clause

SELECT COUNT(movie_lang)
FROM movies
where movie_lang = 'English';

 count 
-------
    38
```

## Sum

```sql
select sum(revenues_domestic)
from movies_revenues;

  sum   
--------
 5719.5

select SUM(revenues_domestic::numeric)
from movies_revenues
where revenues_domestic::numeric > 200;

  sum   
--------
 3425.6

SELECT SUM(DISTINCT revenues_domestic)
FROM movies_revenues;

  sum   
--------
 5708.4
```

## Min and Max

```sql
SELECT min(movie_length), MAX(movie_length)
FROM movies

 min | max 
-----+-----
  87 | 168
```

## Average, Greatest, Latest

```sql
SELECT GREATEST(10, 20, 30, 40), LEAST(10, 20, 30, 40);

 greatest | least
----------+-------
       40 |    10

SELECT GREATEST('A', 'B', 'C', 'D'), LEAST('A', 'B', 'C', 'D');

 greatest | least
----------+-------
 D        | A

SELECT GREATEST('A', 'B', 'C', 1);

-- ERROR:  invalid input syntax for type integer: "A"
-- LINE 1: SELECT GREATEST('A', 'B', 'C', 1);

SELECT AVG(movie_length)
FROM movies;

         avg          
----------------------
 126.1320754716981132
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://dev117uday.gitbook.io/databases/sql/tables/aggregation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
