Objectives:
- Understand the
SELECT
statement syntax - Retrieve all columns and specific columns from a table
- Use aliases to simplify column names
1. Introduction to SELECT Statement (10 minutes)
Syntax Overview:
- The basic syntax of the
SELECT
statement is:
SELECT column1, column2, ...
FROM table_name;
- Example:
SELECT * FROM TestTable;
*
retrieves all columns from the table.
2. Retrieving All Columns (5 minutes)
- Using
*
to Select All Columns:
SELECT * FROM TestTable;
- Exercise:
- Write a query to select all columns from the
TestTable
.
3. Retrieving Specific Columns (10 minutes)
Syntax for Selecting Specific Columns:
- Example: Select
ID
andName
fromTestTable
.
SELECT ID, Name FROM TestTable;
Exercise:
- Write SQL queries to retrieve:
- Only
ID
andDateOfBirth
fromTestTable
. - Only
Name
andDateOfBirth
fromTestTable
.
4. Using Aliases to Simplify Column Names (10 minutes)
Syntax for Aliases:
- Use the
AS
keyword to rename columns:
SELECT ID AS StudentID, Name AS StudentName FROM TestTable;
- Example:
SELECT ID AS StudentID, Name AS StudentName, DateOfBirth AS DOB FROM TestTable;
Exercise:
- Write SQL queries to:
- Select
ID
asStudentID
,Name
asStudentName
, andDateOfBirth
asDOB
fromTestTable
. - Use aliases for the columns to make the output clearer.
5. Practical Exercise: Basic SELECT Queries (10 minutes)
- Task:
- Create a new table named
Students
with columnsStudentID
,FirstName
,LastName
, andEnrollmentDate
.CREATE TABLE Students ( StudentID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), EnrollmentDate DATE );
- Insert sample data into the
Students
table:INSERT INTO Students (StudentID, FirstName, LastName, EnrollmentDate) VALUES (1, 'John', 'Doe', '2024-01-15'), (2, 'Jane', 'Smith', '2024-01-16'), (3, 'Emily', 'Johnson', '2024-01-17');
- Exercises:
- Retrieve all columns from the
Students
table. - Select only
FirstName
andLastName
from theStudents
table. - Use aliases to display
StudentID
asID
,FirstName
asFirst
, andLastName
asLast
.
Exercises
- Basic SELECT Queries:
- Exercise: Write SQL queries to:
- Select all columns from
TestTable
. - Select specific columns:
ID
,Name
,DateOfBirth
.
- Select all columns from
- Using Aliases:
- Exercise: Select
ID
asStudentID
,Name
asStudentName
, andDateOfBirth
asDOB
fromTestTable
.
- Creating and Populating
Students
Table:
- Exercise:
- Create the
Students
table with the specified columns. - Insert sample data into the
Students
table.
- Create the
- Sample Queries for
Students
Table:
- Exercise: Execute the following queries:
- Retrieve all columns from the
Students
table. - Select
FirstName
andLastName
from theStudents
table. - Use aliases to display
StudentID
asID
,FirstName
asFirst
, andLastName
asLast
.
- Retrieve all columns from the
Homework:
- Practice Questions:
- Write SQL queries to:
- Select all columns from
Students
. - Retrieve
FirstName
andEnrollmentDate
fromStudents
. - Use aliases to format column names for better readability.
- Select all columns from