How to Use the SELECT Statement in MySQL

08/04/2021

Contents

In this article, you will learn how to use the SELECT statement in MySQL.

Using the SELECT statement in MySQL

The SELECT statement is one of the most important SQL commands used to retrieve data from a MySQL database.

Connect to MySQL

Before we can use the SELECT statement, we need to connect to the MySQL server using a client like MySQL Workbench, phpMyAdmin or through command line.

Syntax of the SELECT statement

The basic syntax of the SELECT statement is as follows:

SELECT column_name(s) FROM table_name WHERE condition;

The column_name(s) is the name of the column(s) you want to retrieve data from. If you want to retrieve data from all columns, use the * symbol instead. The table_name is the name of the table you want to retrieve data from. The WHERE clause is optional and is used to specify the condition that must be met in order for the rows to be retrieved.

Example

Retrieving data from a single column
SELECT first_name FROM users;

This will retrieve the data from the first_name column in the users table.

Retrieving data from multiple columns
SELECT first_name, last_name FROM users;

This will retrieve the data from the first_name and last_name columns in the users table.

Retrieving data from all columns
SELECT * FROM users;

This will retrieve the data from all columns in the users table.

Retrieving data with a condition
SELECT first_name, last_name FROM users WHERE gender = 'female';

This will retrieve the data from the first_name and last_name columns in the users table where the gender is ‘female’.

Sorting data

To sort the retrieved data, use the ORDER BY clause. The ORDER BY clause sorts the data in ascending or descending order based on the specified column(s).

SELECT column_name(s) FROM table_name ORDER BY column_name ASC/DESC;

The ASC keyword sorts the data in ascending order (default) and the DESC keyword sorts the data in descending order.

Example

SELECT first_name, last_name FROM users ORDER BY last_name ASC;

This will retrieve the data from the first_name and last_name columns in the users table sorted in ascending order by the last_name column.

Limiting data

To limit the number of rows retrieved, use the LIMIT clause.

SELECT column_name(s) FROM table_name LIMIT number;

The number is the maximum number of rows to be retrieved.

Example

SELECT first_name, last_name FROM users LIMIT 10;

This will retrieve the data from the first_name and last_name columns in the users table with a maximum of 10 rows.