How to query a fixed number of rows ordered by date in mysql?Can I concatenate multiple MySQL rows into one field?How to output MySQL query results in CSV format?How do I connect to a MySQL Database in Python?How to get a list of user accounts using the command line in MySQL?MySQL - Rows to ColumnsConvert text into number in MySQL queryHow to reset AUTO_INCREMENT in MySQL?Select last N rows from MySQLReference - What does this error mean in PHP?How do I import an SQL file using the command line in MySQL?

1, 2, 4, 8, 16, ... 33?

In a folk jam session, when asked which key my non-transposing chromatic instrument (like a violin) is in, what do I answer?

What is this utensil for?

2000s Animated TV show where teenagers could physically go into a virtual world

Does Fires of Invention allow adventure instant and sorceries to be played for free?

Worms crawling under skin

Why does NASA publish all the results/data it gets?

Strange Sticky Substance on Digital Camera

Writing a letter of recommendation for a mediocre student

Drawing line in notebook with Mathematica command

Replace HP Smart Array RAID Controller with newer generation controller (e.g. 410 -> 420)

What causes the traces to wrinkle like this and should I be worried

Where Does VDD+0.3V Input Limit Come From on IC chips?

Why is there not a feasible solution for a MIP?

When is it acceptable to write a bad letter of recommendation?

Is the mass of paint relevant in rocket design?

Designing a time thief proof safe

Magneto 2 How to call Helper function in observer file

To what extent is it worthwhile to report check fraud / refund scams?

What benefits does the Power Word Kill spell have?

How can this Stack Exchange site have an animated favicon?

How to deal with my team leader who keeps calling me about project updates even though I am on leave for personal reasons?

If an object moving in a circle experiences centripetal force, then doesn't it also experience centrifugal force, because of Newton's third law?

What is the meaning of "heutig" in this sentence?



How to query a fixed number of rows ordered by date in mysql?


Can I concatenate multiple MySQL rows into one field?How to output MySQL query results in CSV format?How do I connect to a MySQL Database in Python?How to get a list of user accounts using the command line in MySQL?MySQL - Rows to ColumnsConvert text into number in MySQL queryHow to reset AUTO_INCREMENT in MySQL?Select last N rows from MySQLReference - What does this error mean in PHP?How do I import an SQL file using the command line in MySQL?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am using mysql to query a DB. What I would like to do is to query NOT the full database, but only the last 1000 rows ordered by timestamp.



I have tried to use this query which doesn't work ad I would like. I know the limit is used to return a fixed number of selected elements. But that is not what I would like. I want to query a fixed number of element.



select * from mutable where name = 'myschema' ORDER BY start_time DESC LIMIT 1000;


Any help?










share|improve this question


























  • What you're after is only possible if you give it a condition, something like WHERE start_time > some_number. MySQL can't know what "last 1000 rows ordered by timestamp" are unless it orders the rows by value (full table scan) and then takes the 1000.

    – Mjh
    Mar 28 at 15:47











  • What is the difference between "return a fixed number of selected elements" which you don't want and "query a fixed number of element" which you do want. Can you explain that better? Are your intentions to use this as a subquery and you are hoping to eliminate a full table scan or is there something else you are aiming for here? If it's an optimimzation/subquery thing then you may want to read up on how mysql optimizes ORDER BY... LIMIT using indexes and the like.

    – JNevill
    Mar 28 at 15:49












  • Jnevil yes, I don't want to scan the full table because I don't need all the values in the full table, I need only 1000 elements which are the most recent. Hope it can help to understand what I mean...

    – dventi3
    Mar 28 at 16:08











  • Ambiguity. "the last 1000 rows ordered by timestamp" -- One answer (so far) assumes that "last" implies a timestamp ordering. One answer assumes that ids provide the meaning of "last". Which it it?

    – Rick James
    Apr 18 at 18:56

















0















I am using mysql to query a DB. What I would like to do is to query NOT the full database, but only the last 1000 rows ordered by timestamp.



I have tried to use this query which doesn't work ad I would like. I know the limit is used to return a fixed number of selected elements. But that is not what I would like. I want to query a fixed number of element.



