0% found this document useful (1 vote)
95 views3 pages

SQL Practice: Final Query Exercises

The document provides 10 exercises to practice SQL queries using employee and salary data tables. The exercises include finding average salaries by gender and department, retrieving lowest and highest department numbers, creating a table with employee number, lowest department number, and assigned manager, retrieving employees hired in 2000, retrieving engineers and senior engineers, creating a stored procedure to retrieve an employee's number and last department, counting contracts over 1 year and $100k, creating a trigger to check hire dates, defining functions to retrieve maximum and minimum contract salaries for an employee, and creating a third function to return maximum, minimum, or range of salaries based on a parameter.

Uploaded by

Yashi Shekhar
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 (1 vote)
95 views3 pages

SQL Practice: Final Query Exercises

The document provides 10 exercises to practice SQL queries using employee and salary data tables. The exercises include finding average salaries by gender and department, retrieving lowest and highest department numbers, creating a table with employee number, lowest department number, and assigned manager, retrieving employees hired in 2000, retrieving engineers and senior engineers, creating a stored procedure to retrieve an employee's number and last department, counting contracts over 1 year and $100k, creating a trigger to check hire dates, defining functions to retrieve maximum and minimum contract salaries for an employee, and creating a third function to return maximum, minimum, or range of salaries based on a parameter.

Uploaded by

Yashi Shekhar
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

Practice SQL – 10 Final Query Questions

Exercise 1

Find the average salary of the male and female employees in each department.

Exercise 2

Find the lowest department number encountered in the 'dept_emp' table. Then, find the highest
department number.

Exercise 3

Obtain a table containing the following three fields for all individuals whose employee number is not
greater than 10040:

- employee number

- the lowest department number among the departments where the employee has worked in (Hint: use
a subquery to retrieve this value from the 'dept_emp' table)

- assign '110022' as 'manager' to all individuals whose employee number is lower than or equal to 10020,
and '110039' to those whose number is between 10021 and 10040 inclusive.

Use a CASE statement to create the third field.

If you've worked correctly, you should obtain an output containing 40 rows.

Here’s the top part of the output. Does it remind you of an output you’ve obtained earlier in the course?

Exercise 4

Retrieve a list of all employees that have been hired in 2000.


Exercise 5

Retrieve a list of all employees from the ‘titles’ table who are engineers.

Repeat the exercise, this time retrieving a list of all employees from the ‘titles’ table who are senior
engineers.

After LIKE, you could indicate what you are looking for with or without using parentheses. Both options are
correct and will deliver the same output. We think using parentheses is better for legibility and that’s why
it is the first option we’ve suggested.

Exercise 6

Create a procedure that asks you to insert an employee number and that will obtain an output containing
the same number, as well as the number and name of the last department the employee has worked in.

Finally, call the procedure for employee number 10010.

If you've worked correctly, you should see that employee number 10010 has worked for department
number 6 - "Quality Management".

Exercise 7

How many contracts have been registered in the ‘salaries’ table with duration of more than one year and
of value higher than or equal to $100,000?

Hint: You may wish to compare the difference between the start and end date of the salaries contracts.

Exercise 8

Create a trigger that checks if the hire date of an employee is higher than the current date. If true, set the
hire date to equal the current date. Format the output appropriately (YY-mm-dd).

Extra challenge: You can try to declare a new variable called 'today' which stores today's data, and then
use it in your trigger!

After creating the trigger, execute the following code to see if it's working properly.

Exercise 9

Define a function that retrieves the largest contract salary value of an employee. Apply it to employee
number 11356.

In addition, what is the lowest contract salary value of the same employee? You may want to create a new
function that to obtain the result.
Exercise 10

Based on the previous exercise, you can now try to create a third function that also accepts a second
parameter. Let this parameter be a character sequence. Evaluate if its value is 'min' or 'max' and based on
that retrieve either the lowest or the highest salary, respectively (using the same logic and code structure
from Exercise 9). If the inserted value is any string value different from ‘min’ or ‘max’, let the function
return the difference between the highest and the lowest salary of that employee.

Common questions

Powered by AI

To filter employees hired in a specific year, such as 2000, you would use a WHERE clause on the hire date, coupled with YEAR function extraction on the hire date field in SQL. The main challenges include ensuring the date formats are consistently stored in the database and dealing with any missing or inaccurately entered data. Incorrect date formats can affect the comparison logic and lead to inaccurate filtering results .

Defining a function with multiple parameters illustrates SQL's adaptability by allowing a single reusable function to handle multiple scenarios, such as retrieving either the maximum, the minimum, or the difference between salaries based on a parameter's value. This showcases SQL's ability to incorporate complex logic and conditional processing within its structured query capabilities, providing powerful tools for tailored data retrieval and enhancing efficiency in database management tasks .

To find the average salary of employees by gender in each department using SQL, you can utilize the GROUP BY clause on both gender and department fields with an aggregating function like AVG. This involves querying the relevant employee and department tables, and joining them if necessary, to fetch and group the required data. The potential implications of these findings include insights into gender pay equity within a department, disparities that might need addressing, and guiding financial decisions regarding payroll distributions .

Key considerations include identifying the latest departmental association of an employee by ranking or ordering the department history records. This task involves using SQL components such as procedures to define executable routines, JOIN operations to combine employee details with departments, and potentially the ORDER BY and LIMIT clauses to precisely select the most recent record. Accuracy and performance are crucial, ensuring the procedure returns the right data rapidly .

An SQL query to determine the count of contracts longer than a year with values exceeding $100,000 would involve conditionally filtering the contracts using the WHERE clause combined with the DATEDIFF function to calculate duration, and comparison operators for salary value. Advanced skills necessary to optimize such queries include indexing knowledge for quick lookups, understanding query execution plans to fine-tune performance, and possibly using subqueries for complex conditions that require pre-filtering data sets .

To locate the lowest and highest department numbers in a database table, you can use the MIN and MAX functions in SQL specifically on the department numbers column. This is valuable because it helps ensure proper indexing and ascertain whether department numbers are consistent and logical, aiding data integrity. Additionally, it could highlight unused department numbers or help in planning and structuring departments as the organization evolves .

Creating an SQL trigger that adjusts invalid hire dates enhances data integrity by automatically correcting any input errors related to hiring, where future dates get mistakenly entered. This ensures that the data remains consistent and realistic—reflecting only legitimate, past or current dates. Moreover, it provides a safeguard against accidental data entry mistakes, helps maintain accurate employment records, and reduces manual correction efforts .

To structure a function that returns the largest contract salary of a specific employee, you would define the function with a parameter for the employee ID, and use SQL's MAX function to retrieve the highest salary from the relevant salary table. Extending the capabilities of this function could involve adding parameters for returning the minimum salary or calculating the salary difference, depending on additional input arguments like 'min' or 'max', thus making the function versatile for different analytical requirements .

Using LIKE with parentheses in SQL enhances query legibility by visually delineating the search pattern, making it clearer what exactly is being filtered or matched, which is especially beneficial for complex queries or when multiple conditions are involved. While the outcome remains the same without parentheses, parentheses aid readability and minimize errors in pattern specification, which can indirectly reduce debugging time and enhance maintainability of SQL code .

The SQL CASE statement can be used to conditionally assign managers to employees based on specific criteria, such as employee numbers, by evaluating each record and applying the correct assignment. This is practical when a rule specifies different managers for different ranges of employee numbers. The CASE statement evaluates each condition sequentially and applies the corresponding result if a condition is true, allowing for flexible, dynamic data management within queries .

You might also like