The MySQL SELECT
statement is used to retrieve data from one or more tables. This statement is essential for querying the database and extracting the desired information.
SELECT column1, column2, ...
FROM table_name
[WHERE condition]
[ORDER BY column [ASC|DESC]]
[LIMIT number];
The SELECT
statement has the following components:
column1, column2, ...
: The columns to be retrieved.table_name
: The name of the table from which to retrieve the data.[WHERE condition]
: An optional condition to filter the rows.[ORDER BY column [ASC|DESC]]
: An optional clause to sort the results.[LIMIT number]
: An optional clause to limit the number of rows returned.Let's look at some examples of the MySQL SELECT
statement:
USE mydatabase;
This query sets the context to the database named mydatabase
.
Create a table to work with:
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);
This query creates a table named employees
with columns for id
, first_name
, last_name
, and email
.
Insert some initial rows into the table:
INSERT INTO employees (first_name, last_name, email)
VALUES ('John', 'Doe', 'john.doe@example.com'),
('Jane', 'Smith', 'jane.smith@example.com');
This query inserts two rows into the employees
table.
Select all rows from the table:
SELECT *
FROM employees;
This query retrieves all columns from all rows in the employees
table.
Select specific columns from the table:
SELECT first_name, last_name FROM employees;
This query retrieves the first_name
and last_name
columns from all rows in the employees
table.
Select rows based on a condition:
SELECT *
FROM employees
WHERE last_name = 'Doe';
This query retrieves all columns from rows in the employees
table where the last_name
is 'Doe'.
Select rows and sort the results:
SELECT *
FROM employees ORDER BY first_name ASC;
This query retrieves all columns from all rows in the employees
table, sorted by first_name
in ascending order.
Select a limited number of rows:
SELECT *
FROM employees LIMIT 1;
This query retrieves all columns from the first row in the employees
table.
The MySQL SELECT
statement is a powerful tool for retrieving data from tables. Understanding how to use the SELECT
statement is essential for effective data querying and analysis in MySQL.