'Get the last non null value of a table column
Below is my table and from column B I want to get the value 3 in results.
| A | B |
|---|---|
| 1 | 1 |
| 2 | Null |
| 3 | 2 |
| 4 | Null |
| 5 | 3 |
| 6 | Null |
| 7 | Null |
| 8 | Null |
Case not working: it should return 10
| A | B |
|---|---|
| 1 | 1 |
| 2 | Null |
| 3 | 2 |
| 4 | Null |
| 5 | 3 |
| 6 | Null |
| 7 | Null |
| 8 | 10 |
Solution 1:[1]
Use a LIMIT query:
SELECT *
FROM yourTable
WHERE B IS NOT NULL
ORDER BY A DESC
LIMIT 1;
Solution 2:[2]
Do you want to get the value '3' because it is the largest in 'B' column?
If so, you can run the following query:
SELECT *
FROM Table
WHERE B IS NOT NULL
ORDER BY B DESC
LIMIT 1;
Solution 3:[3]
There is not much to go on in the question. However, assuming that you can order by the col A, the answer would be
SELECT * from table
where B is not NULL
Order by A DESC
Limit 1
If A is numeric, then the order by works fine and you get all 3 non null values from column B. Then Order by descending + limit 1 will ensure you get last value of B
Solution 4:[4]
You already received really good answers that should help you. I just want to add a futher propose that works fine if both A and B are numeric and they are always sorted like in your example, meaning the highest b entry always has the highest a value.
SELECT MAX(b) FROM tableB
WHERE b IS NOT NULL
HAVING MAX(a);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Biegeleisen |
| Solution 2 | Bogner Roy |
| Solution 3 | Ashu |
| Solution 4 | Jonas Metzler |
