Retrieving Columns of Data
The SELECT statement is the SQL command used to retrieve data from a table. It is the most common SQL statement, and almost every query begins with it. You tell SELECT which columns you want and which table to read them from, and it returns the matching rows.
Questions you may have include:
- How do you retrieve specific columns?
- How do you retrieve every column?
- How do you remove duplicates or rename a column?
Selecting specific columns
List the columns you want, separated by commas, then name the table after the keyword FROM:
SELECT first_name, last_name FROM customers;
This returns just the first and last name of every customer, in the order the rows happen to be stored.
Selecting all columns
To return every column without listing them, use the asterisk (*):
SELECT * FROM customers;
This is handy when exploring a table, but naming the columns you actually need is clearer and more efficient in real applications.
Removing duplicate values
Add DISTINCT to return only unique values. For example, to list the states your customers live in without repeats:
SELECT DISTINCT state FROM customers;
Renaming a column in the results
The AS keyword gives a column a friendlier name in the output (an alias). It changes only how the result is labeled, not the table itself:
SELECT last_name AS surname FROM customers;
Summary
The SELECT statement retrieves data from a table. List specific columns separated by commas, or use * for all of them. DISTINCT removes duplicate values, and AS renames a column in the output. SELECT is the foundation for the sorting and filtering covered in the next lessons.
