what if I wanted to update the records in the table by altering values in one of the columns?
I have records in the table that have one column empty(null values). I want to change these values and insert values from another table into those records.
Basically I have a table with one column empty. I do not want to append to the end of the table but start inserting from record 1.
For the existing records, you would have to use UPDATE to update that one column, WHERE thatColumn IS NULL.
Shouldn't the values in that column have some relation to the rest of the record? I could understand initializing the existing records to a non-null value, or using an UPDATE query to populate data from another table in that column, but all related to the original row...
UPDATE old SET old.badColumn = new.newData
FROM oldTable old
JOIN newTable new on old.someID = new.someID
This would find the related data in newTable matching oldTable, and update the badColumn to some data from newTable... let me know if you need more help.
See the "Using the UPDATE statement with information from another table" section from this page of SQL Server Books Online.
Related
I'm trying to insert rows into a table while ignoring duplicate entries. At the same time, I want to assign a value to a certain column in the newly inserted rows.
Here's what I have so far (without assigning the value)
INSERT INTO stats (unique_key,clicks)
SELECT unique_key,clickss FROM temp_stats
ON DUPLICATE KEY UPDATE stats.unique_key=temp_stats.unique_key;
I would like to throw in clicks = 20 for the newly inserted rows.
How would I achieve this?
Just select the literal value, instead of the field from the table.
INSERT INTO stats (unique_key,clicks)
SELECT unique_key,20 FROM temp_stats
ON DUPLICATE KEY UPDATE stats.unique_key=temp_stats.unique_key;
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.
I have created a lookup transformation to search 2 table col for matching data and then insert another column data from matching data into the other table. My problem is how can i insert the matching data into that table i have shown in the shot.
I managed to insert the lookup matched cols by inserting OLEDB Command and Writing update query
Update dbo.city set fdocode = ? where id = ?
and then Map the col i want to insert to first parameter and id to second parameter.see shot for more clarity.
I have a table that has a number of columns. For each row, I'd like to select three columns (PAR_BOOK, PAR_PAGE, PAR_LINE) and concatenate the contents of those three columns into a new fourth column (APN).
So, if PAR_BOOK=0108, PAR_PAGE=291 and PAR_LINE=07, APN should be 010829107
Make sense?
But, I'm unsure of what query I should use to do this. I need the results stored back in the same table as it needs to be ultimately exported out as a csv to work with the program that's going to map the data.
Assuming your fourth column is already in the table, you would use the following update query:
UPDATE YourTable
SET APN = CONCAT(PAR_BOOK, PAR_PAGE, PAR_LINE)
If your fourth column is not present in the table yet, you should use the ALTER TABLE statement to add it first before running the UPDATE statement:
ALTER TABLE YourTable
ADD APN VARCHAR(256) NULL
Inserting into the same table with INSERT INTO ... SELECT ... is no problem at all. MySQL holds the selected rows in a temporary table.
I don't think this is possible as I couldn't find anything but I thought I would check on here in case I am not searching for the correct thing.
I have a settings table in my database which has two columns. The first column is the setting name and the second column is the value.
I need to update all of these at the same time. I wanted to see if there was a way to update these values at the same time one query like the following
UPDATE table SET col1='setting name' WHERE col2='1 value' AND SET col1='another name' WHERE col2='another value';
I know the above isn't a correct SQL format but this is the sort of thing that I would like to do so was wondering if there was another way that this can be done instead of having to perform separate SQL queries for each setting I want to update.
Thanks for your help.
You can use INSERT INTO .. ON DUPLICATE KEY UPDATE to update multiple rows with different values.
You do need a unique index (like a primary key) to make the "duplicate key"-part work
Example:
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE b = VALUES(b), c = VALUES(c);
-- VALUES(x) points back to the value you gave for field x
-- so for b it is 2 and 5, for c it is 3 and 6 for rows 1 and 4 respectively (if you assume that a is your unique key field)
If you have a specific case I can give you the exact query.
UPDATE table
SET col2 =
CASE col1
WHEN 'setting1'
THEN 'value'
ELSE col2
END
, SET col1 = ...
...
I decided to use multiple queries all in one go. so the code would go like
UPDATE table SET col2='value1' WHERE col1='setting1';
UPDATE table SET col2='value2' WHERE col1='setting1';
etc
etc
I've just done a test where I insert 1500 records into the database. Do it without starting a DB transaction and it took 35 seconds, blanked the database and did it again but starting a transaction first, then once the 1500th record inserted finish the transaction and the time it took was 1 second, so definetely seems like doing it in a db transaction is the way to go.
You need to run separate SQL queries and make use of Transactions if you want to run as atomic.
UPDATE table SET col1=if(col2='1 value','setting name','another name') WHERE col2='1 value' OR col2='another value'
#Frits Van Campen,
The insert into .. on duplicate works for me.
I am doing this for years when I want to update more than thousand records from an excel import.
Only problem with this trick is, when there is no record to update, instead of ignoring, this method inserts a record and on some instances it is a problem. Then I need to insert another field, then after import I have to delete all the records that has been inserted instead of update.