SqlShare.com Logo
 
Skip Navigation Links
Home
Video List
Events
Classes
About Us
Login / Register
Subscribe RSS Feed 

Confio Ignite

Performing Updates with Common Table Expressions (CTE)

Common table expressions are a more readable version of a derived table. This videos shows you how to utilize a common table expression to update data.

Duration:
2 mins 49 secs
Skill Level:
100
Rating:
4.13 out of 5
Publish Date:
November 06, 2008
Performing Updates with Common Table Expressions (CTE) You must be logged in to view this video.  
Bookmark and Share
 
1=Poor, 3=Good, 5=Excellent

About the Author

Image of Plamen Ratchev
Plamen Ratchev has over two decades experience in the software architecture and development field. He has enjoyed building solutions for UNIX, DOS and Windows platforms, with main focus on SQL Server since version 4.21. Plamen is founder of Tangra, specializing in relational database applications analysis, implementation, and tuning. His particular interest is in design patterns, performance a...

References



Comments
Johnny on 11/11/2008
It looks good, but I think the UPDATE .. FROM .. WHERE is simpler and more logical than CTE.

Plamen Ratchev on 11/12/2008
In my opinion the use of the CTE makes the code more readable and more convenient to troubleshoot and maintain. It is very easy to test the CTE with a SELECT statement to check what values will get updated. Plus you get the same efficient plan as you would get with the UPDATE with JOIN syntax. Also, there are some cases where incorrectly written UPDATE with FROM clause that does not reference the target table for the update may produce very unpleasant results (see more details in the following article by Jeff Moden: http://www.sqlservercentral.com/articles/Performance+Tuning/62278/).

Blake on 1/7/2009
talks too fast and does't explain what he is doing

Bill Nicolich on 1/7/2009
Good example.

Adam Gojdas on 1/7/2009
I would have to slightly disagree with your statement: "created once then used multiple times in a query or script". I would only say that it can be used multiple times in a query. It would not qualify for multiple times in a script because it would need to be redefined within the execution scope of each SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement that utilizes it. You cannot just define it once in a script and use it throughout multiple/separate queries within the script. I do find it an interesting alternative to the "UPDATE .. FROM .. WHERE" syntax though.

Plamen Ratchev on 1/7/2009
Adam, you are correct. I am not sure why that description was added to the video, I do not discuss the nature of CTEs in the video at all. The CTE is valid only in the scope of the consuming statements as you pointed out (including the MERGE statement in SQL Server 2008).

Harvey Schwartz on 1/7/2009
Is it possible to get a version of the t-sql that I can cut and paste and then execute? It would be useful for this and most other demos.

544525734F on 1/7/2009
Very good. Simple and Precise.

Andy Warren on 1/8/2009
Plamen, Adam, I updated the description to simplify!

Chris Kasten on 1/8/2009
make it twice as long with another example. I *think* I get it... but would love a bit more reinforcement

Mike Mastro on 1/8/2009
Very Good. Simple & solid example.

Jon on 1/10/2009
Good job, but I had a little trouble with accent. Lack of exposure on my part, I suppose.

Plamen Ratchev on 1/14/2009
Harvey, the sample scripts used in the video are attached now under References.

Narasmha Rao on 1/28/2009
good

Chris Helm on 2/13/2009
another example may have helped but I think I get the idea.

Tom Grumbling on 2/28/2009
It would have been helpful to have an example of what the update statement would be if you hadn't used the CTE

Plamen Ratchev on 3/1/2009
Tom, using the T-SQL specific UPDATE with JOIN (without CTE), the query will look like this: UPDATE Products SET product_desc = U.product_desc, price = U.price FROM products AS P JOIN ProductUpdates AS U ON P.sku = U.sku WHERE U.effective_date < CURRENT_TIMESTAMP;

suresh.kala on 12/1/2009
its good

Feodor Georgiev on 12/2/2009
Great video!

seth buxton on 2/8/2010
UPDATE a SET some_value = 200 --select * FROM TableA a JOIN TableB b on b.some_value = a.some_value WHERE a.some_other_value = 400 Highlight from SELECT down to view the affected rows, highlight the entire UPDATE statement to affect the UPDATE. You don't have to use a CTE to preview the affected rows.

seth buxton on 2/8/2010
The formatting got mangled.

Tatyana on 9/21/2010
Hm... tried to extend this technique to INSERT (by UNION of new records to that Update table), kind of tried to mimic a MERGE statement... and got an error message "Update or insert of view or function [CTE table name] failed because it contains a derived or constant field. Why so? Can it be done (UPDATE + INSERT using CTE)?

Plamen Ratchev on 9/22/2010
Tatyana, not sure what you are trying to do. A CTE can be consumed by only one query, so you cannot use both UPDATE and INSERT in the same query, it has to be one or the other. Please post you query to clarify the intent. The error that you posted indicates something else, that you have a derived column on which you cannot perform update/insert. If you use UNION inside the CTE to add rows then this really does not act like insert, it just adds rows to the CTE but not to the permanent table/view.

Tatyana on 9/22/2010
Hi Plamen, thanks for answering! Here is my query, below. It works the way you introduced in your sample, but if to lift a comment from a commented part it generates the error I mentioned. DECLARE @TableMain table (item_ID int NOT NULL, item_name varchar(100)) DECLARE @TableUp table (item_ID int NOT NULL, item_name varchar(100)) INSERT INTO @TableMain VALUES(1, 'aaa'), (2, 'bbb'), (3, 'ccc') INSERT INTO @TableUp VALUES(1, 'aaa'), (2, 'xxx'), (3, 'cccX'), (4, 'ddd') ;WITH Update_CTE AS (SELECT TM.item_name AS item_name, TU.item_name AS new_item_name FROM @TableUp TU JOIN @TableMain TM ON TU.item_ID = TM.item_ID ----------------- --UNION --SELECT TM.item_name AS item_name, TU.item_name AS new_item_name --FROM @TableUp TU LEFT OUTER JOIN @TableMain TM --ON TU.item_ID = TM.item_ID WHERE TM.item_ID IS NULL ------------------ ) UPDATE Update_CTE SET item_name = new_item_name SELECT * FROM @TableMain

Tatyana on 9/22/2010
...and I see that there is an objection to a UNION; however, with a FULL JOIN (see below) it updates only the first set of records... I wonder if INCERT viw CTE is possible at all. DECLARE @TableMain table (item_ID int NOT NULL, item_name varchar(100)) DECLARE @TableUp table (item_ID int NOT NULL, item_name varchar(100)) INSERT INTO @TableMain VALUES(1, 'aaa'), (2, 'bbb'), (3, 'ccc') INSERT INTO @TableUp VALUES(1, 'aaa'), (2, 'xxx'), (3, 'cccX'), (4, 'ddd') ;WITH Update_CTE AS (SELECT ISNULL(TM.item_ID, TU.item_ID) AS item_ID, TM.item_name AS item_name, TU.item_name AS new_item_name FROM @TableUp TU FULL JOIN @TableMain TM ON TU.item_ID = TM.item_ID ) UPDATE Update_CTE SET item_name = new_item_name SELECT * FROM @TableMain

Tatyana on 9/22/2010
...Hey, but it updates AND inserts records in the second set (@TableUP in my sample)! Very interesting! I'm apologizing for turning this comments section into a discussion, but your sample is just too inspiring! :) Thank you!

Plamen Ratchev on 9/23/2010
Tatyana, in your first query you cannot use union, because then the data set defined by the CTE is not updatable. In your second query the FULL OUTER JOIN works. But I am not sure what you mean that it inserts and updates at the same time. Both of your source tables have the same rows after the UPDATE, only some values are updated. What is the final result that you are trying to accomplish?

vin lawrence on 11/9/2010
Difficult to understand his accent should talk slower

vijay on 11/9/2010
Good demo

suman on 11/9/2010
Very good video

neeta on 11/9/2010
Would it be possible to have written transcripts of these videos?

Kasey Wheeler on 11/9/2010
Good video.

robert on 11/9/2010
slow down a bit...a lot of code here. Good stuff though.

MorpheusXP on 11/9/2010
It would be great if it would be explained a little bit more in detail.

Steve Harris on 11/9/2010
Very good and simeple example. One additional step that could be shown is how to clean up the product updates table to remove the records that had been processed.

Tom Hamilton on 11/9/2010
Good clear example - thanks

17EB042629 on 11/9/2010
try doing a demo of how to update or insert new rows into destination table from a source table but only if the row is new or if only certain of the values in the matching rows have changed, regardless whether other values in the matching rows have changed or not. HINT: use the EXCEPT predicate with a CTE.

santhosh on 11/9/2010
Simply superb....

Don Nesbitt on 11/9/2010
I need more experience to understand, but presentation was still simple and eaasy to get.

Ann on 11/9/2010
Great video!

Daniel on 11/9/2010
I have never seen CTE before. It does make things much more clear than using the where clause in the update statement. Plus you can verify how it will work by running only the select statement before committing any changes to the database.

Richard Ray on 11/9/2010
Good content, well presented. I can't think of anything to complain about. A+

Rick Beley on 11/9/2010
Was a little confusing at first, but I got it and am eager to use it!

A2D6709F0F on 11/9/2010
Would've appreciated a little more detail regarding why the UPDATE query was applied to the Product table...

John on 11/9/2010
Like the thinking

Brian Savoie on 11/9/2010
Very useful in everyday life!

manjeet on 11/9/2010
Learned new update type

Carlos on 11/14/2010
Very helpful, thanks!

Stevan Cohen on 11/15/2010
Too fast, hard to follow. Would help to have text version of this code.

Plamen Ratchev on 11/16/2010
Stevan, in the References section you can press the Example Script link and download the text for all code used in this video.

Michael on 11/16/2010
Thanks

Max Turavani on 6/16/2011
very good !

rupesh sharma on 6/16/2011
Really useful, thanks

Terry Phelps on 6/16/2011
Obviously this video was created a few years ago considering the dates used for the update statements.

kana alexander on 6/16/2011
Thanks useful tidbit on CTE's for updates

Caleb Bell on 6/16/2011
Good way to show how to use the CTE syntax with updates. It would have been helpful to show the query without using the CTE to illustrate why/when you'd want to use a CTE vs. the typical syntax.

Samson J. Loo on 6/16/2011
Perfect. Exactly what I was looking for.

Vijay on 6/16/2011
what about performance? Can you give example which shows about performance.

Michael Neymit on 6/16/2011
Great tip!

Dennis Allen on 6/16/2011
-- this seems just as clear to me... UPDATE U SET U.product_desc = N.product_description, U.price = N.price FROM Products U JOIN ProductUpdates N ON U.sku = N.sku AND N.effective_date < CURRENT_TIMESTAMP;

Shadab on 6/16/2011
gud 1

Anil Babu on 6/16/2011
good & informative - thanks

DavidB on 6/16/2011
Great basic overview of a neat way to use a CTE. Nice job.

Mick on 6/16/2011
Creative idea

ramesh on 6/16/2011
Nice one to kick up using CTE.

Daniel Frankel on 6/16/2011
This is great, I never knew you could do something like that.

Shashank Banerjea on 6/16/2011
Additional Examples for more complicated operation would have been appreciated. Little more time should be spent on the Syntax of the CTE.

León Carpay on 6/16/2011
short knowledge piece. very nice

Eric on 6/17/2011
Extremely relevent and very helpful. Thanks a ton.

A43036427E on 6/17/2011
As someone who has never seen CTEs before, this was much too fast to absorb.

Carlos B. Vasquez on 6/19/2011
Excellent!!!

Current on 6/19/2011
The information seems to be trivial..we expect more advanced things to spare our time for watching

Plamen Ratchev on 6/21/2011
Vijay, performance would be the same as using UPDATE with FROM clause. Best in each case is to look at the execution plan.

Brad on 6/24/2011
Had difficulty understanding the presenter's English.

ash on 7/15/2011
Have a good one

katharine mahon on 8/18/2011
good demo. also leant from the replies....

Maurice Ivory on 11/10/2011
This was good

Les Weaving on 5/3/2012
Find it really hard to understand what Plamen is saying



Must Be Logged In
 

How Do I Become a Video Author? |  Newsletter History

Copyright © Fourdeuce, Inc., 2005-2009. All Rights Reserved | Privacy Policy | Terms & Conditions