Query to select columns having zero as well as null values - mysql

SELECT ename,comm
FROM emp
WHERE ISNULL(comm,0)= 0;
Please explain this query .
This Query selects the emp records whose commission is null as well as zero.

ISNULL in MYSQL have only one parameter and it's true/false test if variable is null.
IFNULL in MYSQL has 2 params
IFNULL(expr1, expr2) - if expr1 is not NULL, IFNULL() returns expr1, otherwise it returns expr2.
IFNULL(expr1,0) return 0 in two cases:
expr1 = 0
expr1 is NULL (in that case second param - 0 is returned)
MYSQL IFNULL documentation
MYSQL DB Fiddle
In Transact-SQL there is ISNULL function with two params ISNULL ( check_expression , replacement_value ) and it works exactly like MYSQL IFNULL
T-SQL ISNULL documentation
SQL server DB Fiddle

Related

How to use ISNULL Function in mysql version (6.0.11-alpha-community)

I written the query without ISNULL Function in mysql
SELECT DISTINCT s.st_symbol,f.symbol,f.closeprice,f.ltp,f.prevclprice AS CLOSE,(((LTP-prevclprice)/(prevclprice*100))) AS per_change,f.expdate
FROM stmp_stocks_qty AS s
JOIN tbl_intraday_nsefoprice_latest AS f ON s.st_symbol = f.symbol AND f.ID IN (SELECT MAX(ID) FROM tbl_intraday_nsefoprice_latest GROUP BY SYMBOL)
ORDER BY s.st_symbol,f.ExpDate DESC,f.createdon DESC;
This query is working fine and while I execute this query I get the null values in my column based on the calculation "(((LTP-prevclprice)/(prevclprice*100)))" .
ex:
To avoid this null value I used ISNULL Function and written a query like
SELECT DISTINCT s.st_symbol,f.symbol,f.closeprice AS CLOSE,ISNULL(((LTP-prevclprice)/(prevclprice*100)),0) AS per_change,f.expdate
FROM stmp_stocks_qty AS s
JOIN tbl_intraday_nsefoprice_latest AS f ON s.st_symbol = f.symbol AND f.ID IN (SELECT MAX(ID) FROM tbl_intraday_nsefoprice_latest GROUP BY SYMBOL)
ORDER BY s.st_symbol,f.ExpDate DESC,f.createdon DESC;
But while I executing this query I'm getting this king of error
Query: SELECT DISTINCT s.st_symbol,f.symbol,f.closeprice AS CLOSE,isnull(((LTP-prevclprice)/(prevclprice*100)),0) AS per_change,f.expd...
Error Code: 1582
Incorrect parameter count in the call to native function 'isnull'
Execution Time : 0 sec
Transfer Time : 0 sec
Total Time : 0 sec
---------------------------------------------------
Here my intension is if any column is passing null value into the column it should became a 0.
Suggest me how can I achieve this without error.
I'm new to mysql
(Sorry for my bad english)
The MySQL equivalent of ISNULL is IFNULL
or
you can use coalesce(), so your query will be:
SELECT DISTINCT s.st_symbol,f.symbol,f.closeprice AS CLOSE, coalesce(((LTP-prevclprice)/(prevclprice*100)),0) AS per_change,f.expd...
ISNULL() is a function which accepts only one argument. Function tests does the argument IS NULL and returns TRUE (1) or FALSE (1) depends on the testing result.
The function which accepts 2 arguments and returns first value if it is not NULL and second value otherwise is IFNULL().

MySQL comparison of date to the max of a subquery that might return null

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)

NULL to zero with ISNULL

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

What is the difference between IFNULL and COALESCE in MySQL?

