The MySQL SELECT Statement
Continuing with the MySQL stories...
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
Syntax:
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, … are the field names of the table you want to select data from. If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Demo Database
Below is a selection from the “Employees” table in the Northwind sample database:
SELECT Columns Example
The following SQL statement selects the “Last Name”, “City” columns from the “Employees” table:
Example
select Last Name,City from Employees;
SELECT * Example
The following SQL statement selects ALL the columns from the “Employees” table:
Example
SELECT * FROM Employees;
The MySQL SELECT DISTINCT Statement
The SELECT STATEMENT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates) values from the “City” column in the “Employees” table:
Example
SELECT City FROM Employees;
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the “City” column in the “Employees” table:
Example
SELECT DISTINCT City FROM Employees;
The following SQL statement counts and returns the number of different (distinct) cities in the “Employees” table:
Example
SELECT COUNT(DISTINCT City) FROM Employees;
No comments:
Post a Comment