Home > MySQL > MySQL – select every Nth record

MySQL – select every Nth record

February 20th, 2009

Inspired by posts by Ray Camden and then Adrian J. Moreno, I’ve come up with the same solution for MySQL:

SELECT *
FROM (
	SELECT
		@row := @row +1 AS rownum, noun
	FROM (
		SELECT @row :=0) r, nouns
	) ranked
WHERE rownum %4 =1 

The table name is ‘nouns’. The column with data we want is ‘noun’.

As you can see from the return, it is working. This table has over 752 rows, but MySQL gave us every 4th:

select-nth_rows1

MySQL

  1. Stacey
    February 20th, 2009 at 13:37 | #1

    Nifty, but I can’t really think of a practical use for this.

  2. February 20th, 2009 at 15:31 | #2

    It would be good for a disperse sampling of data from a very large table. You don’t want a chunk of 100 rows from just the front, middle, or end.

  3. Dean
    March 10th, 2009 at 12:24 | #3

    For the life of me, I cannot get this to work for me. Anyone know if and at what version this becomes incompatible?

  4. March 10th, 2009 at 12:33 | #4

    @Dean
    I don’t know the answer to that. But I can tell you that the database server I am using is MySQL 5.1.30-community.

  5. April 21st, 2009 at 16:48 | #5

    Intriguing. You made a superb point.

  6. May 9th, 2009 at 14:03 | #6

    so say for example – I want to display ALL the rows in the resultset, BUT, every nth row I want to display a SPECIFIC row?
    How would the coding work with that?

  7. May 10th, 2009 at 09:52 | #7

    @Craig
    I’m not really sure what you mean. If you want to show every row you would just do a normal select without limits. But then specific rows, too?

  8. Sam M.
    May 20th, 2009 at 23:44 | #8

    Curious. What tool is that in the screenshot where you performed the query with the resulting rows?

  9. May 21st, 2009 at 00:15 | #9

    @Sam M.
    That would be Querious: http://www.araelium.com/querious/
    Though I am now a Sequel Pro user: http://www.sequelpro.com/ It is ssuuppeerr fast.

  10. August 14th, 2009 at 04:33 | #10

    Hi!
    This is a nice one!

    I often need every Nth row. For example if you want to visualize the data of your experiments and in Excel you can show only 32000 datapoints.

    With small modifications this statement can be used for efficient random selecting of the table records.
    You generate as many random numbers in the range [1 , count(*)] as the number of records you need and execute the following statement:

    SELECT * FROM (
       SELECT @row:=@row+1 as rownum, mytable.* FROM (
          SELECT @row:=0
       )r,mytable
    )
    ranked
    WHERE rownum IN(__HERE__IS_THE_LIST_OF_THE_RANDOM_NUMBERS)
  1. No trackbacks yet.