2

I have to execute multiple queries that go like:

select count(*) from table_name where product = 'abc';
select count(*) from table_name where product = 'bcd';

...

I have around 2000 such statements and executing one by one seems tedious. How can I execute them in one go and get the result in the form of some table?

Thanks

1
  • 2
    It's obvious: SELECT product, COUNT(product) FROM TableName GROUP BY product Commented Jul 27, 2021 at 10:41

2 Answers 2

4

You can go with aggregation :

select product, count(*) 
from table_name 
group by product;

If you have a large product filter then create one table & use exists :

select product, count(*) 
from table_name t
where exists (select 1 from filtertable ft where ft.product = t.product)
group by product;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I only had to select given values of 'product' that were provided so i put them inside an IN() and got the result =)
2

You don't need to write 2000 such statements.

You are doing Aggregation (getting the count of each product). Go with GROUP BY

SELECT  product, count(*) AS product_count FROM table_name GROUP BY product;

This will give you a table with products and their respective counts. Below is a sample output.

Product product_count
abc 2
def 3
ghi 1

1 Comment

Thanks I only had to select given values of 'product' that were provided so i put them inside an IN() and got the result =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.