Get alternate record from table

Question

How to fetch alternate records(even rows) from a table?

in progress 0
TheDataMonk 55 years 9 Answers 1728 views Grand Master 0

Answers ( 9 )

  1. — To fetch even records
    select * from tableA WHERE ID % 2 == 0

    — To fetch odd number of records
    select * from tableA WHERE ID % 2 != 0

  2. Select *
    from (
    Select * , row_number() OVER(order by empid desc ) As RowNumber from Employee) t
    Where t.RowNumber % 2 == 0

    Note: In case of odd records do
    RowNumber % 2 == 1

  3. *Assuming id is unique and auto-increment column*

    Select id from table
    where mod(id, 2) 0; –to fetch odd rows

    Select id from table
    where mod(id, 2) = 0; –to fetch even rows

  4. 1. To fetch Even records: select * from Table_Name WHERE ID % 2 == 0

    2. To fetch Odd records: select * from Table_Name WHERE ID % 2 != 0

  5. SELECT *
    FROM (
    SELECT *, Row_Number() OVER(ORDER BY id) AS RowNumber

    FROM table
    ) t
    WHERE t.RowNumber % 2 = 0

  6. with cte as (select *,row_number() over ( order by empld desc) as r_num from employee_table)
    select * from cte where r_num %2=0;
    select * from cte where r_num%2!=0;

  7. Assuming Table consists of ID/Sl.no which is AUTOINCREMENT and do not contain any NULL values

    Select *from Table
    where ID%2 ==0;

  8. 1. Assuming the table is ordered in increasing order of ID
    SELECT * FROM table WHERE id%2=0

    2. Assuming table is not ordered and i can order in increasing order of ID
    WITH sub AS
    (SELECT *,ROW_NUMBER() OVER (ORDER BY id ASC) AS r_nbr
    FROM table)
    SELECT * FROM sub WHERE r_nbr%2=0

Leave an answer

Browse
Browse