To retrieve data from a table, you can use the SELECT statement. The SELECT statement specifies the columns to be retrieved from the table.
Syntax
Example
Here we have a table called users with the following columns: id , user_name , age , and city .
users
id
user_name
age
city
1
Alice
25
New York
2
Bob
30
London
3
Carol
35
Paris
To retrieve the user_name column from the users table, you can use the following SQL statement:
This will return the following result:
user_name
Alice
Bob
Carol
Exercise 1.1
Run the following code to select the user_name column from the users table.
id
user_name
age
city
1
Alice
25
New York
2
Bob
30
London
3
Carol
35
Paris
Interactive
Select user_name
Exercise 1.2
Write a SQL statement to select the city column from the users table.
id
user_name
age
city
1
Alice
25
New York
2
Bob
30
London
3
Carol
35
Paris
Interactive
Select city
Exercise 1.3
Write a SQL statement to select the age column from the users table.
id
user_name
age
city
1
Alice
25
New York
2
Bob
30
London
3
Carol
35
Paris
Interactive
select age
Quiz
Loading...
Loading...
Selecting a Column as an Alias
What is an alias? An alias is a temporary name given to a column or a table in a SQL query. You can use aliases to make the output of a query more readable or to shorten the column or table names.
To select a column as an alias, you can use the AS keyword followed by the alias name. For example:
Syntax
Example
To select the user_name column from the users table and give it an alias name , you can use the following SQL statement:
This will return the following result:
name
Alice
Bob
Carol
Exercise 1.4
Run the following SQL statement to select the user_name column from the users table and give it an alias called name .
id
user_name
age
city
1
Alice
25
New York
2
Bob
30
London
3
Carol
35
Paris
Interactive
select user_name as name
Exercise 1.5
Write a SQL statement to select the city column from the users table and give it an alias location .
id
user_name
age
city
1
Alice
25
New York
2
Bob
30
London
3
Carol
35
Paris
Interactive
select city as location
Selecting Multiple Columns
To select multiple columns we separate the column names with commas.
Syntax
Example
If we need to select age and location from the users table, we would write:
Exercise 1.6
Write a SQL statement to select the city and age columns from the users .
id
user_name
age
city
1
Alice
25
New York
2
Bob
30
London
3
Carol
35
Paris
Interactive
select city and age
Selecting All Columns
It can be too much effort to type in all columns, and sometimes we may not know what all the columns are. In this case, we can use the * symbol to select all columns.