- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL SELECT
The SELECT statement is the bread and butter of database interaction. It represents the "Read" operation in the CRUD (Create, Read, Update, Delete) acronym. Whether you are building a dashboard, a mobile app, or a simple report, SELECT is how you ask the database for specific information.
While the statement starts simple, its power lies in its flexibility. You can combine it with various clauses to filter out noise, sort results for user interfaces, or even perform complex calculations across millions of rows.
SELECT and FROM are not case-sensitive in most databases (MySQL, PostgreSQL, SQL Server), writing them in uppercase is a common convention that makes your queries much easier to read and maintain.
Basic Syntax of SELECT
At its core, every SELECT query requires two things: what you want to see (columns) and where it is coming from (the table).
SELECT column1, column2, ...
FROM table_name;
column1, column2, ...: The specific fields you want to retrieve (e.g.,email,username).table_name: The name of the table stored in your database (e.g.,users).
SELECT *. This reduces the amount of data transferred over the network and prevents your application from breaking if someone adds a new column to the table later.
Key Features of the SELECT Statement
1. Selecting All Columns
If you are exploring a new database and want to see what a table looks like, you can use the asterisk (*) wildcard to grab everything.
SELECT * FROM employees;
This retrieves every column and every row from the employees table. It's great for quick debugging but risky in production environments.
SELECT * on tables with many columns or "Large Objects" (like BLOBs or long text fields) can significantly slow down your application and put unnecessary load on the database server.
2. Selecting Specific Columns
By listing specific columns, you create a cleaner and more efficient result set.
SELECT first_name, last_name FROM employees;
In a real-world scenario, if you are building a "Staff Directory" page, you probably only need the name and perhaps an email, rather than the employee's home address or social security number.
3. Using WHERE Clause
Without a filter, SELECT returns every row. The WHERE clause allows you to pinpoint exactly which records you need based on specific criteria.
SELECT * FROM employees WHERE department = 'Sales';
You can use operators like >, <, >=, <=, <> (not equal), and LIKE (for pattern matching) within this clause.
WHERE department = Sales will cause an error; it must be 'Sales'. Numerical values do not require quotes.
4. Using ORDER BY
Data in a database is stored in an "unordered" fashion. To ensure your UI displays items in a logical order, use ORDER BY.
SELECT * FROM employees ORDER BY last_name ASC;
You can use ASC for ascending (A-Z, 1-10) or DESC for descending (Z-A, 10-1). You can also sort by multiple columns, such as ORDER BY department ASC, last_name ASC.
5. Using LIMIT
When dealing with millions of rows, you rarely want to fetch them all at once. The LIMIT clause (or TOP in SQL Server) restricts the number of rows returned.
SELECT * FROM employees LIMIT 5;
This is commonly used for "Pagination" (e.g., showing 10 results per page) or for simply finding the "Top 10" highest-paid employees.
6. Using DISTINCT
Sometimes you only want to know the unique values in a column. DISTINCT filters out the duplicates.
SELECT DISTINCT department FROM employees;
If you have 500 employees but only 5 departments, this query will return just those 5 unique department names.
7. Using Aggregate Functions
SQL isn't just for fetching rows; it's for answering questions. Aggregate functions perform calculations on multiple rows and return a single value.
SELECT COUNT(*) FROM employees WHERE department = 'Sales';
Other common aggregates include SUM() (total), AVG() (average), MAX() (highest), and MIN() (lowest).
8. Using JOIN
In a relational database, data is often split across multiple tables to avoid redundancy. JOIN allows you to combine them back together in a single view.
SELECT employees.first_name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.department_id;
FROM employees AS e JOIN departments AS d ON e.dept_id = d.id.
Example Queries
1. Retrieve All Employees in the 'HR' Department
Use this when you need to populate a list of staff for a specific manager.
SELECT first_name, last_name, email
FROM employees
WHERE department = 'HR';
2. Get the Total Number of Employees
Useful for high-level "Admin Dashboard" statistics. We use AS to give the result a readable name.
SELECT COUNT(*) AS total_employees FROM employees;
3. Get Employee Names and Their Departments, Sorted by Department
This generates an organized list, grouping all employees of the same department together visually.
SELECT first_name, last_name, department
FROM employees
ORDER BY department ASC, last_name ASC;
4. Find Employees with a Salary Greater Than 50,000
Filtering by numeric ranges is a standard task for financial reporting.
SELECT first_name, last_name, salary
FROM employees
WHERE salary > 50000;
5. Get the Average Salary in Each Department
When using AVG alongside a column like department, you must use GROUP BY to tell the database how to categorize the math.
SELECT department, AVG(salary) AS average_salary
FROM employees
GROUP BY department;
Summary
The SELECT statement is the most versatile tool in a developer's SQL toolkit. By mastering basic retrieval, filtering with WHERE, and organizing with ORDER BY, you can handle the majority of data-fetching needs for any application. As you grow, you'll find that combining these basics with JOINs and Aggregates allows you to extract powerful insights from your data with very little code.