- Introduction
- Creating Joins with the SQL Server View Design Tool
- Conclusion
- Join Syntax
There are two primary ways to get to the View Design Tool: by right-clicking Views and choosing New View (see Figure 2), or by right-clicking an existing view and choosing the Design option. Figure 3 shows the four-pane View Design Tool screen.
Figure 2 Creating a new view in SQL Server Enterprise Manager.
Figure 3 SQL Server 2000 View Design Tool.
TIP
If the panes don't appear as shown in Figure 3, click the icons numbered 36 on the toolbar to insert the appropriate panes. (These buttons toggle the panes on and off.)
The first pane is for adding tables; the second for selecting columns, criteria, and sort orders. The third pane shows the SQL query and the fourth shows the query results.
Inner Join
To start creating the inner join, simply click the Add Table button (the one with the plus sign) on the toolbar to add tables or views to our designer. Figure 4 shows the tables in the Northwind sample database used for this example. After adding the Customers and Orders tables from Northwind, we get the result in Figure 5.
Notice the relationship connector in Figure 5 between the Customers and Orders tables. This relationship was already established in the database via a primary-to-foreign key relationship. The first table added is the left table.
CAUTION
Because Enterprise Manager is graphical, the table can be moved to another positionso it may not always appear on the left.
Figure 4 Adding tables to the join.
Figure 5 Inner join of Customers and Orders.
Next, we choose some columns by clicking the check boxes by the columns. For this example, I chose CompanyName, ContactName, OrderID, and OrderDate, and we now have a complete query.
TIP
This is a good way to build a query for the SQL Query Analyzer or stored procedure. Simply copy the query from the SQL pane and paste it into any text editor.
Notice that the dbo. prefix (short for database owner) has been appended to all items in the query. Most database tables are owned by dbo; obviously, if dbo doesn't own the table, the prefix of the owner will appear instead.
To run the query, click the Run button on the toolbar (showing a red exclamation point), or right-click anywhere in the blank gray area of the first pane and choose Run from the context menu. The fourth (result) pane should be populated with the query results, as shown in Figure 6.
Figure 6 Query results.
Now that we've covered the basics, let's begin to analyze joins and see where the View Design Tool really shines.
All relationships between tables (or even within tables) in the database are inner joins; thus, the center of the relationship connector in our example looks like a diamond/parallelogram. If you right-click the connector, a context menu appears, as shown in Figure 7.
Figure 7 Context menu for an inner join relationship connector.
The first option, Remove, deletes the relationship connector for the current view. (This doesn't affect relationships in the database itselfjust the view that we're creating.) By default, the next two options are not checked with inner joins, because only matching rows satisfying the ON condition are returned.
Left Outer Join
To create a left outer join, we click the Select All Rows from Customers option and close the context menu. We now have a left outer join between the Customers and Orders tables, so the join shape on the relationship connector changes to a half-square on the left side (see Figure 8). Notice that the join type in the SQL pane has changed from INNER JOIN to LEFT OUTER JOIN. Executing this query will return the selected columns for all customers, whether or not they have orders.
Figure 8 The query now contains a left outer join.
In the standard Northwind database, two customers have no orders. For these customers, the OrderID and OrderDate entries are null. To see these rows in this example, we need to scroll through the entire 832 rows of the result set.
TIP
How did I come up with 832 rows? Glad you asked. One regrettable omission from the View Design Tool is a row count. To get a row count, copy the text from the SQL pane to the SQL Query Analyzer (see Figure 9). The row count will normally appear either in the status bar or in the Messages tab.
Figure 9 SQL Server 2000 SQL Query Analyzer showing the row count.
Meanwhile, back at the ranch, we'll extend our left outer join to more easily see only the customer records without orders. We'll do that by adding a WHERE condition to look for any OrderID that's null. (Always use IS NULL to check for equality to NULL.)
There are two ways to enter the WHERE clause:
by using the Criteria column of the second pane
by adding the clause directly to the SQL statement in the SQL pane
The end result will look the same, after the View Design Tool edits the query and before executing it. Figure 10 shows the WHERE condition and results for this example.
Figure 10 Customers without orders in the Northwind database.
NOTE
We could just as easily have checked for a null OrderDate, as all we're looking for is a null column in the Orders table. The column doesn't even have to be selected in the second pane for outputany column in the Orders table would work just fine. The same number of rows would be returned, even without any selected order columns.
Right Outer Join
How do we change this query to a right outer join? And what are we asking from the system's point of view? In short, we're asking whether any rows in the second (right) table exist without matching rows in the left.
Because a primary/foreign key relationship (one to many) exists in this database, with the setting Enforce Relationship for Inserts and Updates active between the Customers and Orders tables, we expect all orders to have the customer number of an existing customer. How could life be otherwise? Well, in a real-world scenario:
We could have imported some data and disabled the constraints.
We might have tables that were built without constraints, and later created the constraints without using the option Check Existing Data on Creation.
We could have altered the table at some point to disable the constraints.
Let's set up the right outer join. To change the setting for the query, right-click the join connector; then deselect Select All Rows from Customers in the context menu. Right-click again, and click Select All Rows from Orders. (The checks are toggles.)
We also need to change the columns to check for nulls in the Customers table. Using the field Customers.CustomerID to test for nulls, the screen should look similar to Figure 11.
Figure 11 Searching for orders without customers.
Prestono orphaned rows appear. Life is good!
Full Outer Join
How do we find unmatched rows in both tables? Because we just unchecked Select All Rows in Customers, why don't we select it again while leaving the other option, Select All Rows in Orders, selected as well?
However, let's change the WHERE clause to look for nulls in both tables (see Figure 12). This will show us only the extra rows from both outer joins. (We have eliminated all of the inner join rows with our WHERE clause.)
Figure 12 Full outer join of Customers and Orders.
This looks a lot like our left outer jointhe one in which we checked for customers without orders. Because there were no orphaned order records, this is exactly what we got.
Notice that the join symbol is now a square, with an etched diamond or parallelogram. The beauty of using this tool is that it helps you immediately spot the join relationships.
Cross Join
The cross join is kind of a misnomer. Cross joins are really a pairing of rows from one table to the rows of another. For example, you might want to generate a list of different name combinations from first names and last names for test data.
TIP
The number of result rows in a cross join is always the number of rows of each table, multiplied together.
For this example, we'll start with a new view, using the Employees table in a self join. Because the Employees table has nine rows, we can expect 81 rows in the result set.
To create the self join, add the table twice by double-clicking twice on the list item in the Table list box.
Remove the join condition by clicking it and deleting.
Choose FirstName from Employees, and LastName from Employees_1.
To make the output clearer, order by dbo.Employees.FirstName and Employees_1.LastName. You can do this by entering the text directly into the SQL pane, by choosing 1 and 2 in the Sort Order column, or by choosing the Ascending option in the Sort Type column in respective order.
NOTE
To keep the two identical tables separate, the SQL 2000 View Design Tool prefaces the second table as Employees_1, and aliases the second listing of dbo. Employees with Employees_1.
Figure 13 shows the cross join.
Figure 13 Self join/cross join on Employees.
The result is a pairing of the FirstName in every row of the first table with the LastName of every row of the second table.
Although this query seems innocent enough, two tables with 5,000 rows each can yield 25 million records. This join is often done by mistake late in the day, simply by leaving out a WHERE clause or join condition. Following is a nonANSI example of how this query can be written:
Select * from table1, table2
CAUTION
For large tables, it's not uncommon to run out of system swap area or otherwise bog down system resources with this kind of query.