Using the SQL SELECT Statement
The SQL SELECT statement enables you to retrieve data from your database and is usually the first statement that people learn when they are new to SQL. A SELECT statement can be very simple but there are plenty of optional parts to it that can make it a lot more complicated. It is a very powerful statement that enables you to filter and shape the data that you want to retrieve. In this multi part series on the SQL SELECT statement we will start off demonstrating the SELECT statement in its simplest form and then building on this we will demonstrate additional aspects of the SELECT statement.
The basic SELECT query
In its most basic form the SELECT statement retrieves specified columns from a single table. The syntax for this is:
The ColumnNames(s) argument is the list of columns that you want to retrieve. The column names should be seperated by commas and there should be no comma after the last column name.
The columns in the returned resultset are listed left to right in the same sequence as you specify in your SELECT column list. This enables you to re-arrange the sequence of columns to a sequence that is different to that of the column sequence in the table that you are retrieving the data from.
The TableName argument for the FROM clause is the name of the table that we want to retrieve data from. In the below example we retrieve 3 columns (PublisherID, Title and Synopsis) from the table in our database that stores book information.
If you want to select all the columns from a table you can use a handy shorthand method. Instead of writing out a list of all the column names you can simply use the asterisk (*) symbol as a shorthand version. In this context * means 'All columns' :
By default the resultset that is returned by the SELECT statement assigns the same column headings as those given in the ColumnName list. There are times however when you may want a more user friendly column name. This can be achieved by assigning an alias to the column name by using the 'As' keyword in the ColumnName list. The alias should be enclosed in single quotation marks In the example below we select the cat_ID column from the Books table but we assign it an alias of Category ID so that when a user views the results of the query they are quite clear what the column represents:
Conclusion
In this article we have shown how to write a basic SQL SELECT query that retrieves data from a table. We have seen how we can adapt the resultset by specifying to retrieve one, some or all columns, changing the sequence of the columns returned and providing more user friendly column headings by using the 'As' keyword to specify column aliases.
In the next article in this series we will learn a hugely powerful feature of the SELECT statement - the WHERE clause - which will enable us to influence which rows are returned from the table we are querying.