0% found this document useful (0 votes)
15 views5 pages

SQL Practice Questions For Lab Exam

This document provides a comprehensive set of SQL practice questions designed to prepare students for a lab exam, covering various topics such as database schema creation, SQL commands, joins, aggregate functions, and PL/SQL programming. It includes detailed requirements for two database schemas: a University Management System and an E-commerce System, with specific tasks for each schema. The questions range from basic SQL queries to complex queries and PL/SQL code blocks, triggers, procedures, and functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views5 pages

SQL Practice Questions For Lab Exam

This document provides a comprehensive set of SQL practice questions designed to prepare students for a lab exam, covering various topics such as database schema creation, SQL commands, joins, aggregate functions, and PL/SQL programming. It includes detailed requirements for two database schemas: a University Management System and an E-commerce System, with specific tasks for each schema. The questions range from basic SQL queries to complex queries and PL/SQL code blocks, triggers, procedures, and functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SQL Practice Questions for Lab Exam

Based on your sample paper, here are practice questions covering all the topics you mentioned.
These are designed to help you prepare for your lab exam.

Database Schema 1: University Management System


Tables:
STUDENT (student_id, first_name, last_name, dob, gender, email, enrollment_date)
DEPARTMENT (dept_id, dept_name, building, budget)
COURSE (course_id, course_name, credits, dept_id)
INSTRUCTOR (instructor_id, first_name, last_name, hire_date, salary, dept_id)
ENROLLMENT (enrollment_id, student_id, course_id, semester, year, grade)

SQL DDL Commands


1. Create the STUDENT table with appropriate constraints:
student_id should be the primary key
email should be unique
gender should only accept 'M', 'F', or 'O'
enrollment_date should not be null
2. Create the COURSE table with appropriate foreign key constraints referencing the
DEPARTMENT table.
3. Alter the STUDENT table to add a new column 'address' of VARCHAR(200) type.
4. Create an index on the last_name column of the STUDENT table for faster searching.

Basic SQL SELECT Commands


5. Write a query to select all columns from the STUDENT table.
6. Write a query to display the first_name, last_name, and email of all students.
7. Write a query to list all courses with more than 3 credits.

Queries with ORDER BY, EXISTS, NOT EXISTS, BETWEEN, IN, NOT IN
8. Write a query to list all students ordered by last_name in ascending order and then by
first_name in descending order.
9. Find all courses with credits between 3 and 5.
10. List all instructors who were hired between '2010-01-01' and '2020-01-01'.
11. Find all students who are enrolled in either course 'CS101', 'CS201', or 'CS301'.
12. List all departments that do not have any instructors.

Explicit Joins
13. Write a query to join STUDENT and ENROLLMENT tables to display student names along
with the courses they are enrolled in.
14. Join the COURSE and DEPARTMENT tables to list course names along with their respective
department names.
15. Use a left join to list all departments and the number of instructors in each department
(including departments with zero instructors).

GROUP BY and HAVING with Aggregate Functions


16. Find the total number of students enrolled in each course.
17. Calculate the average grade for each course in the Fall 2023 semester.
18. List departments with more than 5 instructors.
19. Find courses with an average grade higher than 85.

Nested Queries
20. Find all students who are enrolled in more courses than the average number of enrollments
per student.
21. List all instructors who earn more than the average salary of instructors in their department.
22. Find departments that have more courses than the average number of courses per
department.

Complex Queries
23. Find the department with the highest number of students enrolled in its courses, along with
the total number of enrollments.
24. For each instructor, list the courses they teach and the average grade of students in those
courses, but only include courses with at least 3 students enrolled.
25. Find all students who have taken courses from at least 3 different departments.

PL/SQL Code Blocks


26. Write a PL/SQL code block to calculate and display the factorial of a given number.
27. Create a PL/SQL block that declares variables for student details (id, name, grade), assigns
values to them, and displays whether the student passed (grade >= 60) or failed.
PL/SQL Triggers
28. Create a trigger that prevents instructors from being deleted if they are teaching any
courses.
29. Write a trigger that automatically updates the 'last_updated' timestamp in the COURSE
table whenever a course record is modified.

