|
SELECT [Alias].<Column Name>,[Alias].<Column Name>,[Alias].<Column Name>,etc... FROM <Table Name> [Alias] WHERE <Column Name> [= < > != BETWEEN NOT] <Column Name or Value> [AND/OR] [<Column Name> [= < > != BETWEEN NOT] etc.] GROUP BY <Column Name> ORDER BY <Column Name> [Sort Order] <ASC or DESC>; |
|
I know the syntax looks rather intimidating if you are just starting out, but it is rather simple once it has been broken down for you. There are 2 Mandatory parts to a SELECT statement. The SELECT and the FROM. The other three peices (WHERE, GROUP BY, ORDER BY) are optional, I highly recommend the use of WHERE in all your SELECT statements, as there are very few occations where you will require all of the data in your table. So back to our example, we will get all of the data in our table for display. We will need the following statement to do this. (Watch how the alias is used and don’t forget to terminate your statement with a semi-colon) |
|
SELECT TC.nID, TC.nLegs, TC.strColor, TC.strSize, TC.strType, TC.nWeight FROM tblChair TC; All of our table data is returned to us using this statement. |
|
|
|
|
|
|
|
|
Now we will only return the data in our table where the chairs have 4 legs. This will demonstrate the use of the WHERE clause |
|
SELECT TC.nID, TC.nLegs, TC.strColor, TC.strSize, TC.strType, TC.nWeight FROM tblChair TC WHERE TC.nLegs = 4; Only the data where the chairs have 4 legs is returned to us. |
|
|
|
|
|
|
|
|
Well, now we only want to see if we have a chair in our data that has 4 legs, and we don’t really want to return more that one row. This will demonstrate the use of the GROUP BY clause, which will take all common elements in a record set and display them only once. |
|
SELECT TC.nLegs FROM tblChair TC WHERE TC.nLegs = 4 GROUP BY TC.nLegs; Only the data where the chairs have 4 legs is returned to us, and even though we have more than one row with this criteraa, our SELECT/GROUP BY will only return the following. |
|
nLegs |
|
|
The last thing we need to know about SELECT Statements is the ORDER BY clause. This allows you to sort your data in ASC (Ascending) or DESC (Descending) order by the column(s)/field(s) you choose. If you leave the sort order blank, it will default to Ascending order. I will remove the GROUP BY clause for demonstration purposes. |
|
SELECT TC.nID, TC.nLegs, TC.strColor, TC.strSize, TC.strType, TC.nWeight FROM tblChair TC WHERE nID IS NOT NULL ORDER BY TC.nWeight DESC; |
|
|
|
|
|
|
|
|
At this point, I have given you the basics, now the best thing you can do is practice. Visit the SQL Links page for some great Tutorial sites with online practice zones or continue on to the next lesson. |
![]() |
|||||||