Select last N rows from MySQL - 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

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!

Sort records in random order for specific group of data using MySQL select query

I have a below db table structure :
Tablename : agency_mst
Fields:
id
name
is_premium
date_added
I want to sort the data so that the agencies with is_premium=1 comes first and the rest of the data is sorted by date_added desc order.
But also the is_premium=1 records should be sorted in random order. so first set of premium agencies will have random order. How can I do that using MySQL Select query.
I have built this query partially but not sure how to filter specific set of data. Below is that query:
SELECT * FROM agency_mst
ORDER BY is_premium DESC, date_added DESC
How about
SELECT *
FROM agency_mst
ORDER BY IF(is_premium=1, RAND(), -1.0), date_added DESC
That will use random ordering for the matching rows, then put the others last, and order them by date.
Be careful with performance, though. ORDER BY RAND() in any variant is a notorious performance antipattern in tables with many rows.
select t1.id,t1.name,t1.is_premium,t1.date_added from
(select (ROW_NUMBER() over (order by id))* cast(CRYPT_GEN_RANDOM(10) as int) RND,* from agency_mst) t1
order by t1.RND
SELECT id, name, is_premium , date_added ,if(is_premium ,rand()*-15,0) as first_order
FROM agency_mst
ORDER BY first_order, date_added DESC
Check This Using rand()*-15 you get -velue it show first and remain will be 0 and that will be order by date_added

how to orderby after applying limit in sql

I need to get the information from DB in such a way, the limit should be 3 rows and out of which i want to sort by descending order.
I used
select * from table where coloumn = 'Myfilter' order by serialNumber desc limit 3
after the execution I am not getting the latest three records rather the first three records ordered by descending.
Applying limit before order by
SELECT * FROM (SELECT * FROM table WHERE coloumn = 'Myfilter' ORDER BY serialNumber LIMIT 3) a ORDER BY serialNumber DESC
This query solves my question thank you all for suggestions,
SELECT * FROM (SELECT * FROM table WHERE coloumn='myFilter' ORDER BY serialnumber desc LIMIT 3) a ORDER BY serialnumber asc
the query uses to select the latest 3 rows ordered by big to small serial number then again the selected rows order where reversed, thnx #Kelvin Barsana
"SELECT * FROM table WHERE coloumn = 'Myfilter' ORDER BY serialNumber DESC LIMIT 3";

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 can I select the row with the highest ID in 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