Introduction
COALESCE helps you pick the first value that is not empty or missing from a list. It makes sure you get a real value instead of nothing.
COALESCE(value1, value2, ..., valueN)
SELECT COALESCE(NULL, 'apple', 'banana');
SELECT COALESCE(NULL, NULL, 10, 20);
SELECT COALESCE(NULL, NULL, NULL);
CREATE TABLE fruits (id INT, name VARCHAR(20), color VARCHAR(20)); INSERT INTO fruits VALUES (1, 'Apple', NULL), (2, NULL, 'Yellow'), (3, NULL, NULL); SELECT id, COALESCE(name, color, 'Unknown') AS fruit_name FROM fruits ORDER BY id;
COALESCE do when used in a query?COALESCE in SQL?Employees with columns FirstName, MiddleName, and LastName, what will this query return?SELECT FirstName, COALESCE(MiddleName, 'N/A') AS Middle, LastName FROM Employees;
FirstName='John', MiddleName=NULL, LastName='Doe'.SELECT COALESCE(FirstName MiddleName, 'Unknown') FROM Employees;
Orders with columns OrderID, Discount, and SpecialDiscount. Some rows have NULL in both discount columns. You want to write a query that returns OrderID and the first available discount value, or 0 if both are NULL. Which query correctly uses COALESCE to achieve this?Pass the test and this pattern moves unknown