These SQL Server Performance Tips are from Simon Harriyott’s blog.
Posts Tagged ‘SQL Server
SQL Server Performance Tips
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.
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
Unfortunately this SQL doesn’t work in Access.