Friday 3 December 2010

The SQL SELECT Statement

The SQL SELECT Statement

The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.

SQL SELECT Syntax

SELECT column_name(s)
FROM table_name
and
SELECT * FROM table_name
Note Note: SQL is not case sensitive. SELECT is the same as select.

An SQL SELECT Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to select the content of the columns named "LastName" and "FirstName" from the table above.
We use the following SELECT statement:
SELECT LastName,FirstName FROM Persons
The result-set will look like this:
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

SQL - Select All (*)

"SELECT (*)" is a shortcut that can be used to select all table columns rather than listing each of them by name. Unfortunately, going this route doesn't allow for you to alter the presentation of the results.

SQL Select All Query:

USE mydatabase;

SELECT *
FROM orders;

SQL Orders Table Results:

idcustomerday_of_orderproductquantity
1Tizag2008-08-01 00:00:00.000Pen4

SQL - Selecting Data

The (*) query statement should be used with caution. Using this against our little tutorial database will surely do no harm, but using this query against an extremely large database may not be the best practice. Large databases may have web services or applications attached to them, so frequently updating and accessing large quantities data may temporarily lock a table for fractions of a second or more. If this disruption happens to occur just as some piece of data is being updated, you may experience data corruption.
Taking every precaution to avoid data corruption is in your best interest as a new SQL programmer. Corrupted data may be lost and never recovered, and it can lead to even more corruption inside a database. The best habits are to be as precise as possible, and in the case of select statements, this often means selecting minimal amounts of data when possible.
At this point, you should feel comfortable with SELECT and how to look into your database and see actual data rows residing inside of tables. This knowledge will prove invaluable as your SQL skills develop beyond the basics and as you begin to tackle larger, more advanced SQL projects.


 SELECT * Example

Now we want to select all the columns from the "Persons" table.
We use the following SELECT statement: 
SELECT * FROM Persons
Tip: The asterisk (*) is a quick way of selecting all columns!
The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Grants For Single Moms