Lab 5: Advanced SQL Statements and Functions Objective: Dive deeper into SQL with advanced statements and functions to manipulate and retrieve data effectively.
SQL UPDATE Statement The UPDATE statement modifies existing records in a table. Always ensure to use the WHERE clause to specify which record(s) to update.
Example: SQL UPDATE UPDATE Courses SET Credits = 4 WHERE CourseName = 'Algorithms';
Exercise: SQL UPDATE Modify the 'CourseName' of the course with ID 101 to 'Advanced Databases'.
SQL DELETE Statement The DELETE statement removes one or more records from a table. Be cautious, and always use the WHERE clause to avoid deleting all records.
Example: SQL DELETE DELETE FROM Students WHERE Age < 18;
Exercise: SQL DELETE Remove all courses from the 'Courses' table that have less than 3 credits.
SQL SELECT TOP Statement The SELECT TOP clause is used to specify the number of top records to return from a table.
Example: SQL SELECT TOP SELECT TOP 3 * FROM Students ORDER BY Age DESC;
Exercise: SQL SELECT TOP Retrieve the top 5 courses from the 'Courses' table with the highest credits.
SQL ORDER BY Statement The ORDER BY statement is used to sort the result set based on one or more columns.
Example: SQL ORDER BY SELECT * FROM Students ORDER BY Name ASC;
Exercise: SQL ORDER BY Retrieve all records from the 'Courses' table ordered by 'CourseName' in descending order.
SQL Aliases Aliases are temporary names given to table or column for the purpose of a specific SQL query.
Example: SQL Aliases SELECT CourseID AS ID, CourseName AS Course FROM Courses;
Exercise: SQL Aliases Rename 'ID' column to 'StudentID' and 'Name' column to 'StudentName' in the 'Students' table for your query result.
SQL MIN() and MAX() Functions MIN() function returns the smallest value of the selected column. MAX() function returns the largest value of the selected column.
Example: MIN() and MAX() SELECT MIN(Age) AS Youngest, MAX(Age) AS Oldest FROM Students;
Exercise: MIN() and MAX() Find the course with the minimum credits and the course with the maximum credits in the 'Courses' table.
SQL COUNT(), AVG() and SUM() Functions COUNT() returns the number of rows that matches a specified criteria. AVG() returns the average value of a numeric column. SUM() returns the total sum of a numeric column.
Example: COUNT(), AVG(), SUM() SELECT COUNT(*) AS TotalStudents, AVG(Age) AS AverageAge, SUM(Fees) AS TotalFees FROM Students;
Exercise: COUNT(), AVG(), SUM() Count the total number of courses, average credits, and total credits in the 'Courses' table.
Advanced SQL Commands Understanding these advanced SQL commands and functions is crucial for efficient database management and data analysis.
Feedback and Questions Students are encouraged to provide feedback and ask questions at the end of the lab.