Like:
INSERT INTO `video_play_counts`
(`id`,`video_id`,`date`,`count`,`created`,`modified`)
VALUES
("",1,"2016-12-01",26,"2016-12-03 17:51:53","2016-12-03 17:51:53")
ON DUPLICATE KEY UPDATE
`count` = GREATEST(`count`,VALUES(`count`)),
`modified` = IF(VALUES(`count`) > `count`,VALUES(`modified`),`modified`)
So, I have a unique key on video_id and date and when I make an UPDATE on this unique key, in the case that the new count value is bigger the existing one, I would like to also update the modified field accordingly.
The count field updates as expected but the modified field does not get the new value in the case of an UPDATE.
Please note that I'm using this to do multiple insert/update in one query, just in this example it has only one set of values.
What am I doing wrong ?
I have not tested, but i am nearly sure that you must switch the last 2 line of your query, so that you first set modified and the set countto VALUES(count), else count is set to the GREATEST and never greater count
Related
I need assistance trying to find a problem where 1 record/row was updated but the entire table got updated with the same value. Need to understand how this could have happened and implement a method to prevent it from doing so again.
update TABLE set pushID='1234567890' where userID='111222333' ;
What would that update statement do if the userID value equaled nothing or equaled NULL? Could that cause the update statement to update every single row with the same pushID?
IE: update TABLE set pushID='1234567890' where userID='' ;
Could a blank userID value cause this? If not, what could cause this? If so, how could I write the query statement to prevent this from happening again?
What would that update statement do if the userID value equaled nothing or equaled NULL?
If the userID is NULL, then the condition becomes userID = NULL. This will always evaluate as false. In other words, no record will be updated.
If the userID is the empty string, then the condition becomes userID = ''. This will only update records where userID is equal to the empty string. I would expect that userID is the primary key of your table, so it would be suprising the find an empty value. And even if there is one, it will be unique, so a unique record will be updated.
As you see, none of the two above use case would generate a massive update of the table. The most probable option is that the query was triggered without an actual WHERE clause, like:
update TABLE set pushID='1234567890'
In case these are altogether integer ID, you should not convert them to string with ''. Doing so may lead to unexpected results (never tried, but it seems to be a possible cause for the comparison in the WHERE condition to fail). For example:
UPDATE TABLE SET pushID=1234567890 WHERE userID=111222333;
When all records are being updated, the query lacks the WHERE condition. Make sure to have posted the correct query, because this query should update nothing when the WHERE condition fails to match.
I have added a new column as "DateOrder" to my existing table called "orders" and I need to add (insert) data to the new column.
The only way I have found is using the "Update, Set, Where" syntax, however, it forces me to add values each by repeating the syntax.
I would appreciate if you help me how I can insert all my values at once.
Four rows only? Then use CASE WHEN in the SET clause:
update orders
set dateorder =
(
case id
when 1 then date '2018-10-13'
when 2 then date '2017-08-24'
when 3 then date '2019-01-11'
when 4 then date '2018-02-02'
end
);
Don't store dates as integers. Store them as dates as shown.
Initially, while creating the new column set a default value to it. And see if it has any binding with others. Then after you can directly insert new values to new records and update previous records just by update.
I am doing the following SQL tutorial: http://sql.learncodethehardway.org/book/ex11.html
and in this exercise the author says in the second paragraph:
In this situation, I want to replace my record with another guy but
keep the unique id. Problem is I'd have to either do a DELETE/INSERT
in a transaction to make it atomic, or I'd need to do a full UPDATE.
Could anyone explain to me what the problem is with doing an UPDATE, and when we might choose REPLACE instead of UPDATE?
The UPDATE code:
UPDATE person SET first_name = "Frank", last_name = "Smith", age = 100
WHERE id = 0;
Here is the REPLACE code:
REPLACE INTO person (id, first_name, last_name, age)
VALUES (0, 'Frank', 'Smith', 100);
EDIT: I guess another question I have is why would you ever do a DELETE/INSERT instead of just an UPDATE as is discussed in the quoted section?
According to the documentation, the difference is:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
So what it does:
Try to match the row using one of the available indexes;
If the row doesn't exist already: add a new one;
If the row exists already: delete the existing row and add a new one afterwards.
When might using this become useful over separate insert and update statements?
You can safely call this, and you don't have to worry about existing rows (one statement vs. two);
If you want related data to be removed when inserting / updating, you can use replace: it deletes all related data too);
When triggers need to fire, and you expect an insert (bad reason, okay).
First Replace isn't widely understood in all database engines.
Second replace inserts/updates a record based on the primary key. While with update you can specify more elaborate conditions:
UPDATE person SET first_name = 'old ' + first_name WHERE age > 50
Also UPDATE won't create records.
UPDATE will have no effect if the row does not exist.
Where as the INSERT or REPLACE will insert if the row doesn't exists or replace the values if it does.
Update will change the existing records value in table based on particular condition. So you can change one or many records in single query.
Insert or Replace will insert a new record if records is not present in table else will replace. Replace will only work if and only if you provide the primary key value in the insert or replace query. If you forget to add primary key field value than a new record will created in table.
Case example:-
Update: You have a calculation of wages to be done based on a formula using the column values. In this case you will always use update query as using one single query you can update multiple records.
Insert or Replace: Already mentioned in the link you shared.
How the REPLACE INTO statement works:
AS INSERT:
REPLACE INTO table_name (column1name, column2name, ...)
VALUES (value1, value2, ...);
AS UPDATE:
REPLACE INTO table_name SET column1name = value, column2name = value, ... ;
The REPLACE statement checks whether the intended data record's unique key value already exists in the table before inserting it as a new record or updating it.
The REPLACE INTO statement attempts to insert a new record or modify an existing record. In both cases, it checks whether the unique key of the proposed record already exists in the table. Suppose a value of NO or FALSE is returne. In that case, the REPLACE statement inserts the record similar to the INSERT INTO statement.
Suppose the key value already exists in the table (in other words, a duplicate key). In that case, the REPLACE statement deletes the existing record of data and replaces it with a new record of data. This happens regardless of whether you use the first or the second REPLACE statement syntax.
Once the REPLACE INTO statement is used to insert or modify data, it determines first whether the new data record already exists in the table. It checks if the PRIMARY or the UNIQUE KEY matches one of the existing records.
If there is no matching key, the REPLACE works like a normal INSERT statement. Otherwise, it deletes the existing record and replaces it with the new one. This is considered a sort of modification or update of an existing record. However, it would be best if you were careful here. Suppose you do not specify a value for a column in the SET clause. In that case, the REPLACE statement uses the default value (if a default value has been set). Otherwise, it's set as NULL.
How can I update only the nth row from a table?
To update the second row for example, i tried using UPDATE and LIMIT, but it is giving me an error.
UPDATE database_table
SET field = 'new_value'
LIMIT 0, 1
Is there a way to do it?
If you have a primary key and a column you'd like to order by (to get the nth row), you could do something like:
UPDATE database_table
SET field = 'new_value'
WHERE primary_key IN (
SELECT primary_key
FROM database_table
ORDER BY some_date_column
LIMIT n - 1, 1
)
Edit: I should probably add a caveat. This answer might be technically correct, but you're likely wrong to use it. I can't imagine too many scenarios where you'd actually want to update the nth row of a table. You should generally only be updating tables based on primary keys. Updating the nth row will likely break your app if multiple users (or even multiple sessions with the same user) are using it at the same time.
The real answer is you should probably change your code to update based on primary key.
You would need some sort of id, and then do something like this:
UPDATE database_table SET field = 'new_value' WHERE id = 2
I'd like to know how to update several records at once where a certain column type is selected.
I have found how to select records. I have found how to update records. But i don't know how to do it both together for it to work.
Selecting:
SELECT * FROM users WHERE 'type'='new'
Updating:
update table
set column = 937
So basically i want to change the info in the 'column' to 937 in the 'table' if another column 'type' is 'new'.
Thanks,
You can do this by simply adding a WHERE clause to your UPDATE statement:
UPDATE `users`
SET `myColumn` = 937
WHERE `type` = 'new'
Of course, change myColumn to match your column name
You can do this with a subquery :
update users
set column = 937
where id in (select id from users where type='new')
Just change the columns name if I got them wrong.
After researching for a while I found another solution to this problem. When referencing the same table or field name in a query, the name space in MySQL ends up with duplicates and fails. To overcome this use the "AS" syntax to name the duplicate items. Also, update queries often require a key field to be used as the parameter for the where clause, this is often your auto-incremented ID field. This example provides a solution for both of these problems.
UPDATE tbl
SET field=newValue
WHERE tbl.key IN
(SELECT idNew FROM
(Select tbl.key AS idNew
FROM tbl
WHERE field=editValue) AS tblNew);
tbl - Table name being updated
field - Target field for update
newValue - Value to replace items in the target field
tbl.key - Field name for the key in your table
idNew - New name for key in your table, to replace the name and prevent failure from duplicating names in query. could be any alphanumeric string. 'id' or 'id_new' or 'id_n'
editValue - The value to change
tblNew - New name for query, to prevent duplicate table names in the query. Could be any alphanumeric string 'tbl_n' or 'tbl_new' or 'tbl_test'
This query gets the key values for all the records that match records that have values you want edited, then changes the names of the key and tbl so they can be processed by MySQL, lastly the update query runs and changes the values based on the keys provided in the sub-query.
Hopefully this saves someone else a few hours!