select * from mutable where name = 'myschema' ORDER BY start_time DESC LIMIT 1000;


Any help?










share|improve this question


























  • What you're after is only possible if you give it a condition, something like WHERE start_time > some_number. MySQL can't know what "last 1000 rows ordered by timestamp" are unless it orders the rows by value (full table scan) and then takes the 1000.

    – Mjh
    Mar 28 at 15:47











  • What is the difference between "return a fixed number of selected elements" which you don't want and "query a fixed number of element" which you do want. Can you explain that better? Are your intentions to use this as a subquery and you are hoping to eliminate a full table scan or is there something else you are aiming for here? If it's an optimimzation/subquery thing then you may want to read up on how mysql optimizes ORDER BY... LIMIT using indexes and the like.

    – JNevill
    Mar 28 at 15:49












  • Jnevil yes, I don't want to scan the full table because I don't need all the values in the full table, I need only 1000 elements which are the most recent. Hope it can help to understand what I mean...

    – dventi3
    Mar 28 at 16:08











  • Ambiguity. "the last 1000 rows ordered by timestamp" -- One answer (so far) assumes that "last" implies a timestamp ordering. One answer assumes that ids provide the meaning of "last". Which it it?

    – Rick James
    Apr 18 at 18:56













0












0








0








I am using mysql to query a DB. What I would like to do is to query NOT the full database, but only the last 1000 rows ordered by timestamp.



I have tried to use this query which doesn't work ad I would like. I know the limit is used to return a fixed number of selected elements. But that is not what I would like. I want to query a fixed number of element.



select * from mutable where name = 'myschema' ORDER BY start_time DESC LIMIT 1000;


Any help?










share|improve this question
















I am using mysql to query a DB. What I would like to do is to query NOT the full database, but only the last 1000 rows ordered by timestamp.



I have tried to use this query which doesn't work ad I would like. I know the limit is used to return a fixed number of selected elements. But that is not what I would like. I want to query a fixed number of element.



select * from mutable where name = 'myschema' ORDER BY start_time DESC LIMIT 1000;


Any help?







mysql query-performance






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 16:19









O. Jones

62.9k11 gold badges79 silver badges117 bronze badges




62.9k11 gold badges79 silver badges117 bronze badges










asked Mar 28 at 15:44









dventi3dventi3

763 silver badges11 bronze badges




763 silver badges11 bronze badges















  • What you're after is only possible if you give it a condition, something like WHERE start_time > some_number. MySQL can't know what "last 1000 rows ordered by timestamp" are unless it orders the rows by value (full table scan) and then takes the 1000.

    – Mjh
    Mar 28 at 15:47











  • What is the difference between "return a fixed number of selected elements" which you don't want and "query a fixed number of element" which you do want. Can you explain that better? Are your intentions to use this as a subquery and you are hoping to eliminate a full table scan or is there something else you are aiming for here? If it's an optimimzation/subquery thing then you may want to read up on how mysql optimizes ORDER BY... LIMIT using indexes and the like.

    – JNevill
    Mar 28 at 15:49












  • Jnevil yes, I don't want to scan the full table because I don't need all the values in the full table, I need only 1000 elements which are the most recent. Hope it can help to understand what I mean...

    – dventi3
    Mar 28 at 16:08











  • Ambiguity. "the last 1000 rows ordered by timestamp" -- One answer (so far) assumes that "last" implies a timestamp ordering. One answer assumes that ids provide the meaning of "last". Which it it?

    – Rick James
    Apr 18 at 18:56

















  • What you're after is only possible if you give it a condition, something like WHERE start_time > some_number. MySQL can't know what "last 1000 rows ordered by timestamp" are unless it orders the rows by value (full table scan) and then takes the 1000.

    – Mjh
    Mar 28 at 15:47











  • What is the difference between "return a fixed number of selected elements" which you don't want and "query a fixed number of element" which you do want. Can you explain that better? Are your intentions to use this as a subquery and you are hoping to eliminate a full table scan or is there something else you are aiming for here? If it's an optimimzation/subquery thing then you may want to read up on how mysql optimizes ORDER BY... LIMIT using indexes and the like.

    – JNevill
    Mar 28 at 15:49












  • Jnevil yes, I don't want to scan the full table because I don't need all the values in the full table, I need only 1000 elements which are the most recent. Hope it can help to understand what I mean...

    – dventi3
    Mar 28 at 16:08











  • Ambiguity. "the last 1000 rows ordered by timestamp" -- One answer (so far) assumes that "last" implies a timestamp ordering. One answer assumes that ids provide the meaning of "last". Which it it?

    – Rick James
    Apr 18 at 18:56
















