0

I have a simple table with 4 columns (ID (auto gen), ip,date,visits)

ex:

1,'10.10.0.10', '2017-03-01',1

I am looking for Insert or Update in SQLite which needs to check the ip & date column and if exists update visits +1 else insert a new row.

i can issue 2 sql but wanted to keep it in 1 sql.

Is this possible in SQLite?

1 Answer 1

2

If you generate a uniqe index for IP and date you can use the insert or replace statement to achieve this in two steps:

  1. Try to query the current number of visits for IP and date; set to 0 if record not found.
  2. Execute the insert or replace for IP and date (I'm using named parameters in this example; you need to bind them to the appropriate values):

    insert or replace into Visits (id, ip, date, visits)
    values (NULL, :ip, :date, :visits + 1);
    

You can add a table contstraint to create the unique index like in the following example, or you use a separate create unique index statement:

create table Visits (..., unique (ip, date));

Addendum: There's even a possibility to update the number of visits in one query:

insert or replace into Visits (id, ip, date, visits)
    select NULL, :ip, :date, ifnull(max(visits), 0) + 1
    from Visits
    where ip = :ip and date = :date;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.