PL/SQL Stored Procedures


30. Create a stored procedure to enroll a student in a course, which takes student_id, course_id,
semester, and year as parameters.
31. Write a stored procedure that transfers all instructors from one department to another
department.

PL/SQL Stored Functions


32. Create a stored function that returns the total number of courses offered by a specific
department.
33. Write a stored function that calculates and returns the average salary of instructors in a
given department.

Database Schema 2: E-commerce System


Tables:
CUSTOMER (customer_id, first_name, last_name, email, phone, registration_date)
PRODUCT (product_id, product_name, description, price, stock_quantity, category_id)
CATEGORY (category_id, category_name, parent_category_id)
ORDER_HEADER (order_id, customer_id, order_date, total_amount, status)
ORDER_DETAILS (order_detail_id, order_id, product_id, quantity, unit_price)
SHIPPING (shipping_id, order_id, shipping_date, delivery_date, address, carrier)

SQL DDL Commands


34. Create the CUSTOMER table with appropriate constraints:
customer_id as primary key
email must be unique
registration_date cannot be null
35. Create the PRODUCT and CATEGORY tables with all necessary constraints including a self-
referencing foreign key in CATEGORY for the parent-child relationship.
Basic SQL SELECT Commands
36. List all customers who registered in 2024.
37. Find all products with stock_quantity less than 10.

ORDER BY, EXISTS, NOT EXISTS, BETWEEN, IN, NOT IN


38. List all products ordered by price in descending order.
39. Find all orders with total_amount between $100 and $500.
40. List customers who have placed orders but never made a purchase in the "Electronics"
category.

Explicit Joins
41. Join CUSTOMER and ORDER_HEADER to display customer names with their order dates.
42. Write a query that joins ORDER_HEADER, ORDER_DETAILS, and PRODUCT to list order IDs
with product names and quantities.

GROUP BY and HAVING with Aggregate Functions


43. Calculate the total revenue generated by each product category.
44. List customers who have placed more than 3 orders.
45. Find products that have generated more than $1000 in total sales.

Nested Queries
46. Find customers who have ordered products that are out of stock (stock_quantity = 0).
47. List products that have been ordered more times than the average number of orders per
product.

Complex Queries
48. Find the top 3 customers who have spent the most money, showing their names and total
amount spent.
49. For each category, list the most expensive product along with its price.
50. Find pairs of products that are always ordered together by at least 3 different customers.

PL/SQL Code Blocks, Triggers, Procedures, Functions


51. Write a PL/SQL block that calculates and displays the total revenue for each month of the
current year.
52. Create a trigger that updates product stock_quantity whenever an order is placed or
canceled.
53. Write a stored procedure that applies a discount to all products in a specific category.
54. Create a stored function that returns the total number of days between ordering and
shipping for a given order_id.

Common questions

Powered by AI

Nested queries in an e-commerce system optimize data retrieval by allowing precise filtering and deeper insights into complex data relationships. For example, nested queries can identify customers who ordered out-of-stock products by first selecting products with zero stock and then matching them against recent orders . Additionally, they can enhance product analysis by listing products ordered more frequently than average, where a subquery computes the average number of orders per product . To implement nested queries effectively, careful structuring of subqueries and main queries with appropriate conditions ensures accurate and efficient data retrieval, thereby reducing computational overhead.

SQL indexes improve the speed of search queries by allowing quicker data retrieval, acting similarly to an index in a book. In large academic databases, creating an index on the STUDENT table's last_name column speeds up queries that frequently search or sort by last name . However, indexes have limitations: they consume additional disk space and can slow down data modification operations like INSERT, UPDATE, and DELETE because the index itself must be updated. Therefore, while indexes optimize query performance, their use should be balanced against these costs and the specific query workload of the database system.