What you're after is only possible if you give it a condition, something like WHERE start_time > some_number. MySQL can't know what "last 1000 rows ordered by timestamp" are unless it orders the rows by value (full table scan) and then takes the 1000.

– Mjh
Mar 28 at 15:47





What you're after is only possible if you give it a condition, something like WHERE start_time > some_number. MySQL can't know what "last 1000 rows ordered by timestamp" are unless it orders the rows by value (full table scan) and then takes the 1000.

– Mjh
Mar 28 at 15:47













What is the difference between "return a fixed number of selected elements" which you don't want and "query a fixed number of element" which you do want. Can you explain that better? Are your intentions to use this as a subquery and you are hoping to eliminate a full table scan or is there something else you are aiming for here? If it's an optimimzation/subquery thing then you may want to read up on how mysql optimizes ORDER BY... LIMIT using indexes and the like.

– JNevill
Mar 28 at 15:49






What is the difference between "return a fixed number of selected elements" which you don't want and "query a fixed number of element" which you do want. Can you explain that better? Are your intentions to use this as a subquery and you are hoping to eliminate a full table scan or is there something else you are aiming for here? If it's an optimimzation/subquery thing then you may want to read up on how mysql optimizes ORDER BY... LIMIT using indexes and the like.

– JNevill
Mar 28 at 15:49














Jnevil yes, I don't want to scan the full table because I don't need all the values in the full table, I need only 1000 elements which are the most recent. Hope it can help to understand what I mean...

– dventi3
Mar 28 at 16:08





Jnevil yes, I don't want to scan the full table because I don't need all the values in the full table, I need only 1000 elements which are the most recent. Hope it can help to understand what I mean...

– dventi3
Mar 28 at 16:08













Ambiguity. "the last 1000 rows ordered by timestamp" -- One answer (so far) assumes that "last" implies a timestamp ordering. One answer assumes that ids provide the meaning of "last". Which it it?

– Rick James
Apr 18 at 18:56





Ambiguity. "the last 1000 rows ordered by timestamp" -- One answer (so far) assumes that "last" implies a timestamp ordering. One answer assumes that ids provide the meaning of "last". Which it it?

– Rick James
Apr 18 at 18:56












2 Answers
2






active

oldest

votes


















0
















tl;dr Sort Less Data



I guess your mutable table has an autoincrementing primary key called mutable.mutable_id.



You can then do this:



 SELECT mutable_id 
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000;


It gives you a result set of the ids of all the relevant rows. The ORDER BY ... LIMIT work then only has to sort mutable_id and start_time values, not the whole table. So it takes less space and time in the MySql server.



Then you use that query to retrieve the details:



 SELECT *
FROM mutable
WHERE mutable_id IN (
SELECT mutable_id
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000
)
ORDER BY start_time DESC;


This will fetch all the data you need without needing to scan and sort the whole table.



If you create an index on name and start_time the subquery will be faster: the query can random-access the index to the appropriate name, then scan the start_time entries one by one until it finds 1000. No need to sort; the index is presorted.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time);


If you're on MySQL 8 you can create a descending index and it's even faster.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time DESC);





share|improve this answer



























  • The subquery you're using performs what OP's original query does, why would it be faster than original query?

    – Mjh
    Mar 28 at 16:28











  • My subquery does far less work than the original query. (1) It doesn't sort the whole table just to discard most rows. (2) It can partially scan the compound index I suggested to avoid the sort step.

    – O. Jones
    Mar 28 at 17:05











  • Since name is tested with =, the issues about DESC in the INDEX do not apply.

    – Rick James
    Apr 18 at 18:40












  • INDEX(name, start_time) also applies to the first query (without the subquery). That is the optimal solution.

    – Rick James
    Apr 18 at 18:42











  • @RickJames no, it's not the optimal solution. There's a really neat way where one can use primary key and not expand index with additional data and secondary keys. You're providing false info.

    – Mjh
    Apr 18 at 18:58


















