Mysql Select command
The SELECT command in MySQL is used to retrieve data from one or more tables in a database. The syntax for the SELECT statement is as follows:
SELECT column1, column2, ..., columnN
FROM table_name
WHERE condition
ORDER BY column_name [ASC|DESC]
LIMIT num_rows OFFSET offset_value;
The SELECT
statement retrieves one or more columns from a table in a database. The columns to be retrieved are specified by a comma-separated list of column names. To retrieve all columns from a table, use an asterisk (*) in place of the column names.
The FROM
clause specifies the name of the table from which the data is to be retrieved.
The WHERE
clause is optional and specifies a condition that must be satisfied for a row to be retrieved. The condition can include operators such as =
, !=
, <
, >
, <=
, >=
, LIKE
, IN
, BETWEEN
, and NOT
.
The ORDER BY
clause is used to sort the result set in ascending or descending order based on one or more columns. The default sorting order is ascending, but you can specify descending order by adding the DESC
keyword after the column name.
The LIMIT
clause is used to limit the number of rows returned by the query. It takes two arguments: num_rows
, which specifies the maximum number of rows to return, and offset_value
, which specifies the number of rows to skip before starting to return rows.
Examples:
To retrieve all columns from a table named employees
:
SELECT *
FROM employees;
To retrieve the first_name
and last_name
columns from the employees
table where the department
column is equal to ‘Sales’ and the salary
column is greater than 50000:
SELECT first_name, last_name
FROM employees
WHERE department = 'Sales' AND salary > 50000;
To retrieve the product_name
and unit_price
columns from the products
table sorted in descending order by unit_price
:
SELECT product_name, unit_price
FROM products
ORDER BY unit_price DESC;
To retrieve the first 10 rows from the orders
table:
SELECT *
FROM orders
LIMIT 10;
To retrieve the next 10 rows from the orders
table after skipping the first 10 rows:
SELECT *
FROM orders
LIMIT 10 OFFSET 10;
These are some of the basic examples of using the SELECT
command in MySQL to retrieve data from one or more tables in a database. The SELECT
command can be combined with other commands such as JOIN
, GROUP BY
, and HAVING
to perform more complex queries.