Category Archives: Database Development

SQL: Full Outer Join

A full outer join is used when you need to return all rows from both the left and right tables.  Where there is no row match in the other table then a row of nulls is returned.

For example:


SELECT E.LastName, L.LocationID
FROM Employees E Full OUTER JOIN Location L
ON E.LocationID = L.LocationID

This should include, in a single list, employees that have not been allocated a location and those locations that do not have any employees.  The list can be filtered futher by checking for NULLs on either table.

SQL: With Ties

When you need to return the top number of rows in a result set you would use SELECT TOP which can be a percentage or number e.g.

SELECT TOP 5% … etc
SELECT TOP 5 … etc 

This is fairly simple but what if the fifth, sixth and seventh rows had the same value.  You would probably want to return them as well.  This can be achieved by using WITH TIES e.g. 

SELECT TOP 5 WITH TIES EmployeeID, Salary
FROM Employee
ORDER BY 2 DESC  /* the 2 represents the second column */

The result set would have 7 rows. 

Also see With Ties – SQL Server Tip from Simon Harriyott’ blog for an excellent example.

Using SQL to loop through a result set

Found this code sample recently on how to loop through a result set without using a cursor and therefore reducing any locking problems.


DECLARE @NextID INT
SELECT @NextID = MIN(EmployeeID) FROM Employees
WHILE @NextID IS NOT NULL
BEGIN
SELECT EmployeeID, FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = @NextID
SELECT @NextID = MIN(EmployeeID) FROM Employees WHERE EmployeeID > @NextID
END

The code is incomplete.  I imagine using a SELECT INTO statement to insert the records into a temporary table would be useful.

simple SQL for reporting

I’ve been studying for my MCP in database design (70-229) recently when I found this simple and useful query technique.

Scenario:
You have to run a report against two related tables.  Let’s use the Employee and Orders tables from the Northwind sample database.

You want to see a row for every record in the Employee table; however the report has to be filtered using criterion which applies to both tables e.g.

Region = ‘WA’ (Employee table)
Order Date > ’07/12/1996′ (Orders Table)

What you want is a row for each employee record with NULLs placed in the fields that do not match the criteria.

It’s easy to apply this criterion and obtain output that returns employees that match the criteria, but not all employees would be outputted i.e. those that do not match the criteria.

Here is the SQL to obtain the desired output:


SELECT E.LastName, O.OrderID, O.OrderDate, E.Region
FROM Employees E LEFT OUTER JOIN Orders O
ON E.EmployeeID = O.EmployeeID
AND E.Region = 'WA'
AND O.OrderDate > '1996-07-12'
ORDER BY E.LastName

Note that there is no WHERE clause.

Output: (SQL Server 2000)

Output from SQL code

Output from SQL code

Unfortunately this SQL doesn’t work in Access.