0
















This works only with auto_increment



The trick is to sort less data, like O. Jones mentioned. Problem is in telling MySQL how to do so.



MySQL can't know what "last 1000 records" are unless it sorts them based on the query. That's exactly what you want to avoid so you need to tell MySQL how to find "last 1000 records".



This trick consists of telling MySQL at which auto_increment to start looking for the data. The problem is that you're using timestamps so I'm not sure whether this fits your particular use case.



Here's the query:



SELECT * FROM mutable 
WHERE `name` = 'myschema'
AND id > (SELECT MAX(id) - 1000 FROM mutable WHERE `name` = 'myschema')
ORDER BY start_time DESC LIMIT 1000;


Problems:



  • auto_increments have gaps. These numbers aren't sequential, they're unique, calculated via sequential increment algorithm. To get better results, increase the subtraction number. You might get 1000 results, but you might get 500 results - depending on your dataset


  • if you don't have an auto_increment, this is useless


  • if the timestamps inserted are required to be sorted beforehand from larger to lower, this is useless

advantages:
- primary key is used to define the value range (where id > x), therefore dataset reduction will be the fastest possible.






share|improve this answer

























  • Another problem: It requires a temp table and a sort.

    – Rick James
    Apr 18 at 18:55











  • @RickJames - there's no problem. Naturally, you didn't explain how the nonexistent problem is solved.

    – Mjh
    Apr 18 at 18:57











  • Can someone provide EXPLAIN SELECT... for that query.

    – Rick James
    Apr 18 at 19:19











  • @RickJames I tried to reply politely, but I just can't. Could you please click the downvote button, write your own reply and just leave me be? I don't want to do the whole rite of passage with you, I get nothing out of explaining what PK is, how to use it in smart ways and that you can perform a range scan if you wanted the fastest possible solution there is. I could also go to lengths about what using temporary and using filesort really is but I don't think you'd read carefully nor that you care about helping and reading about the OP's actual problem. Have a good night.

    – Mjh
    Apr 18 at 20:02














Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55401741%2fhow-to-query-a-fixed-number-of-rows-ordered-by-date-in-mysql%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0
















tl;dr Sort Less Data



I guess your mutable table has an autoincrementing primary key called mutable.mutable_id.



You can then do this:



 SELECT mutable_id 
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000;


It gives you a result set of the ids of all the relevant rows. The ORDER BY ... LIMIT work then only has to sort mutable_id and start_time values, not the whole table. So it takes less space and time in the MySql server.



Then you use that query to retrieve the details:



 SELECT *
FROM mutable
WHERE mutable_id IN (
SELECT mutable_id
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000
)
ORDER BY start_time DESC;


This will fetch all the data you need without needing to scan and sort the whole table.



If you create an index on name and start_time the subquery will be faster: the query can random-access the index to the appropriate name, then scan the start_time entries one by one until it finds 1000. No need to sort; the index is presorted.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time);


If you're on MySQL 8 you can create a descending index and it's even faster.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time DESC);





share|improve this answer



























  • The subquery you're using performs what OP's original query does, why would it be faster than original query?

    – Mjh
    Mar 28 at 16:28











  • My subquery does far less work than the original query. (1) It doesn't sort the whole table just to discard most rows. (2) It can partially scan the compound index I suggested to avoid the sort step.

    – O. Jones
    Mar 28 at 17:05











  • Since name is tested with =, the issues about DESC in the INDEX do not apply.

    – Rick James
    Apr 18 at 18:40












  • INDEX(name, start_time) also applies to the first query (without the subquery). That is the optimal solution.

    – Rick James
    Apr 18 at 18:42











  • @RickJames no, it's not the optimal solution. There's a really neat way where one can use primary key and not expand index with additional data and secondary keys. You're providing false info.

    – Mjh
    Apr 18 at 18:58















0
















tl;dr Sort Less Data



I guess your mutable table has an autoincrementing primary key called mutable.mutable_id.



You can then do this:



 SELECT mutable_id 
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000;


