Professional Documents
Culture Documents
The following are two common circumstances in which you may want to compare two tables and find unmatched records. Depending on your circumstance, finding unmatched records may be the first of several steps that you want to take. This article only covers finding unmatched records. You use one table to store data about a thing (such as a product), and another table to store data about actions (such as orders) that involve that thing. For example, in the Northwind 2 ! database template, data about products is stored in the "roducts table, and data about which products are included in each order is stored in the #rder Details table. $ecause %by design& there is no data about orders in the "roducts table, it is not possible, by looking at the "roducts table alone, to determine which products have never been sold. This information is also not possible to determine by looking at the #rder Details table alone, because the #rder Details table includes data only about products that have been sold. 'ou must compare the two tables to determine which products have never sold. (f you want to review a list of things from the first table for which there are no corresponding actions in the second table, you can use a Find )nmatched *uery.
You have two tables that have overlapping, redundant, or conflicting information, and you want to consolidate them into one table. For example, suppose that you have one table named +ustomers and another table named +lients. The tables are nearly identical, but one table or both tables contain some records that the other is missing. To consolidate the tables, you must first determine which records are uni,ue to one table or to the other table. (f this is your circumstance, the methods described in this article can help, but you will probably have further steps to take. 'ou can run the Find )nmatched *uery -i.ard to identify unmatched records, but if you want to retrieve the combined set of records, you use the results to create a union ,uery. (f you are comfortable writing /tructured *uery 0anguage %/*0& statements, you might even prefer to forgo the Find )nmatched *uery -i.ard, and write the union ,uery by hand. 'ou can often approach the problem of overlapping, redundant, or conflicting information by looking for duplicate data in two or more tables. For more information about union ,ueries, or about finding, hiding, or eliminating duplicate data, click the links in the See lso section.
N#T1 1xamples in this article use a database that was created by using the Northwind 2
! database template.
8& !&
%reate and modify a "ind !nmatched #uery to compare by more than one field
2. 2. 4. 5. #n the %reate tab, in the &ther group, click #uery Wi$ard. (n the 'ew #uery dialog box, double3click "ind !nmatched #uery Wi$ard. #n the first page of the wi.ard, select the table that has unmatched records, and then click 'e(t. For example, if you want to see a list of Northwind 2 ! products that have never been sold, select the "roducts table. #n the second page, select the table that is related, and then click 'e(t. To follow the example, select the #rder Details table.
6.
#n the third page, select the fields that relate the tables, click ) * +, and then click 'e(t. 'ou can choose only one field from each table. To follow the example, select (D from the "roducts table and "roduct (D from the #rder Details table. 7erify that the correct fields are matched by reviewing the text in the ,atching fields box. 'ou can <oin the remaining fields after you have completed the wi.ard. Note that the (D and the "roduct (D fields may already be selected because of existing relationships built in to the template. #n the fourth page, double3click the fields that you want to see from the first table, and then click 'e(t. To follow the example, select the (D and "roduct Name fields. #n the fifth page, click ,odify the design, and then click "inish. The ,uery opens in Design view. (n the ,uery design grid, note that the two tables are <oined on the fields %in this example, (D and "roduct (D& that you specified on the third page of the wi.ard. +reate a <oin for each remaining pair of related fields by dragging them from the first table %the table that has unmatched records& to the second table. For this example, drag the 0ist "rice field from the "roducts table to the )nit "rice field from the #rder Details table. Double3click a <oin %the line connecting the fields& to display the .oin /roperties dialog box. For each <oin, choose the option that includes all the records from the "roducts table, and then click &0. (n the ,uery design grid, note that each <oin now has an arrow at one end.
8. !. =. >. 2 .
22.
-hen you create the <oin between the 0ist "rice and )nit "rice fields, it restricts output from both tables. #nly those records with matching data in the fields in both tables are included in the ,uery results. 9fter you edit the <oin properties, the <oin only restricts the table that the arrow points to. 9ll records in the table that the arrow points from are included in the ,uery results.
N#T1 ?ake sure that all of the arrows on the <oins are pointing in the same direction.
For the table that has related records %in this example, the #rder Details table&, double3click each field that is <oined to the first table, except for the field that you chose on the third page of the wi.ard %in this case, the "roduct (D field&. For each of these fields, clear the check box in the Show row, and type Is 'ull in the %riteria row. #ptionally, add criteria to the other ,uery fields, or create calculated fields that are based on values from the first table. #n the 1esign tab, in the 2esults group, click 2un. The ,uery returns the names of products that are not part of any existing orders.
ii&
N#T1 ?ake sure that all of the <oins are pointing in the same direction. The ,uery will not run if the <oins point in different directions, and
may not run if any <oin is not an arrow. The <oins should point away from the table that has unmtached records.
8&
(n the table that has unmatched records, double3click the fields that you want the ,uery to return. i& #ptionally, enter criteria for any of these fields, or create calculated fields. For the table that has related records, double3click each field that is <oined to the first table. For each of these fields, clear the box in the Show row, and type Is 'ull in the %riteria row. #n the 1esign tab, in the 2esults group, click 2un.
!& =&
4wo or more records can contain duplicate fields. Two records might be considered duplicates, even though not all fields of the records contain matching values. For example, in this figure, you see two records for 9ntonio ?oreno Ta,uerDa.
1ven though each record has a uni,ue customer (D %the value in the left3most column&, the values in the Name, 9ddress, and +ity fields match. (n such situations, even a partial match can be a good reason to use your knowledge of your business and review the records to see if they are duplicates. 4wo or more tables can contain similar data. For example, you might find that a +ustomers table and a +lients table both contain records for the same customers.
1ven though the tables might have different structures, both tables contain the same kind of information E customer data E so you should consider merging any uni,ue %non3duplicate& values into a single table and eliminating the extra table. 4wo or more databases can contain similar data. (f you find that two or more databases contain similar data, or you inherit a database that overlaps with your current database, you must compare the data and structure of the databases and then take necessary steps to consolidate them. ?anually comparing databases, even small ones, is not an easy task. (f you need help with a comparison, several third3party vendors sell tools for comparing the contents and structure of 9ccess databases. 7isit the Database management section of the ?icrosoft #ffice ?arket"lace to check out the currently featured database management tools.
N#T1 (f you take steps to eliminate duplicate data from your tables and you still see duplicate data in a form or report, it might be due to incorrect design of a form or report. ?ake sure that the underlying tables and ,ueries are <oined properly, and that the form or report sections do not include more than one control that is bound to the same control source. For more information about report design, see the article ?odify, edit, or change a report.
(n this view, several records appear to be duplicates. (f you add one or more additional fields to the ,uery, such as the names of the customers or the primary key fields for each order %#rder (D&, you will see that each record is actually uni,ue, like soB
9s a rule, when you create a ,uery, you should include the field or fields that identify each record uni,uely. Typically, a primary key field serves that function, but you can use combinations of other fields instead. For example, you have many instances of a common contact name and many instances of a city name, but if you include a phone number and an address, that combination of data should make each record uni,ue.
$efore you start deleting redundant data, consider one or more of these ways to prepare your databaseB
?ake sure that the database is not read3only. ?ake sure that you have the necessary permissions to edit or delete records in the database. 9sk all other users of the database to close the ob<ects that you want to work with. This helps avoid lock violations.
T(" (f a large number of users connect to the database, you might need to close the database and reopen it in exclusive mode. To do so, click the
in 9ccess, and then click &pen. $rowse to and select the database, click the arrow next to the &pen button, and then click
$ack up your database before you delete records. 'ou cannot reverse or undo a delete operation. The only way to recover deleted records is to restore them from a backup. 9 delete operation might also delete records in related tables, so it is best to back up the entire database before starting the operation.
6ac8 up a database
2& 2& +lick the ,icrosoft &ffice 6utton , click the arrow next to ,anage, and then click 6ac8 !p 1atabase. The Save s dialog box appears, and 9ccess appends the current date to the file name. For example, if you have a database named 9ssets, 9ccess creates the following type of file nameB ssets9:;;<=>;=:?. 9ccept the default name and location, or select another name or location, and then click Save. i& ii& 9ccess closes the original file, creates a backup, and then reopens the original file. To revert to a backup, close and rename the original file so that the backup copy can use the name of the original version. 9ssign the name of the original version to the backup copy, and open it in 9ccess.
4&
COMPANY NAME
Baldwin Museum of Science Blue Yonder #irlines
CONTACT NAME
Josh Barnhill
ADDRESS
1 Main St.
CITY
POSTAL CODE
PHONE
(5 5! 555" 2122 (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
$aleed %eloo
52 1st St.
Boston
2345&
'oho $iner(
)ica *uido
Seattle
345&+
'ontoso )harmaceuticals
/ondon
NS1 0$2
1ourth 'offee
Julian )rice
'alle Smith 2
Me2ico
5&+34
'it( 'oho $iner( 'hristine %u.hes 3122 +5th St. S. Seattle 345&+ (2 &! 555" 2125 (41&! 555" 2123 (5 3! 555" 2124 (+! 555"2233
%umon.ous 5nsurance
Ste,e 6ile(
7am-a
1234
7re( 6esearch
8ana Birk9(
2 Nose( )kw(
)ortland
4321
1ourth 'offee
6eshma )atel
'alle Smith 2
Me2ico 'it(
5&+34
LAST NAME
Barnhill %eloo *uido
FIRST NAME
Josh $aleed )ica
ADDRESS
1 Main St. 52 1st St. 3122 +5th #,e. S.$. 1 'ontoso Bl,d. 'alle Smith 2
CITY
New York Boston Seattle
BIRTH DATE
5"1e9"14&3 22"Ma("145+ 11"No,"14&
HIRE DATE
1 "Jun"1444 22"No,"144& 11"Mar"2
Ba.el )rice
22"Mar"14&4 5"Jun"14+2
22"Jun"1443 5"Jan"2 2
3122 +5th St. S. &+ Bi. St. 2 Nose( )kw( 1 'ontoso Bl,d.
23"#-r"1444 14":ct"2 4
24"Mar"144+ 2 "Jun"1443
COMPANY NAME
Baldwin Museum of Science Blue Yonder #irlines
CONTACT NAME
Josh Barnhill
ADDRESS
1 Main St.
CITY
POSTAL CODE
PHONE
(5 5! 555" 2122 (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
AMOUNT DUE
;55&.+3
$aleed %eloo
52 1st St.
Boston
2345&
;1<343.24
'oho $iner(
)ica *uido
Seattle
345&+
;321.+4
'ontoso )harmaceuticals
/ondon
NS1 0$2
=45+.&3
1ourth 'offee
Julian )rice
'alle Smith 2
5&+34
;43.+5
'oho $iner(
'hristine %u.hes
345&+
;321.+4
%umon.ous 5nsurance
Ste,e 6ile(
7am-a
1234
;24+.45
7re( 6esearch
8ana Birk9(
2 Nose( )kw(
)ortland
4321
;5 4. 4
2124 1ourth 'offee 6eshma )atel 2 'alle Smith Me2ico 'it( 5&+34 (+! 555"2233 ;43.+5
NAME
Baldwin Museum of Science Blue Yonder #irlines
ADDRESS
1 Main St.
CITY
PHONE
FAX
(5 5! 555" 2122 (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
New York (5 5! 555" 2122 Boston (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
52 1st St.
'oho $iner(
Seattle
'ontoso )harmaceuticals
/ondon
1ourth 'offee
'alle Smith 2
'onsolidated Messen.er
(2 &! 555" 2125 (41&! 555" 2123 (5 3! 555" 2124 (5 3! 555" 2233
(2 &! 555" 2124 (41&! 555" 2123 (5 3! 555" 211 (5 3! 555" 2234
7am-a
/itware< 5nc.
3 Microsoft $a(
)ortland
7ails-in 7o(s
4 Microsoft $a(
)ortland
i&
ii&
2&
table to the database. Double3click the first cell in the header row and type the name of the field in the sample table. i& $y default, 9ccess denotes blank fields in the header row with the text dd 'ew "ield, like soB
ii& 4& 5& )se the arrow keys to move to the next blank header cell, and then type the second field name %you can also press T9$ or double3click the new cell&. Aepeat this step until you enter all field names. 1nter the data in the sample table. i& 9s you enter the data, 9ccess infers a data type for each field. (f you are new to relational databases, you should set a specific data type, such as Number, Text, or DateHTime, for each of the fields in your tables. /etting data types help ensure accurate data entry and also helps prevent mistakes, such as using a telephone number in a calculation. For these sample tables, you should let 9ccess infer the data type.
6&
-hen you finish entering the data, click Save. i& 0eyboard shortcut "ress +TA0I/. ii& The Save s dialog box appears.
8&
(n the 4able 'ame box, type the name of the sample table, and then click &0. i& 'ou use the name of each sample table because the ,ueries in the how3to sections use those names.
i&
6&
N#T1 'ou might need to add worksheets to your spreadsheet file. For information on doing that task, see the help for your spreadsheet
program. /ave the workbook to a convenient location on your computer or your network, and go to the next set of steps.
3or3 +lick ,ore, and then select a spreadsheet program from the list. The 5et 7(ternal 1ata = Spreadsheet dialog box appears. +lick 6rowse, open the spreadsheet file that you created in the previous steps, and then click &0. i& The (mport /preadsheet -i.ard starts. $y default, the wi.ard selects the first worksheet in the workbook %+ustomers, if you followed the steps in the previous section&, and data from the worksheet appears in the lower section of the wi.ard page. +lick 'e(t. #n the next page of the wi.ard, click "irst row contains column headings, and then click 'e(t. #ptionally, on the next page, use the text boxes and lists under "ield &ptions to change field names and data types, or to omit fields from the import operation. #therwise, click 'e(t. 0eave the @et ccess add primary 8ey option selected, and then click 'e(t. $y default, 9ccess applies the name of the worksheet to your new table. 9ccept the name or enter another name, and then click "inish. Aepeats steps 2 through ! until you create a table from each worksheet in the 1xcel workbook.
2&
#ptionally, edit the field values or delete records when viewing the ,uery results in Datasheet view. #ptionally, alter the /tructured *uery 0anguage %/*0& code in the ,uery to look for values that partially match. (f you don:t alter the /*0 code, the ,uery returns only those records where the values in the specified fields match character for character. The steps in this section explain how to create a duplicates ,uery, and how to alter the ,uery to look for partial matches. The steps use the +ustomers table provided in the following table. To use the table in a database, see the section "repare some sample data, earlier in this document. 'ou can adapt the steps to fit your data.
COMPANY NAME
Baldwin Museum of Science Blue Yonder #irlines
CONTACT NAME
Josh Barnhill
ADDRESS
1 Main St.
CITY
POSTAL CODE
PHONE
(5 5! 555" 2122 (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
$aleed %eloo
52 1st St.
Boston
2345&
'oho $iner(
)ica *uido
Seattle
345&+
'ontoso )harmaceuticals
/ondon
NS1 0$2
1ourth 'offee
Julian )rice
'alle Smith 2
5&+34
'oho $iner(
'hristine %u.hes
345&+
(2 &! 555" 2125 (41&! 555" 2123 (5 3! 555" 2124 (+! 555"2233
%umon.ous 5nsurance
Ste,e 6ile(
7am-a
1234
7re( 6esearch
8ana Birk9(
2 Nose( )kw(
)ortland
4321
1ourth 'offee
6eshma )atel
'alle Smith 2
Me2ico 'it(
5&+34
i& 2& (n the 'ew #uery dialog box, click "ind 1uplicates #uery Wi$ard, and then click &0. i& (f an alert message appears and tells you that the feature is not installed, click Yes to install the wi.ard. (n the list of tables, select the table that contains your duplicate data, and then click 'e(t. (n the list of available fields, select only the field or fields that contain duplicate information. (f you use the +ustomers table, add only the +ompany Name, 9ddress, and +ity fields, because those are the only fields that contain character3for3character matching values. +lick 'e(t.
4& 5&
i&
6& 8&
N#T1 (f the fields that you add in this step do not contain character3for3character matches, the ,uery might not return any results.
(n the next list of available fields, select the field or fields that contain the data that you want to inspect or update, or those that contain data that can help you distinguish duplicate from non3duplicate records. (f you use the +ustomers table, you add the +ontact Name and "hone fields, because the data in those fields can help you find the duplicate values and possibly identify why the values were entered. +lick 'e(t. 9ccept the suggested name %"ind duplicates for %ustomers& or enter your own name, and then click "inish to run the ,uery. (f you used the +ustomers table, you see this resultB
COMPANY NAME
1ourth 'offee
ADDRESS
CITY
CONTACT NAME
Julian )rice
PHONE
(+! 555" 212& (+! 555" 2233
1ourth 'offee
6eshma )atel
2&
-hen you created the +ustomers table, you might have noticed more than two duplicate records %the table contains four&. 'ou don:t see the other duplicates because the values in the 9ddress field don:t match character3for3character. 'ou can modify the ,uery to return values that partially match E the next set of steps explains how.
SQL STATEMENT
DESCRIPTION
S0/0'7 'ustomers.>'om-an( Name?< 'ustomers. No chan.es. You want to see the same fields< includin. the entire #ddress field for each >#ddress?< 'ustomers.>'it(?< 'ustomers.>'ontact Name?< set of du-licate records. 'ustomers.>)hone? 16:M 'ustomers $%060 ((('ustomers.'om-an( Name! 5n (S0/0'7 >'om-an( Name? 16:M >'ustomers? #s 7m- *6:@) BY >'om-an( Name?<Left(>#ddress?,7) <>'it(? %#A5N* No chan.e. 6e-lace the field ([Addre !! with a function call that o-erates on the #ddress field (Left([Addre !,7)! to determine du-lication. 7his tests the first se,en characters in the #ddress field instead of the entire field ,alue. 7o match fewer characters< enter a smaller num9er. 7o match more characters< enter a lar.er num9er. 7o com-are the first se,en characters in the #ddress field of one record with that of another record< re-lace [Addre ! with the Left([Addre !,7) function call< and re-lace [C" t#$er !%[Addre ! with the Left([C" t#$er !%[Addre !,7) function call. No chan.e.
2&
The ,uery now returns all four duplicate records, because now it matches only the first ! characters %starting from the left& in the 9ddress fieldB
COMPANY NAME
'oho $iner(
ADDRESS
3122 +5th #,e. S.$. 3122 +5th St. S.$
CITY
Seattle
CONTACT NAME
)ica *uido
PHONE
(2 &! 555" 2124 (2 &! 555" 2125 (+! 555"212&
'oho $iner(
Seattle
'hristine %u.hes
1ourth 'offee
'alle Smith 2
Julian )rice
1ourth 'offee
'alle Smith 2
6eshma )atel
(+! 555"2233
N#T1 (f you find a large number of duplicate records %more than you care to delete by hand&, you can delete those records by creating and running a delete ,uery. For the basic steps involved in creating and running a delete ,uery, see the section )se a delete ,uery to delete duplicate records, later in this topic. For more complete information about using delete ,ueries, including information on how to plan a deletion and how to change table relationships and delete related data, see the article )se a delete ,uery to delete one or more records from a database.
@owever, if the ,uery included a primary key field, such as an order (D, or some other field that uni,uely identified each record, such as a ship date, you would see that the records are not duplicates. The steps in this section explain how to hide duplicate records where the values in all fields returned by the ,uery match. For example, you can hide one of the records for 9ntonio ?oreno Ta,ueria, but you cannot hide the records for $lauer /ee Delikatessen because the 9ddress fields contain different values. Aemember this rule as you proceedB Two or more records are considered duplicates only when all the fields in your ,uery results contain the same values. (f the values in even a single field differ, each record is uni,ue, and you cannot hide those records by using the techni,ues shown here. (f you want to hide those kinds of duplicate records, you can do so by using a totals ,uery with an aggregate function, such as "I2S4, ,I', , F, and so on. For information on doing so, see the section, /how distinct records by specifying which duplicate appears in your results, later in this article. 9ccess provides two ways to display only uni,ue values in a ,uery result setB
(f you hid the primary key field %or some other field that makes a record uni,ue&, unhide that column. +reate a select ,uery, and then set the !ni3ue -alues property of the ,uery to Yes. -hen the ,uery finds duplicate values, it displays only one of those duplicates %the first one it finds& and hides the rest.
To edit or delete data, open the underlying table in Datasheet view. #n the %reate tab, in the &ther group, click #uery Wi$ard.
i& 4& (n the 'ew #uery dialog box, click Simple #uery Wi$ard, and then click &0. i& (f an alert message appears and tells you the feature is not installed, click Yes to install the wi.ard. (n the list of tables, select the table that contains duplicate records, and then click 'e(t. (n the list of available fields, select only the field or fields that contain the duplicate information, and then click 'e(t. +lick 'e(t again without selecting any additional fields. 9dding any other fields can cause 9ccess to treat some duplicate records as uni,ue records. 9ccept the suggested name for the ,uery, or enter a name of your own, click ,odify the 3uery design, and then click "inish to open the ,uery in Design view. Aight3click the empty area in the top half of the ,uery designer, and then click /roperties. (n the property sheet, locate the !ni3ue -alues property and change it to Yes.
i&
to run the ,uery and display the results in Datasheet view. (f your data contains duplicate records, only one of those records appears.
'ou can use a totals ,uery and an aggregate function with that data in several waysB
)se the "irst function to show only the record that was entered first. )se the @ast function to show only the record that was entered last. )se the ,a( or ,in function to show only the record with the smallest or largest value in a specific field. For example, you can show the record with the most recent date by using the ,a( function, or show the record with the earliest date by using the ,in function.
N#T1 'ou cannot edit the data that this type of ,uery returns. To edit or delete data, open the underlying table in Datasheet view.
The steps in this section explain how to ,uery for original, most recent, and oldest records. The steps use the 1mployees table.
LAST NAME
Barnhill
FIRST NAME
Josh
ADDRESS
1 Main St.
CITY
New York
BIRTH DATE
5"1e9"14&3
HIRE DATE
1 "Jun"1444
%eloo *uido
$aleed )ica
52 1st St. 3122 +5th #,e. S.$. 1 'ontoso Bl,d. 'alle Smith 2
Boston Seattle
22"Ma("145+ 11"No,"14&
22"No,"144& 11"Mar"2
Ba.el )rice
22"Mar"14&4 5"Jun"14+2
22"Jun"1443 5"Jan"2 2
3122 +5th St. S. &+ Bi. St. 2 Nose( )kw( 1 'ontoso Bl,d.
23"#-r"1444 14":ct"2 4
24"Mar"144+ 2 "Jun"1443
(f you want to use the table in a database, see the steps in "repare some sample data, earlier in this article.
i& 2& (n the Show 4able dialog box, double3click the table that contains the duplicate data, and then click %lose. i& The table appears in the upper section of the ,uery designer. 9dd only the field or fields that contain the duplicate data. 'ou can double3click a field, or drag it from the table window to the "ield row in the design grid. i& (f you use the sample 1mployees table, add the 0ast Name, First Name, and $irth Date fields, because those fields determine duplication. 9dd the field that specifies your selection criteria. i& (n the sample 1mployees table, you add the @ire Date field, because that field contains two different values for the employee.
4&
5&
ii&
N#T1 Do not add more fields to the grid. 9 totals ,uery must include only the field or fields that contain duplicate data and one other
#n the 1esign tab, in the ShowGCide group, click 4otals contain your table field.
. The 4otal row appears in the design grid, and 5roup 6y appears in the columns that
0eave the 4otal row for all fields set to 5roup by, and then click 2un to run the ,uery and show the results in Datasheet view. (f you used the data from the table above, the ,uery returns GCean "hilippe $agelG twice because his duplicate records have different hire dates. +hange back to Design view, and specify a condition for selecting one record from among the duplicates. To use the sample data, change the value in the @ire Date column in the 4otal row as followsB a& To view the original record, change the value to "irst. b& To view the most recently entered record, change the value to @ast. c& To pick a record based on the value in a specific field, you need to use the ,a( or ,in function. (n this example, you want to view the record with the oldest hire date. To do this, change the value to ,in. +lick 2un to run the ,uery and show the results in Datasheet view.
=& >&
(f your ,uery produces the desired results, you can then change it to a delete ,uery and run it to delete your duplicate records ,uickly and easily. For information about running a delete ,uery, see the section )se a delete ,uery to delete duplicate records, later in this article.
COMPANY NAME
Baldwin Museum of Science Blue Yonder #irlines
CONTACT NAME
Josh Barnhill
ADDRESS
1 Main St.
CITY
POSTAL CODE
PHONE
(5 5! 555" 2122 (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
AMOUNT DUE
;55&.+3
$aleed %eloo
52 1st St.
Boston
2345&
;1<343.24
'oho $iner(
)ica *uido
Seattle
345&+
;321.+4
'ontoso )harmaceuticals
/ondon
NS1 0$2
=45+.&3
1ourth 'offee
Julian )rice
'alle Smith 2
5&+34
;43.+5
'oho $iner(
'hristine %u.hes
345&+
(2 &! 555" 2125 (41&! 555" 2123 (5 3! 555" 2124 (+! 555"2233
;321.+4
%umon.ous 5nsurance
Ste,e 6ile(
7am-a
1234
;24+.45
7re( 6esearch
8ana Birk9(
2 Nose( )kw(
)ortland
4321
;5 4. 4
1ourth 'offee
6eshma )atel
2 'alle Smith
Me2ico 'it(
5&+34
;43.+5
(f you want to use the table in a database, see the steps in "repare some sample data, earlier in this article.
i& 2& 4& (n the Show 4able dialog box, double3click the table that you want to use in the ,uery, or click dd, and then click %lose to close the dialog box. (f you are using the sample data, add the 9mount #wed table to the ,uery. 9dd the fields that contain duplicate data. i& (f you use the 9mount #wed table, you add the +ompany Name and +ity fields, because those fields determine duplication. 9dd the field that provides selection criteria. (f you use the 9mount #wed table, you add the 9mount Due field. #n the 1esign tab, in the ShowGCide group, click 4otals The 4otal row appears in the design grid, and 5roup 6y appears in the row for each field. Do one of the following, depending on your re,uirementsB a& To count a number of records, select the field that contains the values that you want to count, and then change the value in the field in the 4otal row to %ount. (f you are using the sample data, set the value in the 9mount Due field to %ount. b& To calculate a total amount, set the value in the field to Sum.
i&
!& +lick 2un
N#T1 9 totals ,uery can display only summary information. 'ou cannot show the individual values.
that additional action. 'ou can use the Aelationships tool to investigate the relationships in a database. To start the Aelationships tool, on the 1atabase 4ools tab, in the ShowGCide group, click 2elationships. For more information about planning and running delete ,ueries, see the article )se a delete ,uery to delete one or more records from a database. +reate a ,uery, such as a select or uni,ue3values ,uery, and add or change any criteria until the ,uery returns only the data that you want to delete.
+onvert that ,uery into a delete ,uery, and then run the delete ,uery to delete the unwanted data.
(?"#AT9NT 'ou cannot undo the results of a delete ,uery. For that reason, you should back up your database before you run your delete ,uery. For information about backing up your database, see the section $ack up a database, earlier in this article. The following steps explain how to create a select ,uery, convert it to a delete ,uery, and run it to delete records.
i& ii& 2& The ,uery designer opens, and the Show 4able dialog box appears.
/elect the table on the GoneG side of the relationship, click dd, and then click %lose. i& The table appears as a window in the upper section of the ,uery design grid. The window lists all of the fields in the table. This figure shows a typical table in the ,uery designer.
ii& 4& Double3click the asterisk %D& to add all of the fields in the table to the design grid. i& 9dding all the table fields enables the delete ,uery to delete entire records %rows& from the table. #ptionally, add a column that allows you to enter criteria. i& For example, suppose that a customer goes out of business and you need to delete all of the pending orders for that customer. To find <ust those records, you add the +ustomer (D and #rder Date fields to the design grid. (f you followed the preceding step, enter your criteria in the %riteria row of the design grid. i& 'ou must use criteria to return only the records that you want to delete. #therwise, the delete ,uery deletes every record in the table. To continue the example from the preceding step, you enter the (D number of the customer that went out of business and the date on which that customer:s orders became invalid.
5&
6&
ii)
8& !&
For more information about using criteria, see the article )se a delete ,uery to delete one or more records from a database.
(f you followed the preceding step, clear the Show check box for each criteria field. #n the 1esign tab, in the 2esults group, click 2un. i& 7erify that the ,uery returns the records that you want to delete. Jeep the ,uery open, and then go on to the next steps.
=&
%onvert the select 3uery into a delete 3uery and run the 3uery to delete data
2& 2& +lick 1esign -iew to switch from the datasheet to the ,uery designer. #n the 1esign tab, in the #uery 4ype group, click 1elete. i& 9ccess changes the select ,uery to a delete ,uery, hides the Show row in the lower section of the design grid, and adds the 1elete row. ii& 1nsure that the 1elete row in the D %all fields& column displays "rom. The word Where should appear in any criteria columns.
4&
1nsure that you want to delete the data, and then click 2un i& 9ccess prompts you to confirm the deletion. ii& +lick Yes to delete the data.
+lick the ,icrosoft &ffice 6utton The ccess &ptions dialog box appears.
+lick dvanced, and in the 7diting section, under %onfirm, clear the ction 3ueries check box. +lick &0 to close the ccess &ptions dialog box.
(f the table already has a primary key, set the Inde(ed property of the field to Yes ('o 1uplicates) in table Design view. This property prevents the field from accepting the same value for more than one record. Aemember that in some cases, such as fields that contain name and city information, you must accept duplicates. Specify that a combination of values in two or more fields must be uni3ue for each record. For example, suppose you have a table of contact data. 'ou can designate a combination of fields, such as +ontact Name, 9ddress, and +ity, as the primary key for the table. That approach works because it is highly unlikely that two contacts with the same name also share the same address and city. To create a multi3field primary key, follow these stepsB 2. 2. 4. 5. #pen the table in Design view. +lick the row selector to the left of the first field so that the entire row is selected. @old down +TA0 while you click the row selector for any other fields that you want to include in the primary key. Aight3click, and then click /rimary 0ey on the shortcut menu.
This step sets the Inde(ed property of each field in the primary key to Yes (1uplicates &0) so that, for example, you can enter the same name, or address, or city in multiple records, but you cannot enter an identical combination of name, address, and city in more than one record. For example, you can have two contacts named Cean "hilippe $agel who live at 2456 ?ain /treet, but they cannot both live in 0ondon.
Where duplicates e(ist in two tables, show them adHacent to each other
#ften, you might end up with two tables that contain duplicate or overlapping data in the same database. For example, suppose you have a +lients table and a +ustomers tableB 4he %lients table
NAME
Baldwin Museum of Science Blue Yonder #irlines
ADDRESS
1 Main St.
CITY
PHONE
FAX
(5 5! 555" 3123 (1 4! 555" 2124 (2 &! 555" 2125 (1+1! 555" 212& (+! 555"212+
New York (5 5! 555" 2122 Boston (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
52 1st St.
'oho $iner(
Seattle
'ontoso )harmaceuticals
/ondon
1ourth 'offee
'alle Smith 2
'onsolidated Messen.er
(2 &! 555" 2125 (41&! 555" 2123 (5 3! 555" 2124 (5 3! 555" 2233
(2 &! 555" 2124 (41&! 555" 2123 (5 3! 555" 211 (5 3! 555" 2234
7am-a
/itware< 5nc.
3 Microsoft $a(
)ortland
7ails-in 7o(s
4 Microsoft $a(
)ortland
COMPANY NAME
Baldwin Museum of Science Blue Yonder #irlines 'oho $iner(
CONTACT NAME
Josh Barnhill
ADDRESS
1 Main St.
CITY
POSTAL CODE
TELEPHONE
(5 5! 555"2122
52 1st St. 3122 +5th #,e. S.$. 1 'ontoso Bl,d. 'alle Smith 2
Boston Seattle
2345& 345&+
#d,enture $orks
'hristine %u.hes
3122 3+th $a( S.$. &+ Bi. St. 2 Nose( )kw( 4 0m-ire $a(
345&+
(2 &! 555"2125
Notice that in this case, the individual tables do not contain duplicate values, but fields in both tables contain some overlapping values, such as data in the Name field in the +lients table and data in the +ompany Name field in the +ustomers table. 'ou can:t always integrate the data in each table by merging the two tables. For some customers, the +lients table might have the latest information, but the +ustomers table might have the latest data for other users. Typically, the best course of action is to review the contents of both the tables and then decide what to keep and what to delete. To bring the records together from both tables, you create a union ,uery. The ,uery will place duplicate records close together to make it easier to review them.
2&
i& ii& 2& 4& 5& 9ccess creates a new ,uery. The Show 4able dialog box appears.
+lose the Show 4able dialog box without adding any tables or ,ueries to the design grid. Aight3click the document tab for the ,uery, and then click S#@ -iew. (f you used the preceding tables as an example, you paste the following /*0 statement in the window. (f you use your own data, use the following statement as a guide. )se the /101+T, )N(#N 900 /101+T, and #AD1A $' clauses as shown, but substitute the field and table names from your own data. i& S7@7%4 A%ompany 'ameB, A ddressB, A%ityB, A4elephoneB, "2&, A%ustomersB !'I&' @@ S7@7%4 A'ameB, A ddressB, A%ityB, A/honeB, "2&, A%lientsB &2172 6Y A%ompany 'ameBE The first /101+T statement retrieves records from the +ustomers table, and the second /101+T statement retrieves records from the +lients table. The )N(#N 900 clause brings all records from both tables together. The #AD1A $' statement sorts the records so that duplicate records are placed together for easy reviewing.
N#T1 1ach /101+T statement must return the same number of fields, and in the same order. The corresponding fields are re,uired to
ii&
iii&
6&
have compatible data types, but with one exceptionB you can use a Number field and a Text field as corresponding fields. 9lso, remember that field can names differ. +lick 2un to run the ,uery and see the results in Datasheet view. i& (f you use the records in the tables above, the view shows 2= records E all > records from the +ustomers table and all > records from the +lients table. ii& /ave the ,uery, and then close the view. 'ou will use this ,uery in the next section.
6&
+lick 2un to run the ,uery and see the results in Datasheet view. i& (f you use the example data from the previous section, the ,uery returns 25 records instead of 2=.
'ou create an inner <oin by building a select ,uery that includes both tables, and then creating a relationship between the fields that contain the duplicate values. $y default, 9ccess creates an inner <oin when you create the relationship.
N#T1 'ou cannot edit the fields or rows that are returned by a select ,uery that has an inner <oin. (f you want to edit the data, open the underlying tables and change the values in each table.
i& 2& 4& 5& (n the Show 4able dialog box, double3click the +ustomers table and the +lients table, and then click %lose to close the dialog box. (dentify the fields that contain matching values in duplicate records. (f you use the sample tables, the +ompany Name field in the +ustomers table corresponds to the Name field in the +lients table. Drag the +ompany Name field from the first table to the Name field in the second table. 9ccess connects the fields with a line.
i& ii& $y default, the ,uery creates an inner <oin between the two tables. 9n inner <oin selects only those records where the +ompany Name field matches the Name field.
6& 8&
Double3click the %ompany 'ame field to add it to the ,uery design grid. This field will help you identify the records in the Datasheet view. Double3click the other fields that you want from the +ustomers and +lients tables to add them to the ,uery design grid. (n this case, add the "hone field from the +ustomers table and the Telephone field from the +lients table. +lick 2un tables. to run the ,uery and see the results in Datasheet view. The ,uery returns five records, one for each customer with a record in both
!&
COMPANY NAME
Baldwin Museum of Science Blue Yonder #irlines 'oho $iner( 'ontoso )harmaceuticals 1ourth 'offee
TELEPHONE (CUSTOMERS)
(5 5! 555"2122
PHONE (CLIENTS)
(5 5! 555"3123
-iew only records in one table that donIt have a matching record in another table
+ontinuing with the scenario where the +ustomers table and +lients table have duplicate data, you will now see what you need to do to view those records in the +ustomers table that don't have a duplicate record in the +lients table. This might help you make decisions for certain customers, based on the contents of the +ustomers table alone, before you take steps to consolidate the two tables. 'ou can view <ust the records in the +ustomers table that don:t have a match in the +lients table by creating a find unmatched ,uery. )sing the sample data, this type of ,uery retrieves all the records in the +ustomers table that don:t have a match in the +lients table.
N#T1 'ou can edit the field values or delete records when you view this ,uery in Datasheet view.
i& 2& 4& 5& 6& 8& !& (n the 'ew #uery dialog box, click "ind !nmatched #uery Wi$ard, and then click &0. +lick the +ustomers table E it contains the records in which you are interested. +lick 'e(t. +lick the +lients table E this is the table that you want to compare the +ustomers table against. +lick 'e(t. +lick the +ompany Name field in the +ustomers table, click the Name field in the +lients table, and then click the )*+ button. This will <oin the tables, based on customer names. +lick 'e(t. /elect the fields that you want displayed in your view. (n this case, add the +ompany Name, 9ddress, +ity, and "hone fields. +lick 'e(t. Type a name for the ,uery, and click "inish to view the records in Datasheet view. (f you use the sample tables, the ,uery returns four records E in this case, the records in the +ustomers table that don:t have an overlapping record in the +lients table.
COMPANY NAME
#d,enture $orks
ADDRESS
3122 3+th $a( S.$.
CITY
TELEPHONE
1a9rikam< 5nc.
4 0m-ire $a(
1elete duplicate records from one table and merge the remaining records into another table
9fter you review the duplicate data in similar tables, you can delete the duplicate records and merge the remaining data into a single table. The process follows these broad stepsB #ptionally, in the table that you want to delete, update any data that you want to merge. 1xplaining how to update data is beyond the scope of this topic. For information about ways to update data, see the article )pdate the data in a database.
#ptionally, review any relationships that might exist between the table that you want to delete and other tables in the database. (f a relationship exists, you typically delete the relationship and then establish a new relationship with the other table %the table that contains the merged data&. @owever, you need to ensure that the primary key values in the new table match the primary key values in the other tables.
+reate a delete ,uery that uses the !ni3ue -alues property to find and delete any matching records. 9s part of this, you must ensure that you do not disrupt any relationships among the tables in your database. For example, suppose that you want to move any uni,ue records from the +lients table to the +ustomers table, and then delete the +lients table. (f the +lients table is related to any other tables in the database, you must take steps to ensure that the +ustomers table assumes those relationships. 9 full explanation of relationships is beyond the scope of this topic. For more information, see the article +reate, edit or delete a relationship. +reate an append ,uery to add the remaining records from the table that you want to delete to the table that you want to keep. 9s part of that effort, you might need to add the primary key field and values for the appended data to the table that you want to keep.
Delete the unwanted table. The steps in this section explain how to create and use a delete ,uery and an append ,uery, and how to delete a table. The steps use the +ustomers and +lients tables. 4he %ustomers table
COMPANY NAME
Baldwin Museum of Science Blue Yonder #irlines
CONTACT NAME
Josh Barnhill
ADDRESS
1 Main St.
CITY
POSTAL CODE
TELEPHONE
(5 5! 555"2122
$aleed %eloo
52 1st St.
Boston
2345&
(1 4! 555"2123
'oho $iner(
)ica *uido
Seattle
345&+
(2 &! 555"2124
#d,enture $orks
'hristine %u.hes
3122 3+th $a( S.$. &+ Bi. St. 2 Nose( )kw( 4 0m-ire $a(
345&+
(2 &! 555"2125
NAME
Baldwin Museum of Science Blue Yonder #irlines
ADDRESS
1 Main St.
CITY
PHONE
FAX
(5 5! 555" 3123 (1 4! 555" 2124 (2 &! 555" 2125 (1+1! 555" 212& (+! 555"212+
New York (5 5! 555" 2122 Boston (1 4! 555" 2123 (2 &! 555" 2124 (1+1! 555" 2125 (+! 555"212&
52 1st St.
'oho $iner(
Seattle
'ontoso )harmaceuticals
/ondon
1ourth 'offee
'alle Smith 2
'onsolidated Messen.er
(2 &! 555" 1+1 (41&! 555" 2123 (5 3! 555" 143 (5 3! 555" 2234
7am-a
/itware< 5nc.
3 Microsoft $a(
)ortland
7ails-in 7o(s
4 Microsoft $a(
)ortland
(f you want to use these tables in a database, see "repare sample data, earlier in this article. For this exercise, assume that the +ustomers table has the latest information E thus, you want to delete the matching records from the +lients table and then merge the remaining records from the +lients table into the +ustomers table.
i& 2& 4& 5& (n the Show 4able dialog box, double3click the +ustomers table and the +lients table, and then close the dialog box. Coin the two tables by dragging the +ompanyName field in the +ustomers table to the Name field in the +lients table. Aight3click the empty area in the top half of the window, and then click /roperties. /et the value of the !ni3ue 2ecords property to Yes. i& $y <oining the two tables and setting the ,uery:s !ni3ue 2ecords property to Yes, you avoid the %ould not delete from the specified tables message that would otherwise appear when you run the ,uery.
6& 8&
#n the 1esign tab, in the #uery 4ype group, click 1elete. Drag the asterisk %M& from the +lients table to the "ield row of the first column in the ,uery design grid.
i& ii& !& %lients appears in the 4able row and "rom appears in the 1elete row. This means that the ,uery will delete rows from the +lients table.
'ou now need to specify which records the ,uery deletes. (f you use the sample tables, you can do this by deleting records where the values in the Name, 9ddress, and +ity fields of the +lients table match the corresponding fields in the +ustomers table. i& Drag the Name field from the +lients table to the first blank cell in the "ield row in the ,uery design grid. Do the same for the 9ddress and +ity fields from the +lients table. (f you use the sample tables, in the %riteria row, for the Name field, type A%ustomersB.A%ompany'ameB . (n the %riteria row, for the 9ddress field, type A%ustomersB.A ddressB. (n the %riteria row, for the +ity field, type A%ustomersB.A%ityB. 'our ,uery design grid should look like thisB
=&
-hen you run the ,uery, it will delete all records that meet the criteria in the ,uery E those that have matching values in the three fields of each table. >& +lick -iew to preview the records that will be deleted when you run the ,uery. 'ou will see the five duplicate records from the +lients table.
2 & +lick 2un to run the ,uery. -hen asked to confirm the deletion, click Yes. 22& No to the next steps to create an append ,uery.
i& 2& 4& 5& 6& (n the Show 4able dialog box, double3click the source table, double3click the table that contains the records that you want to append, and then click %lose. (f you use the sample data, double3click the +lients table. #n the 1esign tab, in the #uery 4ype group, click ppend. (n the ppend dialog box, in the 4able 'ame list, select the destination table %the table to which you want to append data&. (f you use the sample tables, select the +ustomers table, and then click %lose. ?ove the fields that you want to append from the source table to the "ield row of the design grid.
i&
ii& 8& !& =& >&
(?"#AT9NT ?ove only those fields that have a corresponding field in the destination table.
(f you use the sample data, move the Name, 9ddress, and "hone fields.
+lick the ppend 4o row in each field and select the name of the corresponding field in the destination table. (f you use the sample data, you select the +ustomer Name, 9ddress, and Telephone, fields, respectively. $ecause you want to add all the records in the +lients table to the +ustomers table, you need not specify any criteria. +lick -iew records that will be added to the +ustomers table when you run the ,uery. /ave and close the view. Find the append ,uery, and double3click it. +lick Yes to confirm the append operation. to preview the
i&
N#T1 Deleting database tables can break part or all of the functionality of a database. For that reason, you must plan a deletion to
ensure that your database remains functional, and you should always back up your database before you delete data or other components. ii& For more information about deleting data, see the article Delete one or more records from a database.
See only the distinct records when viewing data from related tables
9 ,uery that brings together data from two related tables might show records where all fields seem to match. @owever, if you review the tables, you might find that the tables don:t actually contain duplicate records. That problem arises when the ,uery does not include certain fields, such as a primary key, that can uni,uely identify each record. (n such scenarios, you do not want to delete the records, but you can take action to hide what appear to be duplicates. For example, suppose that you use a ,uery to gather customer order data from two tables and ensure that your staff fills orders on time. 'our customers can place an order for multiple products, so each product becomes a separate record %a row& in the underlying tables. $ecause the order is placed on a single day, and then shipped on a single day, the records for a given order can contain large numbers of duplicate dates, like soB
$ecause you know that orders arrive on a given day, and you ship the orders on a given day, you need to see only one record %one row& per order. To display uni,ue records from the tables that contain your order data, you can set the !ni3ue 2ecords property for the ,uery to Yes. -hen the property is set to Yes, the ,uery looks at all the rows in the tables and, where it finds matching rows %not <ust fields&, the ,uery excludes all but one of those duplicate rows from your result set.
9s you proceed, remember that when the !ni3ue 2ecords property is set to Yes, the ,uery compares entire rows, and the rows in all of the tables involved must match before the ,uery excludes any data. 9lso, you can use the !ni3ue 2ecords property setting only when a ,uery includes two or more tables.
-hen you switch to Datasheet view, you see only one record for each order.
Aemember too that when you set the !ni3ue 2ecords property to Yes and run the ,uery, you might still see what appear to be duplicate records. To continue the previous example, you might still find records with matching order and shipped dates, like soB
This happens when you receive two different orders on the same day, and you then ship them on the same day. /etting the !ni3ue 2ecords property to Yes does not hide such records from the ,uery results because the records are not actually duplicates in the underlying tables. (f you want to see only one instance of such records %that is, one order record per day&, you need to set the ,uery:s !ni3ue -alues property to Yes. -hen the !ni3ue -alues property is set to Yes, the ,uery does not look at the underlying tables for duplicates. (nstead, it looks at the values of the fields that you include, and if all fields match for two records, the ,uery hides one record from the view. 'ou set the !ni3ue -alues property in the same way that you set the !ni3ue 2ecords property E display the property sheet for the ,uery and change the setting to Yes. (n the property sheet, the !ni3ue -alues property box resides above the !ni3ue 2ecords property box.
To continue the previous example, you now see only the dates on which one or more orders were received or shipped. 'ou do not see one record per order.
N#T1 $ecause setting the !ni3ue 2ecords property to Yes operates against the rows in the tables that provide data to your ,uery, and setting the !ni3ue -alues property to Yes operates only against the fields in your ,uery, you cannot use both properties together. (f you set one to Yes, 9ccess automatically sets the other property to 'o. @owever, both can be set to 'o to return all records.
The following table provides a summary to help you choose settings for the !ni3ue 2ecords and !ni3ue -alues properties in a ,uery.
SET%%%
RESULT%%%
7wo or more ta9les< 9ut 8istinct records from the ta9le (all the U'()"e Re*#rd to Ye . 5f the ta9le contains du-licate records< the Fuer( i.nores the all Fuer( fields come fields in the ta9le must match for two (#ccess sets U'()"e +,-"e du-licates. %owe,er< the Fuer( results mi.ht still show records from a sin.le ta9le records to Fualif( as du-licates! to N# automaticall(!. where all fields match< if the Fuer( does not include a field that uniFuel( identifies the records. :ne or more ta9les 8istinct records in Fuer( 8atasheet ,iew (all the fields in 8atasheet ,iew must match for two records to Fualif( as du-licates! #ll records U'()"e +,-"e to Ye . (#ccess sets U'()"e Re*#rd to N# automaticall(!. U'()"e +,-"e to N# and U'()"e Re*#rd to N#. 7he Fuer( e2cludes du-licate records (where all fields match! in 8atasheet ,iew. %owe,er< remem9er that (ou mi.ht not see all the distinct records from the underl(in. ta9le.
You see all uniFue and du-licate records from 9oth ta9les.
Find the total ,uantity of each product sold by each employee. +ount the total number of orders that each employee handled for each customer. Find the largest order of the day for each employee. To summari.e data, you use a totals ,uery similar to the ones discussed in the section /how distinct records by specifying which duplicate appears in your results, earlier in this article. That section explained how to use a totals ,uery with a single table. To create a totals ,uery that contains multiple tables, do the followingB
Aemember to add the second table when you add the first table in the Show 4able dialog box. -hen you add the fields that determine duplication, drag the fields that you want from either table and, for all fields, set the value in the 4otal row of the column to 5roup 6y. The field that identifies the record that you want to see or that has the values that you want to summari.e can come from either table.
The shortest, fastest, and easiest way to compare two tables in SQL Server: UNION !
When you have two tables (or resultsets from SELECT statements) that you wish to compare, and you want to see any changes in !" columns, as well as to see which rows e#ist in $ table but not the other (in either direction) % have found that the &!%'! operator wor(s )uite well* &!%'! allows you to compare all columns very )uic(ly, and also handles comparing !&LL values to other !&LLs successfully, which a +oin clause or a W,E-E condition doesn.t normally do* %t also allows you to very )uic(ly see which rows are missing in either table, which only a /&LL '&TE- 0'%! will do, but of course we all (now to avoid those at all costs (right1) 22 a full outer +oin is about as 3unrelational4 as you can get* (every column returned is potentially !ull and must be wrapped in a C' LESCE function)* 5est of all, the &!%'! is )uic( and easy and short* The basic idea is6 if we 7-'&8 the union of two tables on all columns, then if the two tables are identical all groups will result in a C'&!T(9) of :* 5ut for any rows that are not completely matched on any column in the 7-'&8 5" clause, the C'&!T(9) will be $ 22 and those are the ones we want* We also need to add a column to each part of the &!%'! to indicate which table each row comes from, otherwise there is no way to distinguish between which row comes from which table*
So, here.s an e#ample, assuming we are comparing tables (ey of both tables is %;6
FROM (
SELECT 'Table A' as TableName, A.ID, A.COL1, A.COL2, A.COL3, ... FROM A UNION ALL SELECT 'Table B' as TableName, B.ID, B.COL1, B.COl2, B.COL3, ... FROM B ) tm !ROU" B# ID, COL1, COL2, COL3 ... $A%IN! COUNT(&) ' 1 ORDER B# ID The above returns all rows in either table that do not completely match all columns in the other* %n addition, it returns all rows in either table that do not e#ist in the other table* %t handles nulls as well, since 7-'&8 5" normally consolidates !&LL values together in the same group* %f both tables match completely, no rows are returned at all* The <%!() aggregate function used on the TableName column is +ust arbitrary 22 it has no effect since we are only returning groups of rows in which there has been no consolidation with the 7-'&8 5" (note the , =%!7 clause)* %.ve posted an implementation of this techni)ue as a stored procedure in the S>LTeam script library section of the forums (http6??www*s)lteam*com?forums?topic*asp1T'8%C@%;A:BCDE)* ,ere it is, below6 CREATE "ROCEDURE C(m a)eTables(*table1 +a),-a)(1..), *table2 %a),-a)(1..), *T1C(l/m0L1st +a),-a)(1...), *T2C(l/m0L1st +a),-a)(1...) ' '') AS
22 Table1, Table2 a)e t-e tables () +1e3s t( ,(m a)e. 22 T1C(l/m0L1st 1s t-e l1st (4 ,(l/m0s t( ,(m a)e, 4)(m table1. 22 5/st l1st t-em ,(mma2se a)ate6, l17e 10 a !ROU" B# ,la/se. 22 I4 T2C(l/m0L1st 1s 0(t s e,141e6, 1t 1s ass/me6 t( be t-e same 22 as T1C(l/m0L1st. 22 22 T-e )es/lt 1s all )(3s 4)(m e1t-e) table t-at 6( NOT mat,22 t-e (t-e) table 10 all ,(l/m0s s e,141e6, al(09 31t- 3-1,- table t-at 22 )(3 1s 4)(m. 6e,la)e *S:L +a),-a)(;...)< IF *t2C(l/m0L1st ' '' SET *T2C(l/m0L1st ' *T1C(l/m0L1st set *S:L ' 'SELECT ''' = *table1 = ''' AS TableName, ' = *t1C(l/m0L1st = ' FROM ' = *Table1 = ' UNION ALL SELECT ''' = *table2 = ''' As TableName, ' = *t2C(l/m0L1st = ' FROM ' = *Table2 set *S:L ' 'SELECT Ma>(TableName) as TableName, ' = *t1C(l/m0L1st = ' FROM (' = *S:L = ') A !ROU" B# ' = *t1C(l/m0L1st = ' $A%IN! COUNT(&) ' 1' e>e, ( *S:L) Ot-e)31se, l1st t-e ,(l/m0s (4 Table2 10 22 t-e same ()6e) as t-e ,(l/m0s 10 table1 t-at 8(/ 31s- t( ,(m a)e.
Un)eyed Tables
/or tables without a (ey field or )ueries where the first field is not designated as the primary (ey, records are compared se)uentially and the first record that.s different is documented*
Every record that's different is shown with its primary key(s), difference type, and details. For modified records, the field differences, number of fields, and field names are listed.
For each modified record, every field difference is shown side-by-side While viewing the results, there are several options6 'eports6 Several reports are available for you to print, preview, report view, or e#port to file in formats li(e dobe 8;/, ,T<L, snapshot, te#t, etc* ,-port6 To e#port the data differences to a table in your database &ombine6 To merge the two data sources into a new table
Specify $ow Fields are %atched for !omparison ll field names and types match Compare fields by order regardless of field names, provided field types and number of fields match Compare identical field names regardless of field orderH other fields are ignored
&isplay Field &ifferences on (ne )ine or a Separate )ine for Each Field