Transaction management enforces the ACID (Atomicity, Consistency, Isolation, Durability) properties, improving order processing reliability in e-commerce platforms. Atomicity ensures that operations succeed or fail as a whole, preventing partial updates that could occur during order processing . Consistency maintains database integrity through enforced constraints and rules, eliminating erroneous order states. Isolation maintains transaction independence to prevent concurrent transactions from interfering, thus safeguarding accurate order handling . Durability guarantees that once a transaction is committed, it persists through system crashes, protecting transaction records and ensuring customer satisfaction and trust.

Complex SQL queries can be designed by leveraging joins, nested queries, and aggregation functions to identify relationships between data entities. For instance, finding the department with the highest student enrollments requires joining ENROLLMENT and COURSE tables and grouping by department, followed by summarizing and comparing total enrollments . Another approach involves using nested queries to find students enrolled in more courses than the average, which requires calculating the average enrollments per student and filtering those who exceed this average . These techniques allow for the synthesis of comprehensive insights from multi-relational data, thus effectively leveraging entity relationships.

Data integrity in the STUDENT table can be enforced through the use of various constraints. Firstly, the student_id should be set as the primary key to ensure each student has a unique identifier . Secondly, the email field should be unique to avoid duplicate entries for contact information . Additionally, the gender field should be constrained to only accept 'M', 'F', or 'O' to maintain consistency in gender entry . Finally, the enrollment_date must not be null, which ensures that the date of enrollment is always captured for each student .

Ensuring stored functions provide accurate calculations, such as computing average instructor salaries, involves methodologies like precise data validation and efficient handling of null and error values. When constructing a stored function, one must ensure proper aggregation logic and exclude skewing factors such as null salary records, which can affect the average . Utilizing robust error handling and validation checks within the function helps maintain calculation accuracy. Additionally, functions should be tested with realistic dataset scenarios to ensure they handle edge cases and return consistent results across varied input conditions, thereby providing reliable calculations and supporting informed decision-making.

PL/SQL triggers maintain data integrity by automatically enforcing business rules and constraints in response to specific data manipulation events. For instance, a trigger can prevent the deletion of instructors if they are currently teaching courses, thus preserving the referential integrity of the database . Another trigger may automatically update a 'last_updated' timestamp when any modification occurs in the COURSE table, ensuring that modification history is accurately tracked and integrity of data timestamps is maintained . These triggers ensure that critical data-related rules are adhered to without requiring manual intervention, thereby enhancing the reliability and consistency of the database system.

To effectively list course data from multiple related tables, explicit joins such as INNER JOIN and LEFT JOIN can be used. An INNER JOIN between the COURSE and DEPARTMENT tables can list course names along with their respective department names, leveraging foreign key relationships for accurate data retrieval . A LEFT JOIN can be used to ensure all departments are listed even if they have no instructors, highlighting departments with zero instructors . These strategies are effective because they allow for a comprehensive view of related data, facilitating more robust data analysis and reporting.

Stored procedures offer several advantages for managing frequent database operations. They encapsulate business logic within the database, making operations like enrolling a student in a course more efficient and less error-prone, as the operations are pre-compiled and centrally managed . Stored procedures also enhance security by restricting direct access to data tables and allow for consistent execution of complex operations, such as transferring instructors between departments . Furthermore, they reduce network traffic by processing data-intensive logic directly within the database, thus improving application performance.

Aggregate functions combined with GROUP BY clauses enable enhanced data analysis by allowing users to perform calculations and obtain summary information for grouped data. For instance, calculating the total number of students enrolled in each course provides insights into course popularity and capacity needs . Similarly, computing the average grade per course during a specific term, such as Fall 2023, helps assess academic performance across different subjects . Analyzing departments with more than 5 instructors using these functions provides understanding of department size and resource allocation . Thus, GROUP BY and aggregate functions facilitate in-depth data analysis by summarizing key organizational metrics.

You might also like