It gives you a result set of the ids of all the relevant rows. The ORDER BY ... LIMIT work then only has to sort mutable_id and start_time values, not the whole table. So it takes less space and time in the MySql server.



Then you use that query to retrieve the details:



 SELECT *
FROM mutable
WHERE mutable_id IN (
SELECT mutable_id
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000
)
ORDER BY start_time DESC;


This will fetch all the data you need without needing to scan and sort the whole table.



If you create an index on name and start_time the subquery will be faster: the query can random-access the index to the appropriate name, then scan the start_time entries one by one until it finds 1000. No need to sort; the index is presorted.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time);


If you're on MySQL 8 you can create a descending index and it's even faster.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time DESC);





share|improve this answer



























  • The subquery you're using performs what OP's original query does, why would it be faster than original query?

    – Mjh
    Mar 28 at 16:28











  • My subquery does far less work than the original query. (1) It doesn't sort the whole table just to discard most rows. (2) It can partially scan the compound index I suggested to avoid the sort step.

    – O. Jones
    Mar 28 at 17:05











  • Since name is tested with =, the issues about DESC in the INDEX do not apply.

    – Rick James
    Apr 18 at 18:40












  • INDEX(name, start_time) also applies to the first query (without the subquery). That is the optimal solution.

    – Rick James
    Apr 18 at 18:42











  • @RickJames no, it's not the optimal solution. There's a really neat way where one can use primary key and not expand index with additional data and secondary keys. You're providing false info.

    – Mjh
    Apr 18 at 18:58













0














0










0









tl;dr Sort Less Data



I guess your mutable table has an autoincrementing primary key called mutable.mutable_id.



You can then do this:



 SELECT mutable_id 
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000;


It gives you a result set of the ids of all the relevant rows. The ORDER BY ... LIMIT work then only has to sort mutable_id and start_time values, not the whole table. So it takes less space and time in the MySql server.



Then you use that query to retrieve the details:



 SELECT *
FROM mutable
WHERE mutable_id IN (
SELECT mutable_id
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000
)
ORDER BY start_time DESC;


This will fetch all the data you need without needing to scan and sort the whole table.



If you create an index on name and start_time the subquery will be faster: the query can random-access the index to the appropriate name, then scan the start_time entries one by one until it finds 1000. No need to sort; the index is presorted.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time);


If you're on MySQL 8 you can create a descending index and it's even faster.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time DESC);





share|improve this answer















tl;dr Sort Less Data



I guess your mutable table has an autoincrementing primary key called mutable.mutable_id.



You can then do this:



 SELECT mutable_id 
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000;


It gives you a result set of the ids of all the relevant rows. The ORDER BY ... LIMIT work then only has to sort mutable_id and start_time values, not the whole table. So it takes less space and time in the MySql server.



Then you use that query to retrieve the details:



 SELECT *
FROM mutable
WHERE mutable_id IN (
SELECT mutable_id
FROM mutable
WHERE name = 'myschema'
ORDER BY start_time DESC
LIMIT 1000
)
ORDER BY start_time DESC;


This will fetch all the data you need without needing to scan and sort the whole table.



If you create an index on name and start_time the subquery will be faster: the query can random-access the index to the appropriate name, then scan the start_time entries one by one until it finds 1000. No need to sort; the index is presorted.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time);


If you're on MySQL 8 you can create a descending index and it's even faster.



CREATE INDEX x_mutable_start_time ON mutable (name, start_time DESC);






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 28 at 16:22

























answered Mar 28 at 16:15









O. JonesO. Jones

62.9k11 gold badges79 silver badges117 bronze badges




