The SELECT statement is used to query or retrieve data from one or more tables in a MySQL database. You can choose which columns to display, filter rows using conditions, sort the output, and even combine data from multiple tables.
In short, SELECT is the core of DQL (Data Query Language) and is used whenever you want to read data without changing it.
SELECT: Specifies which columns you want to retrieve.FROM: Tells MySQL which table to read data from.WHERE: Filters rows based on a condition (e.g., age > 20).ORDER BY: Sorts the result set (ascending or descending).*: Wildcard that selects all columns from the table.Here is the basic pattern of a SELECT query in MySQL:
-- Basic SELECT syntax to fetch specific columns
SELECT column1, column2, ... FROM table_name;
-- Select all columns from a table
SELECT * FROM table_name;
-- Filter rows using a WHERE condition
SELECT column1, column2 FROM table_name WHERE condition;
-- Sort results using ORDER BY
SELECT column1, column2 FROM table_name ORDER BY column1 ASC;
students TableAssume we have a students table with columns like id, name, and age:
-- Select specific columns from the students table
SELECT name, age FROM students;
-- Select all columns from the students table
SELECT * FROM students;
-- Select students with age greater than 20
SELECT name, age FROM students WHERE age > 20;
-- Select and sort students by age in descending order
SELECT name, age FROM students ORDER BY age DESC;
SELECT name, age FROM students; – returns only the name and age columns for every student in the table.SELECT * FROM students; – returns all the columns (every field) for every student.SELECT name, age FROM students WHERE age > 20; – shows only those students whose age is greater than 20.SELECT name, age FROM students ORDER BY age DESC; – displays students with their age, sorted from oldest to youngest.By combining SELECT, WHERE, and ORDER BY, you can quickly drill down to the exact data you need in a readable form.
WHERE to filter records instead of fetching everything and filtering in your application.ORDER BY to control the order of your results (e.g., latest records on top).SELECT * to improve performance and clarity.NULL values and test your queries with sample data.name and age columns from your own table.WHERE with conditions like >, <, =, and BETWEEN.ORDER BY to sort your results by one or more columns (e.g., ORDER BY age ASC, name ASC).SELECT DISTINCT to remove duplicate values from a specific column.