Home > Software engineering >  How to SELECT last row If WHERE don't match any data in MySql
How to SELECT last row If WHERE don't match any data in MySql

Time:08-02

I want to return last row if condition is not true

I tried like this :- SELECT * FROM cash_book_master WHERE Date = "2022-08-00" ORDER BY ID LIMIT 1

But cant get the desire result, Please help me.

This is my table Structure

| Field           | Type          | Null | Key | Default | Extra          |
 ----------------- --------------- ------ ----- --------- ---------------- 
| ID              | int           | NO   | PRI | NULL    | auto_increment |
| Opening_Balance | decimal(20,0) | NO   |     | NULL    |                |
| Date            | varchar(50)   | NO   |     | NULL    |                |
 ----------------- --------------- ------ ----- --------- ---------------- 

I want if condition true then it working fine but, If condition false then select last row so i can display last row opening balance

CodePudding user response:

how about moving your where clause to a case statement

SELECT * FROM cash_book_master 
ORDER BY Case when  Date = "2022-08-00" then 1 else 2 end, ID
 LIMIT 1
  • Related