sqlbeginner10 minutes

Create a Function to Get Employee Names by Department

Write a SQL function that returns a list of employee names for a given department from an employees table.

Challenge prompt

Create a SQL function named get_employee_names_by_department that accepts a department name as an argument and returns all employee names working in that department. Assume there is a table named employees with columns id, name, and department.

Guidance

  • Use a SELECT statement within the function to filter employees by the department argument.
  • Return the employee names as a set of rows or a table depending on your SQL dialect.

Hints

  • Use the WHERE clause to filter rows based on the department column.
  • If your SQL dialect supports RETURN TABLE functions, use that to list all matching employees.

Starter code

CREATE FUNCTION get_employee_names_by_department(dept_name VARCHAR)
RETURNS TABLE(name VARCHAR) AS $$
BEGIN
  -- Your code here
END;
$$ LANGUAGE plpgsql;

Expected output

Calling get_employee_names_by_department('Sales') returns a list of names of employees in the Sales department.

Core concepts

basic SQL SELECTfunctionsWHERE clause

Challenge a Friend

Send this duel to someone else and see if they can solve it.