Tuesday, March 20, 2012

Possible in SQL Server, deleting any row

Given this data:

RollNo      Name
    1       Yoko
    1       Yoko
    1       Yoko


How to delete the 3rd row?

Requirement source: http://stackoverflow.com/a/6645780/11432

create table test
(
n int,
name varchar(30)
);

insert into test values(1,'yoko'),(1,'yoko'),(1,'yoko');

select ROW_NUMBER() over(order by name) as ordinal, * from test;



 ordinal | n | name 
---------+---+------
       1 | 1 | yoko
       2 | 1 | yoko
       3 | 1 | yoko
(3 rows)


Deleting the 3rd row:

with a as
(
select ROW_NUMBER() over(order by name) as ordinal, * from test
)
delete from a where a.ordinal = 3;


-- delete last row
with a as
(
select ROW_NUMBER() over(order by name) as ordinal, * from test
)
delete from a where a.ordinal = (select MAX(ordinal) from a);

That's both possible in SQL Server, it will have error on Postgresql though:

ERROR:  relation "a" does not exist
LINE 5: delete from a where a.ordinal = 3
                    ^


********** Error **********

ERROR: relation "a" does not exist
SQL state: 42P01
Character: 91

No comments:

Post a Comment