In this post, we'll cover the basic SQL syntax and operations for working with data in MySQL. We'll learn how to use the SELECT
, FROM
, WHERE
, GROUP BY
, and HAVING
clauses to query data from a MySQL database.
The SELECT
clause is used to specify the columns that you want to retrieve from a database table. For example, the following SELECT
statement retrieves the first_name
and last_name
columns from the employees
table:
SELECT first_name, last_name
FROM employees
If you want to retrieve all columns from a table, you can use the *
character in place of the column list:
SELECT *
FROM employees
The FROM
clause is used to specify the table or tables that you want to retrieve data from. For example, the following SELECT
statement retrieves data from the employees
table:
SELECT first_name, last_name
FROM employees
You can specify multiple tables in the FROM
clause by separating them with a comma:
SELECT first_name, last_name
FROM employees, departments
The WHERE
clause is used to specify conditions for retrieving data from a database table. For example, the following SELECT
statement retrieves data from the employees
table where the employee_id
is 1
:
SELECT first_name, last_name
FROM employees
WHERE employee_id = 1
You can use the AND
and OR
operators to specify multiple conditions in the WHERE
clause:
SELECT first_name, last_name
FROM employees
WHERE employee_id = 1 OR employee_id = 2
The GROUP BY
clause is used to group data from a database table. For example, the following SELECT
statement retrieves data from the employees
table and groups it by department_id
:
SELECT department_id, count(*)
FROM employees
GROUP BY department_id
The HAVING
clause is used to specify conditions for retrieving data from a database table. For example, the following SELECT
statement retrieves data from the employees
table where the department_id
is 1
:
SELECT department_id, count(*)
FROM employees
GROUP BY department_id
HAVING department_id = 1
In this post, we've covered the basic SQL syntax and operations for working with data in MySQL. We've learned how to use the SELECT
, FROM
, WHERE
, GROUP BY
, and HAVING
clauses to query data from a MySQL database.