62.9k11 gold badges79 silver badges117 bronze badges















  • The subquery you're using performs what OP's original query does, why would it be faster than original query?

    – Mjh
    Mar 28 at 16:28











  • My subquery does far less work than the original query. (1) It doesn't sort the whole table just to discard most rows. (2) It can partially scan the compound index I suggested to avoid the sort step.

    – O. Jones
    Mar 28 at 17:05











  • Since name is tested with =, the issues about DESC in the INDEX do not apply.

    – Rick James
    Apr 18 at 18:40












  • INDEX(name, start_time) also applies to the first query (without the subquery). That is the optimal solution.

    – Rick James
    Apr 18 at 18:42











  • @RickJames no, it's not the optimal solution. There's a really neat way where one can use primary key and not expand index with additional data and secondary keys. You're providing false info.

    – Mjh
    Apr 18 at 18:58

















  • The subquery you're using performs what OP's original query does, why would it be faster than original query?

    – Mjh
    Mar 28 at 16:28











  • My subquery does far less work than the original query. (1) It doesn't sort the whole table just to discard most rows. (2) It can partially scan the compound index I suggested to avoid the sort step.

    – O. Jones
    Mar 28 at 17:05











  • Since name is tested with =, the issues about DESC in the INDEX do not apply.

    – Rick James
    Apr 18 at 18:40












  • INDEX(name, start_time) also applies to the first query (without the subquery). That is the optimal solution.

    – Rick James
    Apr 18 at 18:42











  • @RickJames no, it's not the optimal solution. There's a really neat way where one can use primary key and not expand index with additional data and secondary keys. You're providing false info.

    – Mjh
    Apr 18 at 18:58
















The subquery you're using performs what OP's original query does, why would it be faster than original query?

– Mjh
Mar 28 at 16:28





The subquery you're using performs what OP's original query does, why would it be faster than original query?

– Mjh
Mar 28 at 16:28













My subquery does far less work than the original query. (1) It doesn't sort the whole table just to discard most rows. (2) It can partially scan the compound index I suggested to avoid the sort step.

– O. Jones
Mar 28 at 17:05





My subquery does far less work than the original query. (1) It doesn't sort the whole table just to discard most rows. (2) It can partially scan the compound index I suggested to avoid the sort step.

– O. Jones
Mar 28 at 17:05













Since name is tested with =, the issues about DESC in the INDEX do not apply.

– Rick James
Apr 18 at 18:40






Since name is tested with =, the issues about DESC in the INDEX do not apply.

– Rick James
Apr 18 at 18:40














INDEX(name, start_time) also applies to the first query (without the subquery). That is the optimal solution.

– Rick James
Apr 18 at 18:42





INDEX(name, start_time) also applies to the first query (without the subquery). That is the optimal solution.

– Rick James
Apr 18 at 18:42













@RickJames no, it's not the optimal solution. There's a really neat way where one can use primary key and not expand index with additional data and secondary keys. You're providing false info.

– Mjh
Apr 18 at 18:58





@RickJames no, it's not the optimal solution. There's a really neat way where one can use primary key and not expand index with additional data and secondary keys. You're providing false info.

– Mjh
Apr 18 at 18:58













0
















This works only with auto_increment



The trick is to sort less data, like O. Jones mentioned. Problem is in telling MySQL how to do so.



MySQL can't know what "last 1000 records" are unless it sorts them based on the query. That's exactly what you want to avoid so you need to tell MySQL how to find "last 1000 records".



This trick consists of telling MySQL at which auto_increment to start looking for the data. The problem is that you're using timestamps so I'm not sure whether this fits your particular use case.



Here's the query:



SELECT * FROM mutable 
WHERE `name` = 'myschema'
AND id > (SELECT MAX(id) - 1000 FROM mutable WHERE `name` = 'myschema')
ORDER BY start_time DESC LIMIT 1000;


Problems:



  • auto_increments have gaps. These numbers aren't sequential, they're unique, calculated via sequential increment algorithm. To get better results, increase the subtraction number. You might get 1000 results, but you might get 500 results - depending on your dataset


  • if you don't have an auto_increment, this is useless


  • if the timestamps inserted are required to be sorted beforehand from larger to lower, this is useless

advantages:
- primary key is used to define the value range (where id > x), therefore dataset reduction will be the fastest possible.






