Home > Database > Mysql Tutorial > How to Select Every Nth Row in MySQL?

How to Select Every Nth Row in MySQL?

Mary-Kate Olsen
Release: 2024-12-10 15:37:13
Original
652 people have browsed it

How to Select Every Nth Row in MySQL?

Selecting Every n-th Row from MySQL

In database management, it often becomes necessary to resample data to obtain a coarser representation of the original dataset. Resampling can involve selecting every n-th row, which can be useful when high-resolution data is not required.

In MySQL, there is a convenient way to perform this operation using a combination of subqueries and window functions. Here's how to select every 5th row from a MySQL table:

SELECT * 
FROM ( 
    SELECT 
        @row := @row + 1 AS rownum, [column name] 
    FROM ( 
        SELECT @row := 0) r, [table name] 
) ranked 
WHERE rownum % 5 = 1 
Copy after login

In this query, the inner subquery assigns a sequential row number to each row in the original table using a user-defined variable @row. The outer subquery then filters out the rows where the row number is not divisible by 5, resulting in a table with only the 5th, 10th, 15th, and so on rows.

The above is the detailed content of How to Select Every Nth Row in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template