MySQL : SELECT Statement

In MySQL, the SELECT statement is used to retrieve data from one or more tables in a database. It allows you to specify which columns you want to retrieve, as well as any conditions or criteria for selecting rows. Here's the basic syntax of the SELECT statement:


SELECT column1, column2, ...
FROM table_name;

 

Where:

  • column1, column2, etc. are the names of the columns you want to retrieve.
  • table_name is the name of the table from which you want to retrieve data.

You can also use the * wildcard to select all columns:


SELECT * FROM table_name;
 

Here are some more advanced features of the SELECT statement:

1. Aliases: You can use aliases to give columns or tables different names in the result set. This is useful for readability and for renaming calculated columns.


SELECT column1 AS alias_name FROM table_name;
 

2. Filtering Rows: You can use the WHERE clause to specify conditions that must be met for rows to be included in the result set.


SELECT column1, column2 FROM table_name WHERE condition;
 

3. Sorting Results: You can use the ORDER BY clause to sort the result set based on one or more columns, either in ascending (ASC) or descending (DESC) order.


SELECT column1, column2 FROM table_name ORDER BY column1 ASC;
 

4. Limiting Results: You can use the LIMIT clause to limit the number of rows returned by the query.


SELECT column1, column2 FROM table_name LIMIT 10;
 

5. Aggregate Functions: MySQL provides several aggregate functions like COUNT(), SUM(), AVG(), MIN(), and MAX() that allow you to perform calculations on groups of rows and return a single result.


SELECT COUNT(column1) FROM table_name;
 

6. Joins: You can use JOIN clauses to combine rows from two or more tables based on a related column between them.


SELECT table1.column1, table2.column2 
FROM table1
JOIN table2 ON table1.id = table2.id;

 

These are just some of the many features of the SELECT statement in MySQL. It's a powerful tool for retrieving and manipulating data in a database.