2

I have an sql table with 3 columns, none of which is UNIQUE ( but the pair name + role is ):

 Name | Role | Votes

What I need to do is, write an sqllite query that stick to the following rules :

  1. If a row with the given name and role already exist, votes is incremented by 1
  2. If not, a new row is created with Votes = 1

I've looked into INSERT OR REPLACE and this great post but it doesn't seem to help me that much, and I'm not even sure INSERT OR REPLACE is a viable option, since something like

INSERT OR REPLACE INTO words (name,role,votes) 
VALUES ('foo','bar', coalesce((
    select votes from words where name = 'foo' and role='bar'),0)+1)

always insterts and never replace

Community
  • 1
  • 1
kaharas
  • 597
  • 2
  • 17
  • 39

2 Answers2

4

You simply need to create unique index over your 2 columns for this to work:

CREATE UNIQUE INDEX words_name_role_idx ON words (name,role)

Note that you do not create unique index for any single column, but for combination of 2 as a whole.

After that, your REPLACE INTO statement should start working correctly:

REPLACE INTO words (name,role,votes) VALUES ('foo','bar',
    coalesce((
        SELECT votes FROM words
        WHERE name = 'foo' AND role='bar'),0
    )+1
)

(note that I have changed counter to votes above).

mvp
  • 111,019
  • 13
  • 122
  • 148
0

This query will update your record with +1.

update todo set text='raj',complete='raj',pk=((SELECT pk FROM todo where text='raj' and complete='raj')+1) where (SELECT pk FROM todo where text='raj' and complete='raj') 

EDIT YOUE QUERY

update words set name='foo',role='bar', votes =((SELECT votes FROM words where name='foo' and role='bar')+1) where (SELECT votes FROM words where name='foo' and role='bar') 

And make insert query if this condition will not true.

Rajneesh071
  • 30,846
  • 15
  • 61
  • 74