share|improve this answer

























  • Another problem: It requires a temp table and a sort.

    – Rick James
    Apr 18 at 18:55











  • @RickJames - there's no problem. Naturally, you didn't explain how the nonexistent problem is solved.

    – Mjh
    Apr 18 at 18:57











  • Can someone provide EXPLAIN SELECT... for that query.

    – Rick James
    Apr 18 at 19:19











  • @RickJames I tried to reply politely, but I just can't. Could you please click the downvote button, write your own reply and just leave me be? I don't want to do the whole rite of passage with you, I get nothing out of explaining what PK is, how to use it in smart ways and that you can perform a range scan if you wanted the fastest possible solution there is. I could also go to lengths about what using temporary and using filesort really is but I don't think you'd read carefully nor that you care about helping and reading about the OP's actual problem. Have a good night.

    – Mjh
    Apr 18 at 20:02
















0
















This works only with auto_increment



The trick is to sort less data, like O. Jones mentioned. Problem is in telling MySQL how to do so.



MySQL can't know what "last 1000 records" are unless it sorts them based on the query. That's exactly what you want to avoid so you need to tell MySQL how to find "last 1000 records".



This trick consists of telling MySQL at which auto_increment to start looking for the data. The problem is that you're using timestamps so I'm not sure whether this fits your particular use case.



Here's the query:



SELECT * FROM mutable 
WHERE `name` = 'myschema'
AND id > (SELECT MAX(id) - 1000 FROM mutable WHERE `name` = 'myschema')
ORDER BY start_time DESC LIMIT 1000;


Problems:



  • auto_increments have gaps. These numbers aren't sequential, they're unique, calculated via sequential increment algorithm. To get better results, increase the subtraction number. You might get 1000 results, but you might get 500 results - depending on your dataset


  • if you don't have an auto_increment, this is useless


  • if the timestamps inserted are required to be sorted beforehand from larger to lower, this is useless

advantages:
- primary key is used to define the value range (where id > x), therefore dataset reduction will be the fastest possible.






share|improve this answer

























  • Another problem: It requires a temp table and a sort.

    – Rick James
    Apr 18 at 18:55











  • @RickJames - there's no problem. Naturally, you didn't explain how the nonexistent problem is solved.

    – Mjh
    Apr 18 at 18:57











  • Can someone provide EXPLAIN SELECT... for that query.

    – Rick James
    Apr 18 at 19:19











  • @RickJames I tried to reply politely, but I just can't. Could you please click the downvote button, write your own reply and just leave me be? I don't want to do the whole rite of passage with you, I get nothing out of explaining what PK is, how to use it in smart ways and that you can perform a range scan if you wanted the fastest possible solution there is. I could also go to lengths about what using temporary and using filesort really is but I don't think you'd read carefully nor that you care about helping and reading about the OP's actual problem. Have a good night.

    – Mjh
    Apr 18 at 20:02














0














0










0









This works only with auto_increment



The trick is to sort less data, like O. Jones mentioned. Problem is in telling MySQL how to do so.



MySQL can't know what "last 1000 records" are unless it sorts them based on the query. That's exactly what you want to avoid so you need to tell MySQL how to find "last 1000 records".



This trick consists of telling MySQL at which auto_increment to start looking for the data. The problem is that you're using timestamps so I'm not sure whether this fits your particular use case.



Here's the query:



SELECT * FROM mutable 
WHERE `name` = 'myschema'
AND id > (SELECT MAX(id) - 1000 FROM mutable WHERE `name` = 'myschema')
ORDER BY start_time DESC LIMIT 1000;


Problems:



  • auto_increments have gaps. These numbers aren't sequential, they're unique, calculated via sequential increment algorithm. To get better results, increase the subtraction number. You might get 1000 results, but you might get 500 results - depending on your dataset


  • if you don't have an auto_increment, this is useless


  • if the timestamps inserted are required to be sorted beforehand from larger to lower, this is useless

advantages:
- primary key is used to define the value range (where id > x), therefore dataset reduction will be the fastest possible.






share|improve this answer













This works only with auto_increment



The trick is to sort less data, like O. Jones mentioned. Problem is in telling MySQL how to do so.



MySQL can't know what "last 1000 records" are unless it sorts them based on the query. That's exactly what you want to avoid so you need to tell MySQL how to find "last 1000 records".



This trick consists of telling MySQL at which auto_increment to start looking for the data. The problem is that you're using timestamps so I'm not sure whether this fits your particular use case.



Here's the query:



