SQL SELECT
Tweet |
SQL SELECT is without a doubt the most frequently used SQL command that's why we are starting our tutorial with it. The SQL SELECT command is used to retrieve data from one or more database tables.
To illustrate the usage of the SELECT command we are going to use the Users table defined in the previous chapter:
FirstName | LastName | DateOfBirth |
John | Smith | 12/12/1969 |
David | Stonewall | 01/03/1954 |
Susan | Grant | 03/03/1970 |
The SQL statement below shows a simple usage of the SQL SELECT command:
Let's examine this SQL statement. The statement starts with the SELECT keyword followed by a list of table columns. This list of columns specifies which columns you want to retrieve from your table. The list of columns is followed by the SQL keyword FROM and the table name (the table we are selecting data from).
There is a special syntax that can be used with the SELECT command, if you want to retrieve all columns from a table. To do that replace the list of columns with the * symbol and voila, you've selected all columns from the table:
It's a prudent programming practice to explicitly specify the list of columns after the SELECT command, as this will improve your query performance significantly.
The SELECT INTO statement retrieves data from a database table and inserts it to another table.
Consider the SELECT INTO example below:
The first part of the statement looks familiar and is just selecting several columns. The second part of this SQL statement is the important part, which specifies to insert the rows into the UsersBackup table. The last part specifies which table to get the rows from. This example assumes that both Users and UsersBackup tables have identical structure.
You can use the following SQL query to make an exact copy of the data in the Users table:
So far you learnt how to specify which columns to select and from which table, but you might be wondering how many rows of data will actually be returned from these SQL statements? The answer is simple - all of them. But what if you have a table with 5 million rows, and you only need to select a few rows satisfying certain criteria? Fortunately there is a way to conditionally select data from a table or several tables. Enter the SQL WHERE command.
References: http://www.sqlclauses.com/sql+select