DE SQL Hiring Questions and Answers - part 102

 

#DE SQL Hiring Questions and Answers for Data Engineers

This blog post dives into a set of advanced SQL interview questions commonly encountered in data engineering interviews. These questions test your ability to manipulate data, optimize queries, and solve complex problems using SQL. We'll cover concepts like window functions, aggregate functions, join behavior, date manipulation, and query optimization.

Question : How to get the top 40% of employees from each department

This question requires using window functions to rank employees within each department and then filter for the top 40%.

Answer:


WITH DepartmentEmployeeRanks AS (
    SELECT
        e.employee_id,
        e.name,
        e.department,
        e.salary,
        COUNT(*) OVER (PARTITION BY e.department) AS dept_employee_count,
        RANK() OVER (PARTITION BY e.department ORDER BY e.salary DESC) AS salary_rank
    FROM
        employees e
    WHERE e.department is not null
)
SELECT
    employee_id,
    name,
    department,
    salary
FROM
    DepartmentEmployeeRanks
WHERE
    salary_rank <= CAST(dept_employee_count * 0.4 AS INT64)
ORDER BY department, salary DESC;
                

Explanation:

  1. `WITH` Clause (CTE):
    A Common Table Expression (CTE) named `DepartmentEmployeeRanks` is defined to calculate the rank of employees within each department.
  2. `COUNT(*) OVER (PARTITION BY e.department)`:
    Calculates the total number of employees in each department.
  3. `RANK() OVER (PARTITION BY e.department ORDER BY e.salary DESC)`:
    Ranks employees within each department based on their salary in descending order. `RANK()` handles ties by assigning the same rank to employees with the same salary.
  4. `WHERE e.department is not null`:
    Filters out any null departments
  5. Final `SELECT` Statement:
    The outer query retrieves the employee details for those whose `salary_rank` is within the top 40% of their department.
    `CAST(dept_employee_count * 0.4 AS INT64)`: Calculates the cutoff rank for the top 40%.
  6. `ORDER BY` Clause:
    Orders the result by department and salary

Question : Managers with employee count having a salary greater than 50k

This question involves joining tables, grouping data, and applying a filter on the aggregated count.

Answer:


SELECT
    m.manager_id,
    m.name AS manager_name,
    COUNT(e.employee_id) AS employee_count
FROM
    managers m
JOIN
    employees e ON m.manager_id = e.manager_id
WHERE e.salary > 50000
GROUP BY
    m.manager_id, m.name
HAVING
    COUNT(e.employee_id) > 0
ORDER BY employee_count DESC;
                

Explanation:

  1. `JOIN` Clause:
    Joins the `managers` table with the `employees` table on the `manager_id` column.
  2. `WHERE` Clause:
    Filters employees with a salary greater than 50000.
  3. `GROUP BY` Clause:
    Groups the result set by `manager_id` and `manager_name` to count employees for each manager.
  4. `HAVING` Clause:
    Filters the groups, selecting only those managers who have at least one employee with a salary greater than 50000.
  5. `ORDER BY` Clause:
    Orders the result by the number of employees in descending order.

Question : How are index seeks better than index scans?

An index scan is a database operation where the database system reads data from an index, rather than reading the entire table. Index scans are generally faster than full table scans, but not always.

Answer:

An index seek is more efficient than an index scan because it allows the database to directly locate the specific rows needed, rather than reading through the entire index. Here's a breakdown:

  • Index Seek: The database uses the index to "seek" to the exact location of the data it needs. This is like using an index in a book to go directly to the page you want. It's very fast, especially for highly selective queries (e.g., looking up a single customer by ID).
  • Index Scan: The database has to read through a larger portion of the index (or even the entire index) to find the relevant data. This is like reading through a large part of a book's index to find a few specific entries. It's less efficient than a seek, but can be more efficient than a full table scan in some cases.

In essence, an index seek is like a surgical strike, while an index scan is like a broader search. When a query is very specific and the database can use an index, a seek is the preferred and more performant method.

These both are better than full table scan which should be excused.

Question : How to get business days between two dates

This is a common question that requires calculating the difference between two dates while excluding weekends.

Answer:

In BigQuery, you can achieve this using a combination of `GENERATE_DATE_ARRAY`, `EXTRACT`, and a `CASE` statement.


CREATE TEMPORARY FUNCTION BUSINESSDAYS(start_date DATE, end_date DATE)
RETURNS INT64 AS (
  SELECT
    COUNT(date)
  FROM
    UNNEST(GENERATE_DATE_ARRAY(start_date, end_date)) AS date
  WHERE EXTRACT(DAYOFWEEK FROM date) NOT IN (1, 7) -- 1 is Sunday, 7 is Saturday
);

