As we all know COALESCE
is an ANSI SQL standard function. It has the same functionality across different RDBMS
(ie) It returns the first NOT NULL
value from list of values.
Consider the following data setup
CREATE TABLE TableA (customerID varchar(10), salary int);
INSERT INTO TableA (customerID, salary)
VALUES
('A1', 100),
('A2', 200),
('A3', 300),
('A4',400);
CREATE TABLE TableB (customerID varchar(10), rate int);
INSERT INTO TableB (customerID, rate)
VALUES
('A1', 2),
('A2', 3),
('A3', 4);
Query :
SELECT t1.customerID,
COALESCE(t1.salary * t2.rate, 'NA') AS salary
FROM TableA t1
LEFT JOIN TableB t2
ON t1.customerID = t2.customerID
In SQL Server when I ran the above code, it generates the following error
Msg 245, Level 16, State 1, Line 64 Conversion failed when converting the varchar value 'NA' to data type int.
It's because COALESCE
function will convert the NA
to Integer since Integer
has higher precedence than varchar
.
When we run the same code in MySQL it works. Here is the Demo
My question is, Why an ANSI SQL function implemented in two different ways in two different RDBMS(SQL Server & MySQL). Till now my thought was ANSI SQL function behaves in same way in all RDBMS!
IMO, The COALESCE
is implemented in the same way in both databases as achieving this goal:
Returning first Non-Null parameter
But there is a policy in SQL Server that is not in MySQL, something like:
Just same values can union as one column
Above policy is applied in many queries:
e.g.:
SELECT 1 AS column1
UNION ALL
SELECT 'c'
SELECT
CASE A
WHEN 1 THEN 1
WHEN 2 THEN 'c'
END
FROM ...
....
I think this is not related to implementation of COALESCE
it's related to query policies of databases.