简体   繁体   中英

MySQL: Adding columns where one has NULL values

Here is my query:

SELECT (contract_value + amendment_value) AS total_value
FROM contracts
ORDER BY total_value DESC

When I run it, the result for each row is NULL . Why is that so?

Each row has either a contract_value or an amendment_value , but not both. Where there is no value, it is NULL. Could that be the problem? (I could not find anything in the documentation to suggest it). If so, how do I get around it?

Use COALESCE :

SELECT
    COALESCE(contract_value, amendment_value) AS total_value
FROM contracts
ORDER BY total_value DESC;

you can use coalesce() - all are showing null because any of your two value is null - with null value any calculation will return as null, so in this case, you've to replace null with 0

SELECT coalesce(contract_value,0) + coalesce(amendment_value,0) AS total_value
FROM contracts
ORDER BY total_value DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM