Codeskill

Learn to code, step by step

Efficient Data Retrieval: Introduction to SELECT Queries

SELECT queries in MySQL matters once your pages get past the basics. How to fetch data, filter it, sort it, and summarise it.

What SELECT does

A SELECT query asks the database for data. You choose which columns, which rows, and how the results are ordered.

The basic SELECT query

Fetch everything from a customers table:

SELECT * FROM customers;

* means all columns. Simple, but often more than you need.

Selecting specific columns

Just names and emails:

SELECT name, email FROM customers;

Only those two columns come back.

The WHERE clause

Filter rows. Customers who joined after 1 January 2022:

SELECT * FROM customers WHERE join_date > '2022-01-01';

WHERE is how you narrow results to the rows you actually want.

Sorting results with ORDER BY

Sort by join date, newest first:

SELECT * FROM customers ORDER BY join_date DESC;

DESC is descending. Use ASC for ascending, or leave it out (ascending is the default).

Combining filters and sorting

Customers who joined in 2022, sorted by name:

SELECT * FROM customers 
WHERE join_date BETWEEN '2022-01-01' AND '2022-12-31' 
ORDER BY name;

WHERE filters, ORDER BY sorts. You can combine both in one query.

Limiting results with LIMIT

Only the first 10 rows:

SELECT * FROM customers LIMIT 10;

Useful on large tables when you only need a sample.

Fetching distinct values

Unique cities from the customers table:

SELECT DISTINCT city FROM customers;

DISTINCT removes duplicates from the result.

Aggregation functions: COUNT, MAX, MIN, AVG, SUM

Count how many customers you have:

SELECT COUNT(*) FROM customers;

MAX, MIN, AVG, and SUM work the same way – they summarise a column rather than returning individual rows.

Best practices for writing SELECT queries

  1. Be specific: fetch only the columns you need instead of SELECT *.
  2. Use aliases for readability: e.g. SELECT COUNT(*) AS total_customers FROM customers;.
  3. Filter early: a WHERE clause reduces the work the database has to do.

SELECT is the query you will write most often. Try combining clauses – WHERE, ORDER BY, LIMIT, and aggregation functions – until the patterns stick.

PreviousMastering CRUD Operations: Create, Read, Update, Delete in MySQL