MySQL Select
The SELECT statement is the primary way to read data from a MySQL table, letting you choose exactly which columns and rows to retrieve.
The SELECT Statement
SELECT is used to query data from one or more tables. Its basic form is SELECT column1, column2 FROM table_name;, which returns the requested columns for every row in the table. SELECT never changes stored data, so it is always safe to run.
You can retrieve every column in a table using the asterisk wildcard, as in SELECT * FROM table_name;. This is convenient while exploring data, but in application code it is usually better to name columns explicitly so the query keeps working even if the table's structure changes later.
Selecting Specific Columns
- Select every column with the * wildcard
- Select only the columns you need by naming them
- Rename output columns on the fly with the AS alias keyword
- Remove duplicate rows from the result using DISTINCT
- Combine SELECT with WHERE, ORDER BY, and LIMIT to shape the result further
Removing Duplicates with DISTINCT
When a column contains repeated values across many rows, such as a department name shared by several employees, SELECT DISTINCT returns each unique value only once instead of once per row.
Query Examples
Select every column from a table
SELECT * FROM employees;Select specific columns
SELECT name, department FROM employees;Select unique department names
SELECT DISTINCT department FROM employees;Exercise: MySQL Select
What does `SELECT * FROM customers;` return?