I'm trying to run a report from the database on a list of contacts. The problem is that about 50 names are duplicate records because the contact has a primary address and a null address. However, some names (that are not duplicates) have a null address and must be displayed in the report. How can I pull in all contacts with a primary address, and the contacts with a null address, and not have duplicate contacts in my report? Thanks.
If you only wanted distinct names, it would be easy --
select distinct contactname from contacts
But it's trickier than that, because presumably you want addresses on your report as well.
Break it down into two sets. Select all the contacts with non-null addresses. Then select all the contacts with null addresses that don't also have a non-null address --
select contactname, contactaddress from contacts where contactaddress is not null union all select contactname, contactaddress from contacts XX where contactaddress is null and not exists ( select * from contacts where contactname = XX.contactname and contractaddress is not null )
Use UNION ALL instead of UNION, to avoid the sort to detect duplicate rows. There cannot be any duplicate rows in the combined result set from the two subqueries in the union, because the partial result set from the first subquery has all non-null addresses, whereas the partial result set from the second subquery has all null addresses. The detection of duplicates in a UNION compares all columns of pairs of rows.
For More Information
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have a SQL tip to offer your fellow DBA's 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, and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.