How to count number of occurrences for all different values in database column?

SqlDatabasePostgresql

Sql Problem Overview


I have a Postgre database that has say 10 columns. The fifth column is called column5. There are 100 rows in the database and possible values of column5 are c5value1, c5value2, c5value3...c5value29, c5value30. I would like to print out a table that shows how many times each value occurs.

So the table would look like this:

Value(of column5)          number of occurrences of the value
     c5value1                              1
     c5value2                              5
     c5value3                              3
     c5value4                              9
     c5value5                              1
     c5value6                              1
        .                                  .
        .                                  .
        .                                  .

What is the command that does that?

Sql Solutions


Solution 1 - Sql

Group by the column you are interested in and then use count to get the number of rows in each group:

SELECT column5, COUNT(*)
FROM table1
GROUP BY column5

Solution 2 - Sql

Use the GROUP BY clause and the COUNT() aggregate function:

SELECT column5, COUNT(column5) AS Occurences
FROM myTable
GROUP BY column5

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRastoView Question on Stackoverflow
Solution 1 - SqlMark ByersView Answer on Stackoverflow
Solution 2 - SqlOdedView Answer on Stackoverflow