HomeBrainDump Beginning SQL the SEQUEL: Working with Advanced SQL Statements
Beginning SQL the SEQUEL: Working with Advanced SQL Statements
So you made it through the first tutorial and now you are back for more. Well buckle up for the ride, because this episode teaches you the glories of advanced SQL statements. By the end of this article you'll be able to sort data, join data, you name it.
That's right, hordes of rows and columns will be at your mercy. You won't only know SQL -- you'll be SQL. So slap on your cool shades and trench coat and get ready to dodge bullets in slow motion. And prepare to become the one.
Disclaimer: You won't actually be able to dodge bullets after reading this article. You will however be able to avoid being shot at by your boss when you show him your l33t programming skillz.
Sorting Things Out
Before I became a big, illustrious writer with oodles of fans, I worked for a boss who liked to sort everything. Even if it couldn't be sorted, he wanted me to sort it. Hours on end he would call me into his office imploring me to sort by name, date, value. And off I would scurry to do his bidding. Then one day he began to ask me to sort things around his office. Like his garbage can and the stapler. Last I heard he was in a small room with a white jacket. They say when the nurses come to bring him his pills, he whispers softly, "Can you sort those for me?"
To sort in SQL, you will need a handy little phrase called the ORDER BY statement.
SELECT FirstName, LastName from EMPLOYEES
ORDER BY LastName;
In the above code, we are telling the database to choose and display the columns FirstName and LastName from our table, Employees, and to then sort them alphabetically by the last name.
If you wanted to sort the same two columns in reverse alphabetical order, then you would do so by adding DESC (descending) to the code.
SELECT FirstName, LastName from EMPLOYEES
ORDER BY LastName DESC;
You can, of course, also sort by more than one column. Say you wanted the first name, last name, and salary of every employee, sorted first by last name, then by salary.
SELECT FirstName, LastName, SALARY from EMPLOYEES
ORDER BY LastName, SALARY;
And finally, for a last bit of sorting madness, if you wanted to sort by LastName in Ascending order and SALARY in Descending order, you would grab a safety helmet and type in the following code: