In a typical query, two tables with different fields
can be joined as long as there is a common field. The
combined set of fields is linked by the common field
that both tables share.
Take a look at a query we used in last month's
Wizard:
In this query, the common field for the two tables is
the CabinKey. The resulting query brings the fields
together from both tables, linked by the common field.
A Union Query is fundamentally different. A Union
Query is unique because it brings the same fields from
two or more tables together. Think of your standard
query as putting two tables side-by-side, linked by a
common field. In a Union Query, you put the tables one
on top of the other.
Take the following tables
The first table contains 7 records of active
customers; the second table contains 8 records of
inactive customers. These two tables contain the same
fields and the same type of data in each of their
fields. In this case, the names of the tables describe
their function. As I mentioned earlier, this application
is poorly designed. A more effective approach would be
to include a field in the customer table indicating the
status of each customer (active or inactive).
Now let's say that you want a report that shows all
of your customers, regardless of status. Our goal is to
get one query that contains the full set of data from
both tables. You could, as my client did, create a third
table and append each of the two tables into the new
table and use that; however a Union Query is a much more
efficient solution.
Building a Union Query is not as straightforward as
your typical query. You must build it in the SQL design
Window. For details on the SQL design window see the (June
2005 edition)
Open up a regular query window in design view (From
the Query tab choose New | Design View). This will take
you to the standard design window. Access will invite
you to select tables for your query; choose Close to
dismiss that dialog box. On the menu at the top of the
screen choose View | SQL View. This is where we'll build
our Union Query. The format is:
select (fields) from (source table 1
name)
union
select (fields) from (source table 2
name)
So, for this example, you'd type:
select * from tblcustactive
union
select *
from tblcustinactive
(Read the details below to find out more about the
use of the wildcard (*) to designate fields.)
When you run this query you get:
The result is one combined table showing all 15 of
our customers combined from both the active customer
table (7) and the inactive customer table (8).
Now if you attempt to look at this query in design
view, you'll automatically be redirected to the SQL
window. Access has no way to represent a Union Query
visually.