Getting the last record in SQL in WHERE condition Getting the last record in SQL in WHERE condition sql-server sql-server

Getting the last record in SQL in WHERE condition


Since the 'last' row for ID 1 is neither the minimum nor the maximum, you are living in a state of mild confusion. Rows in a table have no order. So, you should be providing another column, possibly the date/time when each row is inserted, to provide the sequencing of the data. Another option could be a separate, automatically incremented column which records the sequence in which the rows are inserted. Then the query can be written.

If the extra column is called status_id, then you could write:

SELECT L1.*  FROM LoanTable AS L1 WHERE L1.Status_ID = (SELECT MAX(Status_ID)                         FROM LoanTable AS L2                        WHERE L2.Loan_ID = 1);

(The table aliases L1 and L2 could be omitted without confusing the DBMS or experienced SQL programmers.)

As it stands, there is no reliable way of knowing which is the last row, so your query is unanswerable.


Does your table happen to have a primary id or a timestamp? If not then what you want is not really possible.

If yes then:

    SELECT TOP 1 status    FROM loanTable    WHERE loan_id = 1    ORDER BY primaryId DESC    -- or    -- ORDER BY yourTimestamp DESC


I assume that with "last status" you mean the record that was inserted most recently? AFAIK there is no way to make such a query unless you add timestamp into your table where you store the date and time when the record was added. RDBMS don't keep any internal order of the records.