How can I select the row with the highest ID in MySQL? - mysql

How can I select the row with the highest ID in MySQL? This is my current code:
SELECT * FROM permlog WHERE max(id)
Errors come up, can someone help me?

SELECT * FROM permlog ORDER BY id DESC LIMIT 0, 1

if it's just the highest ID you want. and ID is unique/auto_increment:
SELECT MAX(ID) FROM tablename

For MySQL:
SELECT *
FROM permlog
ORDER BY id DESC
LIMIT 1
You want to sort the rows from highest to lowest id, hence the ORDER BY id DESC. Then you just want the first one so LIMIT 1:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement.
[...]
With one argument, the value specifies the number of rows to return from the beginning of the result set

SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;
This would return all rows with highest id, in case id column is not constrained to be unique.

SELECT MAX(id) FROM TABLENAME
This identifies the largest id and returns the value

Suppose you have mulitple record for same date or leave_type but different id and you want the maximum no of id for same date or leave_type as i also sucked with this issue,
so Yes you can do it with the following query:
select * from tabel_name where employee_no='123' and id=(
select max(id) from table_name where employee_no='123' and leave_type='5'
)

SELECT MAX(ID) FROM tablename LIMIT 1
Use this query to find the highest ID in the MySQL table.

Since both SELECT MAX(id) FROM table and SELECT id FROM table ORDER BY id DESC LIMIT 0,1 fulfill the goal, the interesting part is, which performs better.
SELECT MAX(id) FROM table: 152ms
SELECT id FROM table ORDER BY id DESC LIMIT 0,1: 25ms
(InnoDB-table with 55M rows on MySQL 8.0, 10 runs, average result)
Of course thats not representive, but gives an idea, that the ORDER BY method performs significantly better.

This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery
SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )

SELECT * FROM `permlog` as one
RIGHT JOIN (SELECT MAX(id) as max_id FROM `permlog`) as two
ON one.id = two.max_id

Related

Mysql select rows except first row

I have issue there with select from table. I want to select all rows except for first row. So .. There is my code
SELECT * FROM table ORDER BY id DESC
So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.
There is my full wrong code for select.
$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");
This should do it.
SELECT * FROM table WHERE id NOT IN (SELECT MAX(id) FROM table) ORDER BY id DESC
Try this:
SELECT *
FROM
(
SELECT *, row_number()
OVER (ORDER BY id DESC) row
FROM table
)
WHERE row != 1
It gives numbers to your selected rows and takes all of them without the one with row number 1
Try this
$other = mysql_query("SELECT * FROM table ORDER BY id DESC OFFSET 1");
THE ABOVE QUERY WONT WORK AS A LIMIT IS NEEDED
Refer to this answer
All you need is offset 1, but offset cannot be used without limit. So, I'd suggest something like:
SELECT * FROM table ORDER BY id DESC LIMIT 99999999 OFFSET 1
Warning: make sure your table doesn't contain lots of records, otherwise you will run into performance issues. Or, change the limit to something reasonable, like 10.
EDIT:
Read: How to use offset without limit
SELECT *
FROM table
WHERE id NOT IN ( SELECT id
FROM table
ORDER BY id DESC
LIMIT 1 )
ORDER BY id DESC;
You can try this.
In this case I am selecting all the rows, except the one with the biggest id.
In the example of [1,2,3,4,5], it will be :
SELECT *
FROM table
WHERE id NOT IN ( 5 )
ORDER BY id DESC;
Hope this helps!

Get last record from group data. MySql

Can anyone please help to get last record from the group.enter image description here
I think you need this:
select * from t where col = 85 order by id desc limit 1
According to your comment, this should get last records for every group: (this assumes that id is unique and "last record" means record, with highest id)
select t.* from t
inner join (select max(id) as maxid from t group by col) s
on t.id = s.maxid
To fetch the 1 row from mysql use 'limit' keyword.
MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
E.g.:
From your screenshot, subscription id is same for multiple id's you want to get last record which id is greater. The below query gets your result, grouped by subscription_id and ordered by id desc and limiting to 1 makes fetching only 1 row from database.
select * from tableName group by subscription_id order by id desc limit 1
You can used last() function.
SELECT LAST(CustomerName) AS LastCustomer FROM Customers;

Select last N rows from MySQL

