Alright so I have this table in which until now I was using the following queries to UPDATE else do an INSERT:
$db->query("UPDATE ulogs SET invalid = invalid + 1 WHERE uid = 666 AND date = '2018-04-18'");
if ($db->affectedRows() < 1) {
$db->query("INSERT INTO ulogs (uid,date,invalid,unique,nonu,ea,ref,bo) VALUES (666,'2018-04-18',1,0,0,0,0,0)";
}
I had a regular combined index (non-unique) on uid&date columns. The update query was using the INDEX. All is fine but I was wondering if switching to ON DUPLICATE KEY UPDATE would be better, especially as the two columns' INDEX can be switched to UNIQUE. So I went ahead and modified the INDEX to an UNIQUE one, then rewrote the query as follows:
$db->query("INSERT INTO ulogs (uid,date,invalid,unique,nonu,ea,ref,bo) VALUES (666,'2018-04-18',1,0,0,0,0,0) ON DUPLICATE KEY UPDATE invalid = invalid + 1";
However, mysql explain is showing that the INDEX is not used in this case. Also for some reason it shows the query as an INSERT operation, even though an UPDATE is performed:
Also, by running the query in phpmyadmin, for some reason it shows that 2 rows have been INSERTed, while in fact only 1 row was UPDATEd with the data:
Bottom line is, which operation would be the fastest in terms of code optimization? Thank you.
INSERT ... ON DUPLICATE KEY UPDATE
is a single transaction already, so that is definitely easier to program. The alternative would be maybe a stored procedure with something along the lines ofSTART TRANSACTION ... UPDATE ... IF something THEN INSERT ... COMMIT;
I'm not sure if the exact syntax off the top of my head, but it's definitely more complicated. On the other hand it might be slightly faster. So it depends: do you prefer code simplicity or performance?