How to Delete a single row where there is no Primary key in the table and two rows have same values in a single column
In case we have a table that does have any primary key and contains two rows that have exactly same values. For e.g. consider a table named Dept which has two columns:
a. Deptno
b. Dname
And the data in the table is:
Deptno Dname
20 Marketing
20 Marketing
We can see Deptno column contains two entries with value = 20 and Dname contains same values also. This happened as the record was inserted because, no primary key was present. We cannot delete the row with a delete command. In case we want to do the same we can use Common Table Expressions and Row_Number() function:
With MyCTE as
(
Select row_number() over (order by deptno) as 'RowNumber', * from Dept
)
Select * from MyCTE
The above command will get the following result:
RowNumber Deptno Dname
1 20 Marketing
2 20 Marketing
Now as we have generated RowNumber for a run time column, we can use the same to delete the row. So our command will be:
With MyCTE as
(
Select row_number() over (order by deptno) as 'RowNumber', * from Dept
)
Delete from MyCTE where RowNumber=1
Comments