Write an SQL query to fetch 5th ,10th,15th .. records from a table?
- User
Write an SQL query to fetch 5th ,10th,15th .. records from a table?
- Assistant
To fetch every 5th record (i.e., the 5th, 10th, 15th, etc.) from a table in SQL, you can use the
ROW_NUMBER()window function along with modulo arithmetic. Here's how you can do it:SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY some_column) AS rn FROM your_table ) sub WHERE rn % 5 = 0;Explanation:
-
ROW_NUMBER() Function: The
ROW_NUMBER()window function assigns a unique sequential integer to rows within a partition, ordered bysome_column. Replacesome_columnwith the column by which you want to define the order of the records (e.g., a primary key or a date column). -
Subquery: We use a subquery to first assign row numbers to each record.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.