LogoASPAlliance: Articles, reviews, and samples for .NET Developers
CodeSnip: How to Update Records of a Table in Oracle Using Where Exists Clause
by Deepankar Sarangi
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 18885/ 21


Usually there are situations where we may be required to update those records of a table, which are found equal in some other table. But simply doing an update on the target table will cause the non-matching records updated to null. Here the use of "where exists" clause can avoid ambiguity by letting the non-matching records remain as before.


Oracle database 9i

Problem Description

The above stated problem can be represented as below. Let us say we have a source table and a target table which will get updated consisting of two fields each as NAME and ID.

Source Table:


Figure 1

Picture 3

Destination Table:


Figure 2

Picture 1

Let us say we are required to update the NAME field EMP table for those ID's found common to ID's of DEPT table. This simply means we want the EMP table to get updated as given below.



1        E

2        F

3        G

5        X

The solution seems quite straightforward from the surface. As a result, the most obvious looking solution creates the problem explained below.

Listing 1

update EMP a set =(select name from DEPT b where );

Figure 3

Picture 2

But we never wanted to get a null for the ID= 5. The query in Listing1 not only updates the NAME for common ID's, but it also updates the NAME for non-matching ID as NULL, which is undesirable.

Solution Code

Listing 2

update EMP a set =(select from DEPT b where = ) 
where exists(select 1 from DEPT b where =;

Figure 4

Picture 3


The query in listing 2 solves our problem by updating the NAME for matching ID, but leaving non-matching ID as compared to the query in listing 1.

The reason behind this is simple. The query in listing1 tries to update the NAME field for all the records present in the table, which forces it to update even those NAME the non-matching ID's to NULL.

Whereas the query in listing 2 tries to update the NAME field for only those records whose ID's are found common and avoids updating the NAME for non-matching ID's.


By following this approach the user can use update more effectively and efficiently for similar situations.

Product Spotlight
Product Spotlight 

©Copyright 1998-2021  |  Page Processed at 2021-04-13 6:18:42 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search