Skip to content
Advertisement

How to get percentage of rows which are not NULL in a specific column?

I have a database setup like this:

Table called reviews

+ -------- +
|  review  |
+ -------- +
|   awda   |
|   ggagw  |
|   okok   |
|   ligjr  |
|   kkfm   |
|   seff   |
|   oawr   |
|   abke   |
|  (null)  |
|  (null)  |
|  (null)  |
|  (null)  |
|  (null)  |
|  (null)  |
|  (null)  |
+ -------- +

How do I get the percentage of how many rows there are, which are NOT NULL?

A basic “formula” of what I want:

percentage = 100 * ( (Sum of rows where review is not null) / (Amount of rows) )

For the example above, this would be: percentage = 100 * ( ( 8 ) / ( 15) ) = 53.33333333

How can I achieve that by using only one MySQL query?

Advertisement

Answer

I think the simplest way is:

select avg( review is not null ) * 100
from reviews;

MySQL treats boolean expressions as numbers in a numeric context, with 0 for false and 1 for true.

Similar method does the explicit division:

select 100*count(review) / count(*)
from reviews;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement