Objectives:
- Understand the
SELECTstatement 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
SELECTstatement 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
IDandNamefromTestTable.
SELECT ID, Name FROM TestTable;
Exercise:
- Write SQL queries to retrieve:
- Only
IDandDateOfBirthfromTestTable. - Only
NameandDateOfBirthfromTestTable.
4. Using Aliases to Simplify Column Names (10 minutes)
Syntax for Aliases:
- Use the
ASkeyword 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
IDasStudentID,NameasStudentName, andDateOfBirthasDOBfromTestTable. - Use aliases for the columns to make the output clearer.
5. Practical Exercise: Basic SELECT Queries (10 minutes)
- Task:
- Create a new table named
Studentswith columnsStudentID,FirstName,LastName, andEnrollmentDate.CREATE TABLE Students ( StudentID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), EnrollmentDate DATE ); - Insert sample data into the
Studentstable: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
Studentstable. - Select only
FirstNameandLastNamefrom theStudentstable. - Use aliases to display
StudentIDasID,FirstNameasFirst, andLastNameasLast.
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
IDasStudentID,NameasStudentName, andDateOfBirthasDOBfromTestTable.
- Creating and Populating
StudentsTable:
- Exercise:
- Create the
Studentstable with the specified columns. - Insert sample data into the
Studentstable.
- Create the
- Sample Queries for
StudentsTable:
- Exercise: Execute the following queries:
- Retrieve all columns from the
Studentstable. - Select
FirstNameandLastNamefrom theStudentstable. - Use aliases to display
StudentIDasID,FirstNameasFirst, andLastNameasLast.
- Retrieve all columns from the
Homework:
- Practice Questions:
- Write SQL queries to:
- Select all columns from
Students. - Retrieve
FirstNameandEnrollmentDatefromStudents. - Use aliases to format column names for better readability.
- Select all columns from
