SELECT, DISTINCT, and Aliases
These commands are commonly used together to select data from a table:
SELECT: select data from a table, which is returned in a result table (the result-set)DISTINCT: select only unique values from a field containing duplicate valuesAS: give a temporary name (alias) for a selected column, often to make the output more readable
Syntax
Select all columns in the table:
Select specific columns in the table:
Select only unique values of a column:
Select a column and temporarily rename it in the output:
SELECT <column_name1> AS <temporary_name1>, <column_name2> AS <temporary_name2>, ...
FROM <table_name>;Examples
#1
Select all records in the table:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 5021 | Mexico |
| 3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 5023 | Mexico |
| 4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
| 5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
| 6 | Blauer See Delikatessen | Hanna Moos | Forsterstr. 57 | Mannheim | 68306 | Germany |
| 7 | Blondel père et fils | Frédérique Citeaux | 24, place Kléber | Strasbourg | 67000 | France |
| 8 | Bólido Comidas preparadas | Martín Sommer | C/ Araquil, 67 | Madrid | 28023 | Spain |
| 9 | Bon app’ | Laurence Lebihans | 12, rue des Bouchers | Marseille | 13008 | France |
| 10 | Bottom-Dollar Marketse | Elizabeth Lincoln | 23 Tsawassen Blvd. | Tsawassen | T2F 8M4 | Canada |
#2
Select the “City” column:
| City |
|---|
| Berlin |
| México D.F. |
| México D.F. |
| London |
| Luleå |
| Mannheim |
| Strasbourg |
| Madrid |
| Marseille |
| Tsawassen |
#3
Select all unique countries in the table:
| Country |
|---|
| Germany |
| Mexico |
| UK |
| Sweden |
| France |
| Spain |
| Canada |
| Argentina |
| Switzerland |
| Brazil |
#4
Select the ID, name and postal code of customers and temporarily rename them as “IDs”, “Name” and “Postal_code”:
| IDs | Name | Postal_code |
|---|---|---|
| 1 | Alfreds Futterkiste | 12209 |
| 2 | Ana Trujillo Emparedados y helados | 5021 |
| 3 | Antonio Moreno Taquería | 5023 |
| 4 | Around the Horn | WA1 1DP |
| 5 | Berglunds snabbköp | S-958 22 |
| 6 | Blauer See Delikatessen | 68306 |
| 7 | Blondel père et fils | 67000 |
| 8 | Bólido Comidas preparadas | 28023 |
| 9 | Bon app’ | 13008 |
| 10 | Bottom-Dollar Marketse | T2F 8M4 |
References
Links to the tutorials:
- SQL Select: https://www.w3schools.com/sql/sql_select.asp
- SQL Select Distinct: https://www.w3schools.com/sql/sql_distinct.asp
- SQL Alias: https://www.w3schools.com/sql/sql_alias.asp