I want to select last 50 rows from MySQL database within column named id which is primary key. Goal is that the rows should be sorted by id in ASC order, that’s why this query isn’t working
SELECT
*
FROM
`table`
ORDER BY id DESC
LIMIT 50;
Also it’s remarkable that rows could be manipulated (deleted) and that’s why following query isn’t working either
SELECT
*
FROM
`table`
WHERE
id > ((SELECT
MAX(id)
FROM
chat) - 50)
ORDER BY id ASC;
Question: How is it possible to retrieve last N rows from MySQL database that can be manipulated and be in ASC order ?
You can do it with a sub-query:
SELECT * FROM
(
SELECT * FROM table ORDER BY id DESC LIMIT 50
) AS sub
ORDER BY id ASC;
This will select the last 50 rows from table, and then order them in ascending order.
SELECT * FROM table ORDER BY id DESC LIMIT 50
save resources make one query, there is no need to make nested queries
SELECT * FROM table ORDER BY id DESC, datechat DESC LIMIT 50
If you have a date field that is storing the date (and time) on which the chat was sent or any field that is filled with incrementally (order by DESC) or de-incrementally (order by ASC) data per row put it as second column on which the data should be ordered.
That's what worked for me!!!! Hope it will help!!!!
Use it to retrieve last n rows from mysql
Select * from tbl order by id desc limit 10;
use limit according to N value.
if anyone need this
you can change this into
SELECT
*
FROM
`table`
WHERE
id > ((SELECT
MAX(id)
FROM
chat) - 50)
ORDER BY id ASC;
into
SELECT
*
FROM
`table`
WHERE
id > (SELECT MAX(id)- 50 FROM chat)
ORDER BY id ASC;
select * from Table ORDER BY id LIMIT 30
Notes:
* id should be unique.
* You can control the numbers of rows returned by replacing the 30 in the query

mySQL query to return last record for each table

I have a mySQl db (name "stocks") with 50 tables, each tables with
id, symbol, date, time, open, high, low, close, volume as columns (9 columns).
I would like to know what is the last record for each table, ordered for date then time.
Should I have to ORDER BY all data for each table or there is a better way to just know last record?
I am asking help for a query that just return only last record for each table in db.
Thanks
PS For last record I mean most recent as Date then Time
There are two options how to do that:
-- I would use this only if you need more than one records
SELECT * FROM table ORDER BY date DESC LIMIT 1;
-- Way to go:
SELECT * FROM table WHERE date = (SELECT MAX(date) FROM table) LIMIT 1;
Don't forget to add index on date. If it's possible you add lot's of records at the same time you will have to add:
ORDER BY id DESC -- In case that date is highest for records for last records
ORDER BY time DESC -- Every other case
To the end of query
I am going to make the assumption that the record with the largest ID is the "last" (assuming strictly increasing sequential IDs that are unique within a table). If you have a better definition of "last" that could make a difference.
To get one "last" record, you could do:
Select * from table_1 where id = (select max(id) from table_1);
To get the results of all 50 tables into a single result set, you could do:
Select * from table_1 where id = (select max(id) from table_1)
union
Select * from table_2 where id = (select max(id) from table_2)
union
Select * from table_3 where id = (select max(id) from table_3)
union...
A MySQL-specific solution could be
Select * from table_1 order by id desc limit 1
union
Select * from table_2 order by id desc limit 1
union
Select * from table_3 order by id desc limit 1
union...
Based on your edit (where you actually define what you mean by "last"):
Select * from table_1 order by date desc, time desc, id desc limit 1
union
Select * from table_2 order by date desc, time desc, id desc limit 1
union
Select * from table_3 order by date desc, time desc, id desc limit 1
union...
Here is one way to do it without sorting the table:
select * from tab1
where time = (select max(time)
from tab1
where date = (select max(date) from tab1))
and date = (select max(date) from tab1)
It should be very fast, like, O(c), provided that both columns are indexed, otherwise the time will simply be O(n)

How do I select an entire row which has the largest ID in the table?

How would I do something like this?
SQL SELECT row FROM table WHERE id=max(id)
You could use a subselect:
SELECT row
FROM table
WHERE id=(
SELECT max(id) FROM table
)
Note that if the value of max(id) is not unique, multiple rows are returned.
If you only want one such row, use #MichaelMior's answer,
SELECT row from table ORDER BY id DESC LIMIT 1
You could also do
SELECT row FROM table ORDER BY id DESC LIMIT 1;
This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id is unique among all rows. Otherwise there could be multiple rows with the maximum value for id and you'll only get one.
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
You can not give order by because order by does a "full scan" on a table.
The following query is better:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);
One can always go for analytical functions as well which will give you more control
select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1
If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.
Try with this
SELECT top 1 id, Col2, row_number() over (order by id desc) FROM Table