SELECT Statement
SELECT statements are used to filter data from a table. List results are stored in a result table (called Result-set)
Grammar
SELECT column_name (s) From table_name |
Note: The SELECT declaration is case-insensitive. Select and select are the same.
--------------------------------------------------------------------------------
SQL SELECT Sample
Filter the contents of the column named "LastName" and "FirstName" in a data table named "Persons" with a SELECT statement as follows:
SELECT Lastname,firstname from Persons |
Data Sheet "Persons":
LastName |
FirstName |
Address |
| City
Hansen |
Ola |
TIMOTEIVN 10 |
Sandnes |
Svendson |
Tove |
BORGVN 23 |
Sandnes |
Pettersen |
Kari |
STORGT 20 |
Stavanger |
Results:
lastname |
firstname |
Hansen |
Ola |
svendson |
Tove |
Pettersen |
Kari |
--------------------------------------------------------------------------------
The Result Set
SQL query results are stored in result set, and most database systems allow the result set to collaborate with the programming function to navigate, like moving to the first record, getting the contents of the record, moving to the next record, and so on.
These programming functions are not part of this guide, and learning to use function commands to access data is available in our ADO Guide
--------------------------------------------------------------------------------
Semicolon after the SQL statement?
Semicolons are the standard way to separate each SQL statement in the database system so that multiple statements are executed in the same command that is issued to the server.
Is it necessary for some SQL guides to end each SQL statement with a semicolon? We don't have to add semicolons to each SQL when we use MS Access and SQL Server 2000, but some database systems force you to use it.
--------------------------------------------------------------------------------
SELECT DISTINCT statement
The DISTINCT keyword is used to return different values.
The SELECT statement returns information from a column in the table. But what if we want to choose a project that does not duplicate?
With SQL, all we need to do is add a distinct keyword to select.
Grammar:
SELECT DISTINCT column_name (s) From table_name |
--------------------------------------------------------------------------------
Using the DISTINCT keyword
As shown below, we use an SQL statement to select all values from a column named "Company":
SELECT Company from Orders |
"Orders" table
| Company
OrderNumber |
Sega |
3412 |
W3Schools |
2312 |
Trio |
4678 |
W3Schools |
6798 |
return results
Company |
Sega |
W3Schools |
Trio |
W3Schools |
Note "W3Schools" is listed two times in Result-set.
We use Select DISTINCT to select only the values that are not duplicates from the column named "Company", as follows:
SELECT DISTINCT Company from Orders |
return Result:
Company |
Sega |
W3Schools |
Trio |
Now "W3Schools" is listed only once in Result-set.
SQL Guide-select statements