Update Oracle table column with row number - sql

I want to update a table column with row number.
Each row in empid column should update with related row number.
I tried following query.
UPDATE employee SET empid = row_number();
But this is not working. Any idea?

First, this is not the correct syntax for the row_number() function, since you're missing the over clause (resulting in an ORA-30484 error). Even if it was, this would not work, as you cannot directly use window functions in a set clause (resulting in an ORA-30483 error).
For this usecase, however, you could just use the rownum pseudo-column:
UPDATE employee SET empid = ROWNUM;
SQLFiddle

You could do something like the following. You can change the ORDER BY order the rows if needed.
UPDATE emp
SET empid = emp.RowNum
FROM (SELECT empid, ROW_NUMBER() OVER (ORDER BY empid) AS rowNum FROM employee) emp

UPDATE employee SET empid = row_number();
Firstly, it is syntactically incorrect.
Secondly, you cannot use ROW_NUMBER() analytic function without the analytic_clause.
As you replied to my comment that the order doesn't matter to you, you could simply use ROWNUM.
UPDATE employee SET empid = ROWNUM;
It will assign the pseudo-column value by randomly picking the rows. Since you are assigning EMPID, I would suggest you should consider ordering.
Usually employee ids are generated using a SEQUENCE object. There are two ways to implement the auto-increment functionality:
Oracle 11g and below - Auto-increment using trigger-sequence approach
Oracle 12c - IDENTITY column autoincrement functionality

you could also do this
create table your_table_name as
select row_number() over( order by 1) as serial_no, a.* from your_query a
this creates the serial number when you write the table itself. ( note this is not set as PK if you want it to act as pk)

Related

Update Row ID using Order By [Help]

I can't seem to get this query to work I am pretty sure I have it correct but i keep coming up with errors. I am trying to create a update query to the rows and they way they are sorted by using a where clause to a specific section as well as a join.
Here is my query:
With cte As
(
SELECT Products.Products.PartNumber, Products.Prices.ProductID, Products.Prices.CODE, Products.Prices.Price
ROW_NUMBER() OVER (ORDER BY Price DESC) AS RN
FROM Test
JOIN Products.Prices
ON Products.Products.ID = Products.Prices.ProductID
where partnumber like 'l2%'
Order by Price Desc
)
UPDATE cte SET Number=RN
Thank you.
Instead of updating the row in the table, you could create a VIEW using your ORDER BY query and other queries could check the view instead of the row.
If you want to stick to just your table, you need to check and make sure the ROW ID being set isn't conflicting with any other row. For instance, if you ORDER BY and find row with ID=6 to be the first in the new query, you update it with ID=1. However, row 1 already has ID=1, and that conflicts with your new row ID (Previously row ID=6).

how can we delete one value out of two values from table?

Is it possible to this?I have a table with two rows and 1 column.Both rows have same value.no primary key is there.can we delete 1 row?
Here's one way to do it with ROW_NUMBER() and a common table expression:
with cte as (
select *,
row_number() over (partition by id order by id) rn
from yourtable)
delete from cte
where rn = 1;
SQL Fiddle Demo
you can do this using RANK() function.
or you can use TOP keyword.
You can get fancy and use cte to delete one but if they are the same value (and the table is as simple as you're describing it), you can also delete both and add one back. Much simpler.
Surrogate Key anyone?

Deleting Duplicate Records from a Table

I Have a table called Table1 which has 48 records. Out of which only 24 should be there in that table. For some reason I got duplicate records inserted into it. How do I delete the duplicate records from that table.
Here's something you might try if SQL Server version is 2005 or later.
WITH cte AS
(
SELECT {list-of-columns-in-table},
row_number() over (PARTITION BY {list-of-key-columns} ORDER BY {rule-to-determine-row-to-keep}) as sequence
FROM myTable
)
DELETE FROM cte
WHERE sequence > 1
This uses a common table expression (CTE) and adds a sequence column. {list-of-columns-in-table} is just as it states. Not all columns are needed, but I won't explain here.
The {list-of-key-columns] is the columns that you use to define what is a duplicate.
{rule-to-determine-row-to-keep} is a sequence so that the first row is the row to keep. For example, if you want to keep the oldest row, you would use a date column for sequence.
Here's an example of the query with real columns.
WITH cte AS
(
SELECT ID, CourseName, DateAdded,
row_number() over (PARTITION BY CourseName ORDER BY DateAdded) as sequence
FROM Courses
)
DELETE FROM cte
WHERE sequence > 1
This example removes duplicate rows based on the CoursName value and keeps the oldest basesd on the DateAdded value.
http://support.microsoft.com/kb/139444
This section is the key. The primary point you should take away. ;)
This article discusses how to locate
and remove duplicate primary keys from
a table. However, you should closely
examine the process which allowed the
duplicates to happen in order to
prevent a recurrence.
Identify your records by grouping data by your logical keys, since you obviously haven't defined them, and applying a HAVING COUNT(*) > 1 statement at the end. The article goes into this in depth.
This is an easier way
Select * Into #TempTable FROM YourTable
Truncate Table YourTable
Insert into YourTable Select Distinct * from #TempTable
Drop Table #TempTable