SELECT * FROM mutable 
WHERE `name` = 'myschema'
AND id > (SELECT MAX(id) - 1000 FROM mutable WHERE `name` = 'myschema')
ORDER BY start_time DESC LIMIT 1000;


Problems:



  • auto_increments have gaps. These numbers aren't sequential, they're unique, calculated via sequential increment algorithm. To get better results, increase the subtraction number. You might get 1000 results, but you might get 500 results - depending on your dataset


  • if you don't have an auto_increment, this is useless


  • if the timestamps inserted are required to be sorted beforehand from larger to lower, this is useless

advantages:
- primary key is used to define the value range (where id > x), therefore dataset reduction will be the fastest possible.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 28 at 16:40









MjhMjh

2,3501 gold badge12 silver badges13 bronze badges




2,3501 gold badge12 silver badges13 bronze badges















  • Another problem: It requires a temp table and a sort.

    – Rick James
    Apr 18 at 18:55











  • @RickJames - there's no problem. Naturally, you didn't explain how the nonexistent problem is solved.

    – Mjh
    Apr 18 at 18:57











  • Can someone provide EXPLAIN SELECT... for that query.

    – Rick James
    Apr 18 at 19:19











  • @RickJames I tried to reply politely, but I just can't. Could you please click the downvote button, write your own reply and just leave me be? I don't want to do the whole rite of passage with you, I get nothing out of explaining what PK is, how to use it in smart ways and that you can perform a range scan if you wanted the fastest possible solution there is. I could also go to lengths about what using temporary and using filesort really is but I don't think you'd read carefully nor that you care about helping and reading about the OP's actual problem. Have a good night.

    – Mjh
    Apr 18 at 20:02


















  • Another problem: It requires a temp table and a sort.

    – Rick James
    Apr 18 at 18:55











  • @RickJames - there's no problem. Naturally, you didn't explain how the nonexistent problem is solved.

    – Mjh
    Apr 18 at 18:57











  • Can someone provide EXPLAIN SELECT... for that query.

    – Rick James
    Apr 18 at 19:19











  • @RickJames I tried to reply politely, but I just can't. Could you please click the downvote button, write your own reply and just leave me be? I don't want to do the whole rite of passage with you, I get nothing out of explaining what PK is, how to use it in smart ways and that you can perform a range scan if you wanted the fastest possible solution there is. I could also go to lengths about what using temporary and using filesort really is but I don't think you'd read carefully nor that you care about helping and reading about the OP's actual problem. Have a good night.

    – Mjh
    Apr 18 at 20:02

















Another problem: It requires a temp table and a sort.

– Rick James
Apr 18 at 18:55





Another problem: It requires a temp table and a sort.

– Rick James
Apr 18 at 18:55













@RickJames - there's no problem. Naturally, you didn't explain how the nonexistent problem is solved.

– Mjh
Apr 18 at 18:57





@RickJames - there's no problem. Naturally, you didn't explain how the nonexistent problem is solved.

– Mjh
Apr 18 at 18:57













Can someone provide EXPLAIN SELECT... for that query.

– Rick James
Apr 18 at 19:19





Can someone provide EXPLAIN SELECT... for that query.

– Rick James
Apr 18 at 19:19













@RickJames I tried to reply politely, but I just can't. Could you please click the downvote button, write your own reply and just leave me be? I don't want to do the whole rite of passage with you, I get nothing out of explaining what PK is, how to use it in smart ways and that you can perform a range scan if you wanted the fastest possible solution there is. I could also go to lengths about what using temporary and using filesort really is but I don't think you'd read carefully nor that you care about helping and reading about the OP's actual problem. Have a good night.

– Mjh
Apr 18 at 20:02






@RickJames I tried to reply politely, but I just can't. Could you please click the downvote button, write your own reply and just leave me be? I don't want to do the whole rite of passage with you, I get nothing out of explaining what PK is, how to use it in smart ways and that you can perform a range scan if you wanted the fastest possible solution there is. I could also go to lengths about what using temporary and using filesort really is but I don't think you'd read carefully nor that you care about helping and reading about the OP's actual problem. Have a good night.

– Mjh
Apr 18 at 20:02



















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55401741%2fhow-to-query-a-fixed-number-of-rows-ordered-by-date-in-mysql%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해