How to Use the SELECT Statement to Query Data in MySQL

How to Use the SELECT Statement to Query Data in MySQL

MySQL is a commonly used database management system for large volumes of data. A core function when interacting with any database is being able to query and retrieve data. In MySQL, this is primarily done with the SELECT statement. This article will guide you through the fundamentals of this statement along with practical examples.  

Basics of the SELECT Statement

The SELECT statement is used to fetch data from a database. The basic syntax is: 

SELECT column1_name, column2_name, …
FROM table_name;

The column or table names are not case sensitive, but it is important to remember the semicolon at the end of the request. If you want to select all of the columns in a given table, you can replace the column name list with an asterisk instead:  

SELECT * FROM table_name;

Renaming Columns with Aliases

You can temporarily rename columns when querying a database to make them more readable using the AS keyword after the column name, then the alias in quotes. For example:  

SELECT first_name AS ‘First Name’, last_name AS ‘Last Name’
FROM employee_data;

Filtering With a WHERE Clause

If you only want to pull data that meets certain conditions, you can add a WHERE clause after your FROM clause. It is important to make sure whatever Boolean requirement you set matches the data type available in that column. You do not need to include a column you are filtering by in the list of columns you are selecting.  

SELECT first_name, last_name 
FROM employee_data
WHERE department = ‘Finance’;

You can also add logical operators into your WHERE clause to filter by more than one condition.  

SELECT first_name, last_name 
FROM employee_data
WHERE department = ‘Finance’ AND salary > 75000;

Sorting the Output with ORDER BY

If you want your output data to be sorted by a particular column, you can specify this in the ORDER BY clause. You can also specify in you want to sort ascending by adding ASC after your column name. Otherwise, the data will sort descending. Sorting works for numeric and character column types and, again, you do not need to select the column you order by.  

SELECT first_name, last_name 
FROM employee_data
ORDER BY salary ASC;

Applying Aggregate Functions

In your SELECT clause, you can also select the result of a calculation on a set of values to summarize a particular column. Common functions include COUNT, SUM, AVG, MIN, and MAX.  

SELECT AVG(salary)
FROM employee_data;

Conclusion

There are many ways the SELECT statement can be used to effectively query data in MySQL. These are just a handful of some of the most common implementations of the SELECT statement, but understanding the fundamental clauses and functions allows you to effectively retrieve, filter, sort, and manipulate data.

Leave a Reply

Your email address will not be published. Required fields are marked *