My tricky SQL Update query not working so well

I am trying to update a table in my database with another row from another table. I have two parameters one being the ID and another being the row number (as you can select which row you want from the GUI)
this part of the code works fine, this returns one column of a single row.
(SELECT txtPageContent
FROM (select *, Row_Number() OVER (ORDER BY ArchiveDate asc) as rowid
from ARC_Content Where ContentID = #ContentID) as test
Where rowid = #rowID)
its just when i try to add the update/set it won't work. I am probably missing something
UPDATE TBL_Content
Set TBL_Content.txtPageContent = (select txtPageContent
FROM (select *, Row_Number() OVER (ORDER BY ArchiveDate asc) as rowid
from ARC_Content Where ContentID = #ContentID) as test
Where rowid = #rowID)
Thanks for the help! (i have tried top 1 with no avail)
I see a few issues with your update. First, I don't see any joining or selection criteria for the table that you're updating. That means that every row in the table will be updated with this new value. Is that really what you want?
Second, the row number between what is on the GUI and what you get back in the database may not match. Even if you reproduce the query used to create your list in the GUI (which is dangerous anyway, since it involves keeping the update and the select code always in sync), it's possible that someone could insert or delete or update a row between the time that you fill your list box and send that row number to the server for the update. It's MUCH better to use PKs (probably IDs in your case) to determine which row to use for updating.
That said, I think that the following will work for you (untested):
;WITH cte AS (
SELECT
txtPageContent,
ROW_NUMBER() OVER (ORDER BY ArchiveDate ASC) AS rowid
FROM
ARC_Content
WHERE
ContentID = #ContentID)
UPDATE
TC
SET
txtPageContent = cte.txtPageContent
FROM
TBL_Content TC
INNER JOIN cte ON
rowid = #rowID

Can I get the position of a record in a SQL result table?

If I do something like
SELECT * FROM mytable ORDER BY mycolumn ASC;
I get a result table in a specific order.
Is there a way in SQL to efficiently find out, given a PK, what position in that result table would contain the record with my PK?
You can count the number of records where the value that you are sorting on has a lower value than the record that you know the key value of:
select count(*)
from mytable
where mycolumn < (select mycolumn from mytable where key = 42)
On databases that support it, you could use ROW_NUMBER() for this purpose:
SELECT RowNr
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY mycolumn) AS RowNr,
mycolumn
FROM mytable
) sub
WHERE sub.mycolumn = 42
The example assumes you're looking for primary key 42 :)
The subquery is necessary because something like:
SELECT
ROW_NUMBER() OVER (ORDER BY mycolumn) AS RowNr
FROM mytable
WHERE sub.mycolumn = 42
Will always return 1; ROW_NUMBER() works after the WHERE, so to speak.
SQL doesn't work that way. It's set-based, which means that "position in that result table" is meaningless to the database.
You can keep track of position when you map the ResultSet into a collection of objects or when you iterate over it.
Unfortunately you cannot get "the position of a row in a table".
The best you can get, using ORDER BY and a variant of the ROW_NUMBER construct (depends on the database engine in use), is the position of a row in the resultset of the query executed.
This position does not map back to any position in the table, though, unless the ORDER BY is on a set of clustered index columns, but even then that position might be invalidated the next second.
What I would like to know is what you intended to use this "position" for.
This answer applies to MySQL
==> lower than 8.0
SET #row_number = 0;
SELECT
(#row_number:=#row_number + 1) AS num,
myColumn.first,
myColumn.second
FROM
myTable
ORDER BY myColumn.first, myColumn.second
source: http://www.mysqltutorial.org/mysql-row_number/
==> greater than 8.0
Please see MySQL ROW_NUMBER() function manual as I did not test. But it seems this function is prefered.
There's no way you can tell that without selecting an entire subset of records. If your PK is of integer type, you can
select count(*) from mytable
where id <= 10 -- Record with ID 10
order by mycolumn asc