Monday, 19 April 2010

Two SQL tips

Here's something that I've overlooked but naturally managed to get right (most of the time) when writing SQL commands - the order of the statements. This is how it should be done:

select ...
    from ...
        where ...
            group by ...
                having ...
                    order by ...;

It might seem obvious but it is important to remember it. Here are two sayings that make it easy to remember the order:

Some French Workers Glue Hardwood Often.
San Francisco, Where The Greatful Dead Heads Originated.
 
In case you're wondering, I didn't come up with those.
 
Another tip with SQL, is that when you use UNION, the statements coming after the WHERE clause must come after the last SQL SELECT and WHERE statement. This is how to write it properly:
 
SELECT id, name, password, 'Student' AS position FROM students
WHERE username LIKE '%ar%'
UNION
SELECT id, name, password, 'Staff' AS position FROM staff
WHERE username LIKE '%ar%' 
ORDER BY position;
 
This makes the whole dataset ordered by position. If you try to order individual SELECTs it will throw an error.

No comments:

Post a Comment