IntermediateAdvanced PostgreSQL

Table function: set-returning function

The query

SQL
CREATE OR REPLACE FUNCTION get_dept_employees(p_dept_name TEXT)
RETURNS TABLE(
  emp_id INT,
  full_name TEXT,
  salary NUMERIC,
  hire_date DATE
) AS $$
BEGIN
  RETURN QUERY
  SELECT
    e.emp_id,
    e.first_name || ' ' || e.last_name,
    e.salary,
    e.hire_date
  FROM employees e
  JOIN departments d ON e.dept_id = d.dept_id
  WHERE d.dept_name ILIKE p_dept_name;
END;
$$ LANGUAGE plpgsql;

-- Use it like a table:
SELECT * FROM get_dept_employees('Engineering')
WHERE salary > 60000;
Tested against PostgreSQL 16

Note

Set-returning functions (SRFs) can be used in FROM clause like tables. Supports WHERE, ORDER BY, etc.

Tables referenced