Data inserted or updated can be accessed with the SELECT statement of DML sublanguage of SQL. In this tutorial you will learn to use SELECT Statement to Access Data in SQL.
Data can be fetched from more than one table. But here in this tutorial we will begin with the basic SELECT Statement. In later tutorials you will learn about its complex versions with additional clauses.
Syntax of SELECT Statement to Access Data
SELECT [DISTINCT] *|Column Name1 [alias name],Column Name2 [alias name],…
FROM table name
[WHERE condition expression]
- SELECT, DISTINCT, FROM, WHERE are the keywords
- *|Column Name1, Column Name2,… – defines the columns whose values must be displayed in the output of SELECT query statement. If you include * you will get data of all the columns of the table. You cannot use * and columns names together. Chose one of these two.
- table name is the name of the table from which you want to access data.
- Condition expression in the WHERE clause applies filter on the data being fetched from the table
- alias name is optional. It is used to change the column heading of data being displayed
Examples of SELECT Statement
Using * to Select all Columns
select * from Salestbl;
SPID | SPNAME | SPCITY | SPCOMM |
1001 | Bob Mathews | Nashville | .1 |
1002 | Cathy Mills | San Diego | .1 |
1003 | Alex Rode | New York | .5 |
Using Column Names to Select Data from Specific Columns
select SPCITY, SPCOMM from Salestbl;
SPCITY | SPCOMM |
Nashville | .1 |
San Diego | .1 |
New York | .5 |
Defining Column Aliases to Change Column Headings
If you wish to give a single word alias to column in SELECT Statement, you can simply write the word after column name as given in example below
select SPID SalePerID, SPNAME SalePerName, SPCITY SalePerCIty from Salestbl;
SALEPERID | SALEPERNAME | SALEPERCITY |
1001 | Bob Mathews | Nashville |
1002 | Cathy Mills | San Diego |
1003 | Alex Rode | New York |
If you wish to give a multiple word alias with blank spaces in between the words, you have to use double quotes to enclose the alias(“”) after column name in SELECT Statement. See the example below
select SPID "Salesperson ID", SPNAME "Salesperson Name", SPCITY "Salesperson City" from Salestbl;
Salesperson ID | Salesperson Name | Salesperson City |
1001 | Bob Mathews | Nashville |
1002 | Cathy Mills | San Diego |
1003 | Alex Rode | New York |
Using Where Clause to Filter Data
select * from Salestbl where SPComm=0.1;
SPID | SPNAME | SPCITY | SPCOMM |
1001 | Bob Mathews | Nashville | .1 |
1002 | Cathy Mills | San Diego | .1 |
Points to remember
To use SELECT Statement to Access Data from a table remember following things
- Selecting data from a table or set of tables do not change the data in table.
- Using an alias name does not change the name of the column in table definition. It just changes the heading of the data.
- Multiple conditions in WHERE clause can be added with Logical Operators AND, OR and NOT.