SELECT IFNULL(NULL, 'Replaces the NULL')
--> Replaces the NULL
SELECT COALESCE(NULL, NULL, 'Replaces the NULL')
--> Replaces the NULL
In both clauses the main difference is argument passing. For IFNULL it's two parameters and for COALESCE it's multiple parameters. So except that, do we have any other difference between these two?
And how it differs in MS SQL?
The main difference between the two is that IFNULL function takes two arguments and returns the first one if it's not NULL or the second if the first one is NULL.
COALESCE function can take two or more parameters and returns the first non-NULL parameter, or NULL if all parameters are null, for example:
SELECT IFNULL('some value', 'some other value');
-> returns 'some value'
SELECT IFNULL(NULL,'some other value');
-> returns 'some other value'
SELECT COALESCE(NULL, 'some other value');
-> returns 'some other value' - equivalent of the IFNULL function
SELECT COALESCE(NULL, 'some value', 'some other value');
-> returns 'some value'
SELECT COALESCE(NULL, NULL, NULL, NULL, 'first non-null value');
-> returns 'first non-null value'
UPDATE: MSSQL does stricter type and parameter checking. Further, it doesn't have IFNULL function but instead ISNULL function, which needs to know the types of the arguments. Therefore:
SELECT ISNULL(NULL, NULL);
-> results in an error
SELECT ISNULL(NULL, CAST(NULL as VARCHAR));
-> returns NULL
Also COALESCE function in MSSQL requires at least one parameter to be non-null, therefore:
SELECT COALESCE(NULL, NULL, NULL, NULL, NULL);
-> results in an error
SELECT COALESCE(NULL, NULL, NULL, NULL, 'first non-null value');
-> returns 'first non-null value'
Pros of COALESCE
COALESCE is SQL-standard function.
While IFNULL is MySQL-specific and its equivalent in MSSQL (ISNULL) is MSSQL-specific.
COALESCE can work with two or more arguments (in fact, it can work with a single argument, but is pretty useless in this case: COALESCE(a)≡a).
While MySQL's IFNULL and MSSQL's ISNULL are limited versions of COALESCE that can work with two arguments only.
Cons of COALESCE
Per Transact SQL documentation, COALESCE is just a syntax sugar for CASE and can evaluate its arguments more that once. In more detail: COALESCE(a1, a2, …, aN)≡CASE WHEN (a1 IS NOT NULL) THEN a1 WHEN (a2 IS NOT NULL) THEN a2 ELSE aN END. This greatly reduces the usefulness of COALESCE in MSSQL.
On the other hand, ISNULL in MSSQL is a normal function and never evaluates its arguments more than once. COALESCE in MySQL and PostgreSQL neither evaluates its arguments more than once.
At this point of time, I don't know how exactly SQL-standards define COALESCE.
As we see from previous point, actual implementations in RDBMS vary: some (e.g. MSSQL) make COALESCE to evaluate its arguments more than once, some (e.g. MySQL, PostgreSQL) — don't.
c-treeACE, which claims it's COALESCE implementation is SQL-92 compatible, says: "This function is not allowed in a GROUP BY clause. Arguments to this function cannot be query expressions." I don't know whether these restrictions are really within SQL-standard; most actual implementations of COALESCE (e.g. MySQL, PostgreSQL) don't have such restrictions. IFNULL/ISNULL, as normal functions, don't have such restrictions either.
Resume
Unless you face specific restrictions of COALESCE in specific RDBMS, I'd recommend to always use COALESCE as more standard and more generic.
The exceptions are:
Long-calculated expressions or expressions with side effects in MSSQL (as, per documentation, COALESCE(expr1, …) may evaluate expr1 twice).
Usage within GROUP BY or with query expressions in c-treeACE.
Etc.
Differences in SQL-Server:
There is no IFNULL() function but a similar ISNULL()
ISNULL takes only 2 parameters whereas COALESCE takes variable number of parameters
COALESCE is based on the ANSI SQL standard whereas ISNULL is a proprietary TSQL function
Validations for ISNULL and COALESCE is also different. For example, NULL value for ISNULL is converted to int, whereas for COAELSCE you have to provide a type. Ex:
ISNULL(NULL,NULL) : is int.
COALESCE(NULL,NULL) : will throw an error.
COALESCE(CAST(NULL as int),NULL) : is valid and returns int.
Data type determination of the resulting expression – ISNULL uses the first parameter type, COALESCE follows the CASE expression rules and returns type of value with highest precedence.
ifnull can only replace a null value of the first parameter. Whereas coalesce can replace any value with another value. With coalesce in standard SQL you can have many parameters transforming many values.
EDIT the example according to comments below.
Example: coalesce(null, null, null, 'b*', null, 'null*')
returns 'b*' and it is not possible to do with ifnull.
This db2 SQL will not work with COALESE, I will not see any rows retrieved.
Since I used IFNULL it is working as expected
select a.mbitno ,a.mbstqt,ifnull(b.apr,0)
from
(
select mmstcd,mbstat,mbfaci,mbwhlo,mbitno,mbstqt,MBALQT from libl.mitbal inner join libl.mitmas on
mmcono=mbcono and mmitno=mbitno
where mbcono=200 and mbstat in ('20','50') and mmstcd>0
)
as a left join
(
select mlfaci,mlwhlo,mlitno,mlstas,sum(mlstqt) as APR from libl.mitloc where mlcono=200 and mlstas='2'
group by mlfaci,mlwhlo,mlitno,mlstas
)
b on b.mlfaci=a.mbfaci and b.mlwhlo=a.mbwhlo and b.mlitno=a.mbitno
where a.mbitno in 'GWF0240XPEC' and a.mbstqt>0 and a.mbstqt<>ifnull(b.apr,0)

Is there a function equivalent to the Oracle's NVL in MySQL?

I'm selecting the max of a column from a table. But there is one problem: if there are no rows in the table, it returns null.
I want to use a function which will return a certain value if the result is null. For example with Oracle there is the NVL function which gives a certain value if the column is null. Is there an equivalent function in MySQL ?
Use coalesce:
select coalesce(column_name, 'NULL VALUE') from the_table
or you can use IFNULL(expr1,expr2)
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2.
select IFNULL(column_name, 'NULL VALUE') from the_table;
taken from:
https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull