The SELECT
statement is used to retrieve data from a MySQL database.
Here’s the basic syntax:
SELECT column1, column2, ... FROM table_name;
This statement selects data from one or more columns (column1
, column2
, etc.) in a specified table (table_name
). If you want to select all columns in the table, you can use the asterisk (*
) wildcard character instead of listing the column names explicitly.
For example, to select all columns from a table called customers
, you can use the following statement:
SELECT * FROM customers;
This will return all rows and columns from the customers
table.
You can also add conditions to the SELECT
statement to filter the results based on specific criteria. For example, to select only the customers who have a country
value of USA
, you can use the WHERE
clause:
SELECT * FROM customers WHERE country = 'USA';
This will return all rows and columns from the customers
table where the country
column equals USA
.
You can also use the ORDER BY
clause to sort the results based on one or more columns. For example, to sort the customers
table by the last_name
column in ascending order, you can use the following statement:
SELECT * FROM customers ORDER BY last_name ASC;
This will return all rows and columns from the customers
table sorted by the last_name
column in ascending order.
Finally, you can use the LIMIT
clause to limit the number of rows returned by the SELECT
statement. For example, to select only the first 10 rows from the customers
table, you can use the following statement:
SELECT * FROM customers LIMIT 10;
This will return the first 10 rows and all columns from the customers
table.
MySQL SELECT DISTINCT Statement
In MySQL, the SELECT DISTINCT
statement is used to retrieve unique values from a table. It allows you to select only distinct (unique) values from a column or a combination of columns.
The basic syntax of the SELECT DISTINCT
statement is as follows:
SELECT DISTINCT column1, column2, ... FROM table_name;
In this statement, column1
, column2
, and so on are the names of the columns you want to retrieve unique values from, and table_name
is the name of the table you want to retrieve data from.
For example, suppose you have a table named “employees” with columns named “id”, “name”, “department”, and “salary”. You can use the SELECT DISTINCT
statement to retrieve the unique department names from the “employees” table as follows:
SELECT DISTINCT department FROM employees;
This will return a list of unique department names from the “employees” table.
The SELECT DISTINCT
statement is a powerful tool for retrieving unique values from tables in MySQL and is useful in a wide range of database applications.
Overall, the SELECT
statement is a powerful tool that allows you to retrieve and manipulate data from MySQL databases in a flexible and precise way.