Problem solve Get help with specific problems with your technologies, process and projects.

Comparing values in different rows

I need some advice regarding comparing values in different rows in the same table. For example:

Table X has columns A, B and C:
1 2 3
1 4 5
What I mean by comparison is that the values of B and C need to be reported (their values being non-equal).

As with most SQL questions, there are multiple ways to solve the problem. This one is no different. One way to do it would be to use an EXISTS predicate. First let's create and populate your table.

create table X
( A number,
  B number,
  C number

insert into X values (1, 2, 3);
insert into X values (1, 4, 5);
insert into X values (2, 6, 6);
insert into X values (2, 6, 6);
insert into X values (3, 1, 7);
insert into X values (3, 1, 9);
insert into X values (4, 8, 0);
If I understand your scenario correctly, you wish to only show those rows where the values in columns B and C don't match the values in columns B and C for other rows having the same value for column A. Here's a solution using EXISTS:
select * from X t
  where exists ( select * from X 
                   where A = t.A 
                     and ( B != t.B or C != t.C ) );

For More Information

  • What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
  • The Best SQL Web Links: tips, tutorials, scripts, and more.
  • Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
  • Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
  • Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.

This was last published in March 2002

Dig Deeper on Oracle and SQL



Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Join the conversation

1 comment

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

Have you tried this solution yourself. before posting you should