SELECT BUSINESSDAYS('2023-10-26', '2023-11-05');
                

Explanation:

  1. `GENERATE_DATE_ARRAY`:
    Generates an array of dates between the start and end dates (inclusive).
  2. `UNNEST`:
    Expands the date array into a table.
  3. `EXTRACT(DAYOFWEEK FROM date)`:
    Extracts the day of the week (1 for Sunday, 7 for Saturday) from each date.
  4. `WHERE EXTRACT(DAYOFWEEK FROM date) NOT IN (1, 7)`:
    Filters out dates that fall on weekends (Saturday and Sunday).
  5. `COUNT(date)`:
    Counts the remaining dates, which are the business days.
  6. User Defined Function (UDF):
    The code defines a reusable function `BUSINESSDAYS`

Question: Calculate the exact date difference between two dates

This question tests your ability to work with dates and time intervals.

Answer:


SELECT
    DATE_DIFF('2000-02-28', '2000-02-20', DAY) AS day_difference,
-- To get month and year difference
    DATE_DIFF('2024-02-28', '2023-02-20', MONTH) AS month_difference,
    DATE_DIFF('2024-02-28', '2023-02-20', YEAR) AS year_difference;

---- to Get the date difference in year, month and day format
-- 2000-02-28 and current_date()

    SELECT
  DATE_DIFF(end_date, start_date, YEAR) AS year_diff,
  DATE_DIFF(end_date, start_date, MONTH)
    - DATE_DIFF(end_date, start_date, YEAR) * 12 - CASE WHEN Extract( day from end_date) <= extract( day from start_date) then 1 else 0 end
    AS month_diff,
  DATE_DIFF(
    end_date,
    DATE_ADD(
      DATE_ADD(
        start_date,
        INTERVAL DATE_DIFF(end_date, start_date, YEAR) YEAR
      ),
      INTERVAL (DATE_DIFF(end_date, start_date, MONTH) - DATE_DIFF(end_date, start_date, YEAR) * 12 - CASE WHEN Extract( day from end_date) <= extract( day from start_date) then 1 else 0 end) MONTH
    ),
    DAY
  ) AS day_diff,

FROM (SELECT DATE '2000-02-28' AS start_date, DATE '2025-05-04' AS end_date)

Explanation:

  • `DATE_DIFF`: Returns the difference between two date values, using the specified date part (DAY, MONTH, YEAR).

Question: Calculate the tenure of employees

This question requires calculating the duration an employee has been employed, typically using their hire date and either the current date or a termination date.

Answer:


SELECT
    employee_id,
    hire_date,
    IFNULL(termination_date, CURRENT_DATE()) AS end_date,  -- Use current date for active employees
    DATE_DIFF(IFNULL(termination_date, CURRENT_DATE()), hire_date, YEAR) AS tenure_years,
    DATE_DIFF(IFNULL(termination_date, CURRENT_DATE()), hire_date, MONTH) AS tenure_months,
    DATE_DIFF(IFNULL(termination_date, CURRENT_DATE()), hire_date, DAY)   AS tenure_days
FROM
    employees;
                

Explanation:

  • `IFNULL(termination_date, CURRENT_DATE())`:
    If `termination_date` is not NULL, use that date. If `termination_date` is NULL (meaning the employee is still active), use the current date.
  • `DATE_DIFF`: Calculates the difference between the hire date and the end date (either termination date or current date) in years, months, and days.

Question: Youngest (minimum age) employee with tenure of more than 5 years

This question combines date calculations with filtering and aggregation.

Answer:


SELECT
    employee_id,
    name,
    hire_date,
    DATE_DIFF(CURRENT_DATE(), birth_date, YEAR) AS age,
    DATE_DIFF(CURRENT_DATE(), hire_date, YEAR) AS tenure_years
FROM
    employees
WHERE DATE_DIFF(CURRENT_DATE(), hire_date, YEAR) > 5
QUALIFY RANK() OVER (ORDER BY DATE_DIFF(CURRENT_DATE(), birth_date, YEAR)) = 1
                

Explanation:

  1. Calculate Age and Tenure:
    Calculates the age and tenure (in years) for each employee.
  2. Filter by Tenure:
    Filters out employees with a tenure of 5 years or less.
  3. `QUALIFY` Clause
    Filters the results of a window function.
    `RANK() OVER (ORDER BY DATE_DIFF(CURRENT_DATE(), birth_date, YEAR))`: Ranks employees by age (youngest to oldest).
    `= 1`: Selects the employee with the rank 1 (the youngest).

Comments

Popular posts from this blog

Python Hiring QnA | Py101

Data Engineer SQL Hiring | 105

DE SQL Hiring Questions and Answers - part 101