Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Count column in Postgresql

Tags:

postgresql

I have a single table laid out as such:

id  |  name  |  count
1   |  John  |
2   |  Jim   |
3   |  John  |
4   |  Tim   |

I need to fill out the count column such that the result is the number of times the specific name shows up in the column name.

The result should be:

id  |  name  |  count
1   |  John  |  2
2   |  Jim   |  1
3   |  John  |  2
4   |  Tim   |  1

I can get the count of occurrences of unique names easily using:

SELECT COUNT(name)
FROM table
GROUP BY name

But that doesn't fit into an UPDATE statement due to it returning multiple rows.

I can also get it narrowed down to a single row by doing this:

SELECT COUNT(name)
FROM table
WHERE name = 'John'
GROUP BY name

But that doesn't allow me to fill out the entire column, just the 'John' rows.

like image 268
Josh Avatar asked Sep 02 '15 19:09

Josh


People also ask

How do I update multiple columns in PostgreSQL?

It is very easy to update multiple columns in PostgreSQL. Here is the syntax to update multiple columns in PostgreSQL. UPDATE table_name SET column1 = value1, column2 = value2, ... [WHERE condition];

What is count (*) in PostgreSQL?

1) COUNT(*) You can use the PostgreSQL COUNT(*) function along with a SELECT statement to return the total number of rows in a table including the NULL values as well as the duplicates.

How do I count columns in PostgreSQL?

The PostgreSQL COUNT function counts a number of rows or non-NULL values against a specific column from a table. When an asterisk(*) is used with count function the total number of rows returns. The asterisk(*) indicates all the rows. This clause is optional.


1 Answers

you can do that with a common table expression:

with counted as (
   select name, count(*) as name_count
   from the_table
   group by name
) 
update the_table
  set "count" = c.name_count
from counted c
where c.name = the_table.name;

Another (slower) option would be to use a co-related sub-query:

update the_table
  set "count" = (select count(*) 
                 from the_table t2 
                 where t2.name = the_table.name);

But in general it is a bad idea to store values that can easily be calculated on the fly:

select id,
       name, 
       count(*) over (partition by name) as name_count
from the_table;
like image 66
a_horse_with_no_name Avatar answered Sep 19 '22 12:09

a_horse_with_no_name