0

I need to sort a table by the difference of two columns as

SELECT (first - second) AS dif
 FROM table1
ORDER BY dif DESC

but the two columns can be NULL. In this case, it returns the error:

BIGINT UNSIGNED value is out of range

The solution to this error is to use IFNULL(col,0), but the problem is that I need dif to be NULL if any of the columns is NULL

asked Aug 1, 2018 at 15:28
2
  • In this case, it returns the error Extremely strange. I have tested it on MySQL 5.5.60, 5.6.10, 5.6.39, 5.6.40, 5.7.17, 5.7.22, 8.0.11 - all of them give the result you need. Commented Aug 1, 2018 at 19:42
  • @Akina you're absolutely right. The problem was not null values, but my unsigned column. Thanks for pointing me in the right direction. Commented Aug 1, 2018 at 23:26

3 Answers 3

2

You could test for the columns being null before doing the calculation.

SELECT if(isnull(first) or isnull(second),null,(ifnull(first,0) - ifnull(secon,0))) AS dif
 FROM table1
ORDER BY dif DESC
answered Aug 1, 2018 at 15:47
5

Many ways of doing this, but I find this readable:

SELECT CASE WHEN first IS NULL OR second IS NULL THEN NULL
 ELSE first - second END AS dif
 FROM table1
ORDER BY 1 DESC
answered Aug 1, 2018 at 15:45
0

If the datatype of the columns is BIGINT UNSIGNED, then consider doing CAST(x AS SIGNED)

See also the 'operator' <=>

answered Aug 19, 2018 at 2:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.