I am sure it would be an aggregate function because it is going to count a collection of data.
However, how does any COUNT() function operate in MySQL to perform its respective actions?
Not 100% clear what you are looking for, but for selecting a count of null values in a column, I use something like this:
SELECT SUM(CASE WHEN columnname IS NULL THEN 1 ELSE 0 END) FROM tablename;
When the value is NULL, it is assigned the value 1 otherwise 0, then summed over whatever aggregate you need.
The COUNT(*) is an aggregate function. In the SELECT list, the expression COUNT(*) will return a count of rows. Without a GROUP BY clause, all rows will be collapsed into a single row, and the COUNT(*) aggregate will contain a non-negative integer value representing the number of rows that were collapsed... a "count" of the number of rows.
As you seem to be aware, other expressions involving the COUNT() aggregate operate a little differently, with respect to NULL values.
In the SELECT list, an expression COUNT(expr) operates exactly like COUNT(*) except for rows with values of expr that evaluate to NULL are not included in the count.
This all operates according to the specification.
As far as the non-existent COUNTNULL() function, it depends what you want that to achieve. If you wanted to get a count of the rows that had a NULL value for an expression, you could perform a conditional test, and return a non-NULL value, and use the existing COUNT aggregate, for example:
SELECT COUNT(CASE WHEN expr IS NULL THEN 1 ELSE NULL END) AS `COUNTNULL`
FROM ...
I don't remember where I learned this technique, but arguably the most elegant -- or at least minimalistic -- way to invert the logic of COUNT() is with this expression, which admittedly gives a first impression that black magic may somehow be involved... but it's perfectly legitimate:
COUNT(column1 IS NULL OR NULL)
...this correctly counts only the rows where column1 is null, because it is equivalent to the following expression...
COUNT( (column1 IS NULL) OR (NULL) )
It's a boolean expression that can only ever evaluate to 1 ("true," when column1 is null, and this row is thus counted), or NULL (otherwise, so the row will not be counted).
Logically, it's equivalent to the CASE expression offered by #spencer7593.
Related
I have been exploring dbt tools and I came across the following code snippet :
coalesce(customer_orders.number_of_orders, 0) as number_of_orders
I understand that a coalesce function is used to return the first non-null value in a list. What I do not understand is what does the zero in the second parameter signify?
The COALESCE function returns the first non-null value in a list. COALESCE can take n number of arguments.
COALESCE(val1, val2, ...., val_n)
So according to the query:
coalesce(customer_orders.number_of_orders, 0) as number_of_orders
In case customer_orders.number_of_orders is NULL the result returned in number_of_orders would be 0.
COALESCE can use as many arguments as you want. In most cases (like in your example), COALESCE(some_column,0) is used to prevent that creating a sum or building an average will not lead to the desired result.
Assume there are three columns and you want to sum them. In case you don't use COALESCE, the sum will be NULLeven if only one of your three columns is NULL. So you will use COALESCEand replace NULL values by zero in order to receive the sum of all NOT NULL values.
You can "translate" COALESCE into a CASE WHEN construct:
COALESCE(column1,0)
does following:
CASE WHEN column1 IS NULL THEN 0 ELSE column1 END
Another use case of COALESCE is to replace column1 by column2 if column1 is NULL, if also column2 is NULL, take column3 etc.
I created an example here, so you can see what I mean:
db<>fiddle
I have an sql query that could potentially return null values, in the event of this I want the query to return '0'. Here is the query
SELECT (select count(goal) from fixtures where goal='1' and fixture='$fixture') as goalCountHome
from fixtures where fixture='$fixture'LIMIT 1
Any help much appreciated!
In MySql use IFNULL() function. For MsSql use ISNULL() function.
If you are using MySql, IFNULL(<column_name>, 0) should do.
This query:
SELECT (select count(goal) from fixtures where goal='1' and fixture='$fixture') as goalCountHome
FROM fixtures
WHERE fixture = '$fixture'
LIMIT 1
cannot return NULL values. The subquery is an aggregation query with no GROUP BY, so it always returns one row. That row will contain a result from COUNT(). COUNT() itself can never return a NULL value. If there are no rows, then the value will be zero.
The outer query might return no rows but that is different from NULL values.
Of course, this query is way overcomplicated, and should simply be:
SELECT COUNT(*) as goalCountHome
FROM fixtures
WHERE fixture = ? AND -- pass this in as a parameter
goal = 1 ; -- it looks like a number so I assume it is
Note that you should be passing parameters in using proper parameters rather than munging query strings.
if you need all the rows and not the rows where goal is not null you could use count(*)
select count(*)
from fixtures
where goal=1
and fixture='$fixture'
count(goal) return the number of rows where goal is not null
count(*) return the total number rows selected
otherwise in general when you need not null values in mysql you can ifnull(your_column, value) or coalesce(your_column, value)
based on you comment seems you need sum(goal)
select sum(ifnull(goal,0))
from fixtures
where goal=1
and fixture='$fixture'
I have a WHERE CLAUSE that looks like this:
t.triggered > (SELECT MAX(time_flag) FROM triggers)
When the subquery returns a value because there is one the whole query is executed normally.
When the subquery has no returned value the comparison is always false and no records are returned even though everything is greater than 'NULL'.
I read that 'NULL' is not appropriate for comparisons, so how can the query be written in order to overcome this issue?
Something like:
t.triggered > COALESCE((SELECT MAX(time_flag) FROM triggers), '1900-01-01')
A predicate containing a NULL value, doesn't evaluate to either true, or false: it evaluates to NULL. Using COALESCE you can compare to a very old value in case the subquery returns NULL and hence return everything from your table.
Replace NULL value with default value (some minimal date) in subquery using IFNULL or COALESCE functions:
t.triggered > (SELECT IFNULL(MAX(time_flag), '1000-01-01') FROM triggers)
I have the following SQL statement:
SELECT name, SUM(growth) AS sum_buy_price, SUM(recovery) AS sum_msrp, SUM(growth)+SUM(recovery) AS total
FROM orders
WHERE id = ?
GROUP BY name
My data is coming from a CSV file that I have no control over and either 'growth' or 'recovery' can be NULL in the data, but not at the same time. I need to use ISNULL to convert the possible NULL values to zero in order for the SUM to work correctly, but I'm unsure of how/where to add the ISNULL since the SELECT is indexing another record (name).
ISNULL returns whether the argument passed is null (i.e., it is analogous to true or false). I suppose, what you need is IFNULL:
SELECT
name,
SUM(IFNULL(growth, 0)) AS sum_buy_price,
SUM(IFNULL(recovery, 0)) AS sum_msrp,
SUM(IFNULL(growth, 0))+SUM(IFNULL(recovery,0)) AS total
FROM
orders
WHERE
id = ?
GROUP BY
name
The SUM() function ignores NULL values, so you don't need to change a NULL to a 0 in order for it to work properly.
If however, all values that you're aggregating are NULL and you want to return a 0 instead of NULL you can use IFNULL() or the more common COALESCE() to show 0 as the sum instead of NULL:
SELECT COALESCE(SUM(growth),0)
ISNULL() is a valid SQL Server function, IFNULL() is the equivalent in MySQL, but all major databases make use of COALESCE() which returns the first non-NULL value in a set, ie: COALESCE(NULL,NULL,5) would return 5.
This should work for you:
SELECT name, SUM(ISNULL(growth, 0)) AS sum_buy_price,
SUM(ISNULL(recovery, 0)) AS sum_msrp,
SUM(ISNULL(growth, 0))+SUM(ISNULL(recovery,0)) AS total
FROM orders
WHERE id = ?
GROUP BY name
I was surprised to see one of my students writing
select count(title='Staff') from titles
against MySQL employees database. Does it mean to be a nice shortcut for
select sum(case when title='Staff' then 1 else 0 end) from titles
which just fails to work in MySQL 5.6 (returning full table count)?
No, this count is not a shorthand for the sum you wrote.
COUNT(exp) counts the number of rows with a not null exp.
title='Staff' is a Boolean expression, which evaluates to true if title is 'Staff', false if it's any other value or null if it's null.
So, this query is equivalent to
select count(title) from titles
which, in turn, is equivalent to
select count(*) from titles where title is not null
No!
You can't count against an condition write into brackets. It simple return all rows from that table.
select count(title='Staff') from titles
return all rows from titles