3

How can I select specific rows in a MySQL Table? So instead of selecting ... ORDER BY date can I do something like SELECT * FROM Posts FROM(5) TO(10) ORDER BY date DESC where I would be selecting Posts 5 to 10 in the descending order?

1
  • 1000 rep and no searches on google before? hmm Commented Jun 13, 2011 at 17:29

6 Answers 6

11

Your question is a little ambiguous. There are two possibilities:

  1. You want only part of the results to be retrieved from the database, for example from the 5th one to the 10th one:

    SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 6 OFFSET 4
    

    which will skip the 4 first results and given you next 6 results (beginning with 5th from the original set and ending with 10th from the original set).

  2. You want results with specific IDs between 5 (inclusive) and 10 (inclusive):

    SELECT * FROM `posts` WHERE `id` BETWEEN 5 AND 10 ORDER BY `date` DESC
    

    or (which can be useful if the list of IDs is not the whole range):

    SELECT * FROM `posts` WHERE `id` IN (5,6,7,8,9,10) ORDER BY `date` DESC
    

    but this last example is only to show you different way of picking "specific" rows.

Sign up to request clarification or add additional context in comments.

Comments

3

use limit:

SELECT * FROM Posts ORDER BY date DESC LIMIT 5, 5

http://php.about.com/od/mysqlcommands/g/Limit_sql.htm

1 Comment

LIMIT goes after ORDER BY, i.e. at the end of the statement (see the manual)
1

You can use limit operator in mysql to do this. Ex: SELECT * FROM posts LIMIT 5 , 5;

Comments

1

Alternative Syntax which is more readable in my opinion:

SELECT * FROM Posts ORDER BY date DESC LIMIT 5 OFFSET 5

The first number indicates the number of results returned, the second one defines the offset from where to begin with.

If you use the LIMIT 5,5 it's the other way round.

1 Comment

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY date DESC' at line 1
-1

You can use the limit:

SELECT * FROM tabel ORDER BY date DESC LIMIT 5,5 

(5th till 10th record based on descending date).

2 Comments

Please read that help content regarding code inclusion in the answer
worthless giving a -1 for that tho.
-2
SELECT * FROM Posts ORDER BY date DESC limit 5, 10

2 Comments

Please read that help content regarding code inclusion in the answer
This is incorrect. ORDER BY should go after LIMIT. Check the documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.