Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql: Count rows in price range?

Tags:

sql

mysql

If I wanted to know how many entries I have where product_price is within the 500-1000 range. How can I do that?

Thanks!

like image 245
JD Isaacks Avatar asked Dec 15 '09 20:12

JD Isaacks


People also ask

How do I count number of rows in MySQL?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

How do I count rows in MySQL by group?

In MySQL, the COUNT() function calculates the number of results from a table when executing a SELECT statement. It does not contain NULL values. The function returns a BIGINT value. It can count all the matched rows or only rows that match the specified conditions.

Does count * Return the number of rows?

Answer: COUNT function is an aggregate function that can be used in 3 ways. COUNT(*) – This would COUNT all the rows returned by the SELECT QUERY.


2 Answers

I'm guessing you mean this:

SELECT COUNT(*) FROM products WHERE product_price >= 500 AND product_price <= 1000

But you didn't specify whether your interval is open, closed or half-closed. When using open or closed intervals (the above is a closed interval) you have to be careful not to miss or double count items on the boundary when tabulating all the intervals.

Depending on what you are doing, this might be better for you:

SELECT COUNT(*) FROM products WHERE product_price >= 500 AND product_price < 1000

If you want to get all the intervals, you can do that in one statement too:

SELECT
SUM(CASE WHEN product_price < 500 THEN 1 ELSE 0 END) AS price_range_1,
SUM(CASE WHEN product_price >= 500 AND product_price < 1000 THEN 1 ELSE 0 END) AS price_range_2,
SUM(CASE WHEN product_price >= 1000 THEN 1 ELSE 0 END) AS price_range_3
FROM products

Alternatively (and better in my opinion), store your interval ranges in another table and join with it.

(Many other people have pointed out the BETWEEN keyword. In case you are interested, it's equivalent to the closed interval version, i.e. the first version.)

like image 177
Mark Byers Avatar answered Sep 30 '22 05:09

Mark Byers


SELECT COUNT(*) FROM the_table WHERE price BETWEEN 10 AND 20;
like image 34
Michael Krelin - hacker Avatar answered Sep 30 '22 05:09

Michael Krelin - hacker