Retrieving Data with SELECT
SQL Basics Course
Topic 8: Retrieving Data with SELECT
Learn how to retrieve and display data from database tables using SQL queries.
Learning Objectives
- Use the SELECT statement
- Retrieve specific columns
- Retrieve all columns
- Use DISTINCT values
- Create aliases using AS
- Limit returned records
What is SELECT?
The SELECT statement is used to retrieve data from a database table.
SELECT * FROM students;
This retrieves every column and every row from the students table.
Selecting Specific Columns
SELECT name, city
FROM students;
Only the selected columns will be returned.
| Name | City |
|---|---|
| Rahul | Delhi |
| Amit | Mumbai |
Using SELECT *
SELECT *
FROM students;
The asterisk (*) means all columns.
| ID | Name | City |
|---|---|---|
| 1 | Rahul | Delhi |
| 2 | Amit | Mumbai |
DISTINCT Keyword
SELECT DISTINCT city
FROM students;
DISTINCT removes duplicate values.
Aliases Using AS
SELECT name AS Student_Name
FROM students;
Aliases make column names more readable.
LIMIT Clause
SELECT *
FROM students
LIMIT 5;
Returns only the first 5 records.
TOP Clause (SQL Server)
SELECT TOP 5 *
FROM students;
Used in Microsoft SQL Server to limit results.
FETCH FIRST Clause
SELECT *
FROM students
FETCH FIRST 5 ROWS ONLY;
Used in some SQL systems to restrict output.
Real World Example
SELECT name, salary
FROM employees;
| Name | Salary |
|---|---|
| John | 50000 |
| Sarah | 45000 |
Best Practices
- Select only required columns.
- Avoid using SELECT * in large applications.
- Use aliases for better readability.
- Limit results when testing queries.
- Write clear and readable SQL.
Practice Exercises
- Display all student records.
- Display only student names.
- Show unique cities.
- Create aliases for column names.
- Display only the first three records.
Quiz
1. Which statement retrieves data?
2. What does * mean in SELECT *?
3. What does DISTINCT do?
4. Why are aliases useful?
5. Which clause limits rows in MySQL?
Summary
- SELECT retrieves data from tables.
- You can retrieve specific columns or all columns.
- DISTINCT removes duplicate values.
- Aliases improve readability.
- LIMIT, TOP and FETCH restrict returned rows.