Topic: Last Id

Can any one tell how to use last id of a table for reference?
Select  * from xyz where id = ( here must be last id of table)

Re: Last Id

Select  * from xyz where id = ( select max(id) from xyz)

Re: Last Id

Thank you StateOne. Can you tell if I want to take one or more before max(id)? for Example if max(id) is 300 but I want to take 299 or 298 then I must type max(id-1)?.
Secondly I want to know how can I use this id in conditional statement? if.....then

4 (edited by brian.zaballa 2022-03-11 22:12:21)

Re: Last Id

Hello unforgettable, StateOne:

I'm confused. are you just trying to access the last record of your table? If so then you can just do

Select  * from xyz ORDER BY id DESC LIMIT 1

In this way you don't have to include subquery. You don't want it to slow down your query especially for a well-populated table
Then for e.g. last id is 300, being no gap in the IDs, to access 299,

Select  * from xyz ORDER BY id DESC LIMIT 1, 1

for 298

Select  * from xyz ORDER BY id DESC LIMIT 2, 1

for 297

Select  * from xyz ORDER BY id DESC LIMIT 3, 1

and so on.

For the conditional, try elaborating further the result you want to obtain for us to look for a solution.

brian

Re: Last Id

Thank you brain. In this query LIMIT 1 means one step before and other 1 is an increment.

Re: Last Id

unforgettable wrote:

Thank you brain. In this query LIMIT 1 means one step before and other 1 is an increment.

Limit is the number or record you want to fetch.

1. Limit 1, will be selecting the first record of the query
2. For Limit 1, 1, First 1 will be the offset(will skip 1 record), then the Next 1 will be the number of record you are selecting
3. For Limit 2, 1, This will skip 2 record, then select 1 record from the query

brian

Re: Last Id

Can we use it in conditional statement if....then?
How we use ( select MAX(id) from xyz) in conditional statement? for example
if (select MAX(id) from xyz = (select id_abc from xyz where id_abc = 5) then ......

Re: Last Id

unforgettable wrote:

Can we use it in conditional statement if....then?
How we use ( select MAX(id) from xyz) in conditional statement? for example
if (select MAX(id) from xyz = (select id_abc from xyz where id_abc = 5) then ......

I'm a bit confused to what you really want with if condition.

Is it If-else condition in script or in sql?
Then, can you elaborate to what extend you are going to use it.
Can you at least tell us the logic to why you want the if-else?
Try not to include sql query first and just elaborate the logic or problem.

brian

Re: Last Id

Hi brain,
           Look at attached pic and see what I want to do. This is from income_expenses project

Post's attachments

Attachment icon mvd.JPG 122.08 kb, 67 downloads since 2022-03-16 

Re: Last Id

Sorry. I really can't picture it out to what you really want to do.
I want to help but I need the exact and detailed process.

brian