Pikal Player
Pikal Player

Reputation: 3

How can I update a table with if condition through SQL

How could I set a query with ifs? For example:

UPDATE users.users
SET usd = usd + '500'

The problem is that I need it work only to users where the column unique_number is not the same.

Upvotes: 0

Views: 84

Answers (1)

If I got you right you want to update users but only the first row for users with same IP addresses.

If you have an auto generated primary key column named id then the query will be

with cte as 
(
    select id,usd,unique_number, row_number()over (partition by unique_number 
    order by id) rn  from users.users 
)
UPDATE users.users SET usd = usd + '500' where rn=1

Above query will update users table with usd = usd +'500' if unique_number is single. If there are duplicate unique_number then this query will update only the first occurrence.

** If usd is a number field use usd = usd + 500 instead of usd = usd + '500'

Upvotes: 1

Related Questions