You are on page 1of 4

9/28/2016

DatabaseDesignUnion&minus

SQLtechnique:unionandminus
Setoperationsontables
Somestudentsinitiallythinkofthejoinasbeingasortofunionbetweentwotables.Itsnot
(exceptfortheschemes).Thejoinpairsupdatafromtwoverydifferenttables.InRAandSQL,
unioncanoperateonlyontwoidenticaltables.RemembertheVenn-diagramrepresentationof
theunionandminusoperationsonsets.Unionincludesmembersofeitherorbothsets(withno
duplicates).Minusincludesonlythosemembersofthesetontheleftsideoftheexpressionthat
arenotcontainedinthesetontherightsideoftheexpression.

Bothsets,RandS,havetocontainobjectsofthesametype.Youcantunionorminussetsof
integerswithsetsofcharacters,forexample.Allsets,bydefinition,areunorderedandcannot
containduplicateelements.
SQLandRAsetoperationstreattablesassetsofrows.Therefore,thetablesonbothsidesofthe
unionorminusoperatorhavetohaveatleastthesamenumberofattributes,withcorresponding
attributesbeingofthesamedatatype.Itsusuallycleanerandmorereadableifyoujustgoahead
andgivethemthesamenameusingtheASkeyword.

Union
Forthisexample,wewilladdaSupplierstabletooursalesdataentrymodel.Asupplierisa
companyfromwhichwepurchaseproductsthatwewillre-sell.Eachsuppliersupplierszeroto
manyproducts;eachproductissuppliedbyoneandonlyonesupplier.Thesupplierclass
attributesincludethecompanynameandaddress,plusthenameandphonenumberofthe
representativefromwhomwemakeourpurchases.
Wewouldliketoproducealistingthatshowsthenamesandphonenumbersofallpeoplewe
dealwith,whethertheyaresuppliersorcustomers.Weneedrowsfrombothtables,buttheyhave
tohavethesameattributelist.Lookingattherelationscheme,wefindcorrespondingfirstname,
lastname,andphonenumberattributes,butwestillneedtoshowwhatcompanyeachofthe
supplierrepresentativesworksfor.

http://www.tomjewett.com/dbdesign/dbdesign.php?page=setops.php

1/4

9/28/2016

DatabaseDesignUnion&minus

WecancreateanextracolumninthequeryoutputfortheCustomerstablebysimplygivingita
nameandfillingitwithaconstantvalue.Here,wellusethevalue'Customer'todistinguish
LastName FirstName Phone
Company
theserowsfromsupplierrepresentatives.SQLusesthecolumnnamesofthefirstpartofthe
unionqueryasthecolumnnamesfortheoutput,sowewillgiveeachofthemaliasesthatare
appropriatefortheentiresetofdata.
Buildandtesteachcomponentoftheunionqueryindividually,thenputthemtogether.The
ORDERBYclausehastocomeattheend.
SELECTcLastNameAS"LastName",cFirstNameAS"FirstName",
cPhoneas"Phone",'Customer'AS"Company"
FROMcustomers
UNION
SELECTrepLName,repFName,repPhone,sCompanyName
FROMsuppliers
ORDERBY"LastName";
Phonelist
LastName FirstName Phone

Company

Bradley

Jerry

888-736-8000 IndustrialToolSupply

Dick

Wayne

562-777-3030 Customer

Jewett

Tom

714-555-1212 Customer

Monge

Alvaro

562-333-4141 Customer

O'Brien

Tom

949-567-2312 BoschMachineTools

Minus
Sometimesyouhavetothinkaboutbothwhatyoudowantandwhatyoudontwantinthe
resultsofaquery.IfthereisaWHEREclausepredicatethatcompletelypartitionsallrowsof
interest(theresultset)intothoseyouwantandthoseyoudontwant,thenyouhaveasimple
querywithatestforinequality.
Themultiplicityofanassociationcanhelpyoudeterminehowtobuildthequery.Sinceeach
producthasoneandonlyonesupplier,wecanpartitiontheProductstableintothosethatare
suppliedbyagivencompanyandthosethatarenot.
SELECTprodName,sCompanyName
FROMProductsNATURALJOINSuppliers
WHEREsCompanyName<>'IndustrialToolSupply';
Contrastthistofindingcustomerswhodidnotmakepurchasesin2002.Becauseoftheoptional
one-to-manyassociationbetweenCustomersandOrders,thereareactuallyfourpossibilities:
1.Acustomermadepurchasesin2002(only).
2.Acustomermadepurchasesinotheryears,butnotin2002.
http://www.tomjewett.com/dbdesign/dbdesign.php?page=setops.php

2/4

9/28/2016

DatabaseDesignUnion&minus

3.Acustomermadepurchasesbothinotheryearsandin2002.
4.Acustomermadenopurchasesinanyyear.
Ifyoutrytowritethisasasimpletestforinequality,
SELECTDISTINCTcLastName,cFirstName,cStreet,cZipCode
FROMCustomersNATURALJOINOrders
WHERETO_CHAR(orderDate,'YYYY')<>'2002';
youwillcorrectlyexcludegroup1andincludegroup2,butfalselyincludegroup3and
falselyexcludegroup4.Pleasetaketimetore-readthisstatementandconvinceyourself
whyitistrue!
Wecanshowinsetnotationwhatweneedtodo:
{customerswhodidnotmakepurchasesin2002}=
{allcustomers}{thosewhodid}
TherearetwowaystowritethisinSQL.
TheeasiestsyntaxinthiscaseistocompareonlythecustomerIDs.WellusetheNOTINset
operatorintheWHEREclause,alongwithasubquerytofindthecustomerIDofthosewhodid
madepurchasesin2002.
SELECTcLastName,cFirstName,cStreet,cZipCode
FROMCustomers
WHEREcustIDNOTIN
(SELECTcustID
FROMOrders
WHERETO_CHAR(orderDate,'YYYY')='2002');
WecanalsousetheMINUSoperatortosubtractrowswedontwantfromallrowsin
Customers.(SomeversionsofSQLusethekeywordEXCEPTinsteadofMINUS.)LiketheUNION,
thisrequirestheschemesofthetwotablestomatchexactlyinnumberandtypeofattributes.
SELECTcLastName,cFirstName,cStreet,cZipCode
FROMCustomers
MINUS
SELECTcLastName,cFirstName,cStreet,cZipCode
FROMCustomersNATURALJOINOrders
WHERETO_CHAR(orderDate,'YYYY')='2002';

Othersetoperations
SQLhastwoadditionalsetoperators.UNIONALLworkslikeUNION,exceptitkeepsduplicate
rowsintheresult.INTERSECToperatesjustlikeyouwouldexpectfromsettheory;again,the
schemesofthetwotablesmustmatchexactly.

http://www.tomjewett.com/dbdesign/dbdesign.php?page=setops.php

3/4

9/28/2016

DatabaseDesignUnion&minus

Copyright20022006,byTomJewett.Linkstothissitearewelcomeandencouraged.Individual
copiesmaybeprintedfornon-commercialclassroomorpersonaluse;however,thismaterialmaynot
berepostedtootherwebsitesornewsgroups,orincludedinanyprintedorelectronicpublication,
whethermodifiedornot,withoutspecificpermissionfromtheauthor.

http://www.tomjewett.com/dbdesign/dbdesign.php?page=setops.php

4/4

You might also like