DE SQL Hiring Questions and Answers - part 101

 

DE SQL Hiring Questions and Answers  - part 101 

Note: The syntax are more focused towards BigQuery. For more information, refer BigQuery documentation.

Question 1: Joins (Left, Inner, Full) 

Context:

  • This question tests a candidate's understanding of fundamental SQL join operations, which are crucial for combining data from multiple tables in a data warehouse environment.
  • It also assesses their ability to handle NULL and empty string values, which often cause confusion.

Question:

Perform Left, Inner, and Full Outer Joins on the tables below using BigQuery, and provide the resulting tables.

Table A:

ID
1
1
2
3
4
4
5
NULL
''

Table B:

ID
1
3
3
4
4
NULL
''

Hint: Blanks/Empty strings ('') are treated as values when joining, but NULLs are treated differently.

Answer:

Here's how each join type works and the resulting tables in BigQuery:

Setup (in BigQuery):


CREATE TEMPORARY TABLE TableA (ID STRING);
INSERT TableA VALUES ('1'), ('1'), ('2'), ('3'), ('4'), ('4'), ('5'), (NULL), ('');

CREATE TEMPORARY TABLE TableB (ID STRING);
INSERT TableB VALUES ('1'), ('3'), ('3'), ('4'), ('4'), (NULL), ('');
                    

1. Left Join:

  • Returns all rows from Table A and the matching rows from Table B.
  • If there's no match in Table B, the columns from Table B will contain NULLs.

SELECT
    A.ID AS A_ID,
    B.ID AS B_ID
  FROM
    TableA AS A
    LEFT JOIN TableB AS B ON A.ID = B.ID
ORDER BY A.ID, B.ID;
                    

Result:

A_IDB_ID
11
11
2NULL
33
33
44
44
44
44
5NULL
NULLNULL
''''

2. Inner Join:

  • Returns only the rows where the join condition (A.ID = B.ID) is met in both tables.

SELECT
    A.ID AS A_ID,
    B.ID AS B_ID
  FROM
    TableA AS A
    INNER JOIN TableB AS B ON A.ID = B.ID
ORDER BY A.ID, B.ID;
                    

Result:

A_IDB_ID
11
11
33
33
44
44
44
44

3. Full Outer Join:

  • Returns all rows from both tables, matching rows where the join condition is met.
  • If there's no match in one table, the columns from the other table will contain NULLs.

SELECT
    A.ID AS A_ID,
    B.ID AS B_ID
  FROM
    TableA AS A
    FULL OUTER JOIN TableB AS B ON A.ID = B.ID
ORDER BY A.ID, B.ID;
                    

Result:

A_IDB_ID
11
11
2NULL
33
33
44
44
44
44
5NULL
NULLNULL
''''
NULLNULL

Key Takeaways:

  • LEFT JOIN: Preserves all rows from the "left" table (Table A).
  • INNER JOIN: Returns only matching rows.
  • FULL OUTER JOIN: Returns all rows from both tables, with NULLs for non-matching columns.
  • NULL vs. '': NULL represents the absence of a value, while an empty string ('') is a value itself. Joins treat them as values.

Question 2: Updating Interchanged Values

Context:

  • Tests the ability to write an UPDATE statement with a conditional expression.
  • Assesses understanding of how to manipulate data within a table.

Question:

A table has name and sex columns. However, in the sex column, the 'male' and 'female' values are interchanged. Write an UPDATE query in BigQuery to correct this.

Answer:


UPDATE
    your_table_name
SET
    sex = CASE
        WHEN sex = 'male' THEN 'female'
        WHEN sex = 'female' THEN 'male'
        ELSE sex  --  Handles other cases, if any (e.g., NULL, other values)
    END
WHERE sex IN ('male', 'female');
                    

Explanation:

  • The UPDATE statement modifies the sex column in your_table_name.
  • The CASE expression checks the current value of sex:
    • If it's 'male', it's updated to 'female'.
    • If it's 'female', it's updated to 'male'.
    • The ELSE clause ensures that any other values in the sex column (including NULL) remain unchanged. This is important to prevent unintended data changes.
  • The WHERE clause restricts the update to only the rows where the sex is either 'male' or 'female'. This is good practice for UPDATE statements.

Question 3: COALESCE Parameter Count

Context:

Tests knowledge of a basic SQL function and its syntax.

Question:

How many parameters can the COALESCE function have?

Answer:

The COALESCE function can accept one or more parameters. It returns the first non-NULL expression in the list.

COALESCE(expression1, expression2, ..., expressionN)

Explanation:

  • The COALESCE function evaluates each expression in order.
  • It returns the value of the first expression that is not NULL.
  • If all expressions evaluate to NULL, then COALESCE returns NULL.

Question 4: Nth Largest Salary from Each Department

Context:

  • Tests the ability to use window functions for ranking and filtering data within partitions.
  • Assesses understanding of how to solve a common data analysis problem.

Question:

Write a BigQuery query to find the nth largest salary from each department in an employee table. Use the ROW_NUMBER() window function.

Answer:


CREATE TEMPORARY TABLE Employees (
    EmpId INT64,
    Name STRING,
    Department STRING,
    Salary INT64
);
INSERT Employees VALUES
    (1, 'Alice', 'Sales', 50000),
    (2, 'Bob', 'Sales', 60000),
    (3, 'Charlie', 'Sales', 55000),
    (4, 'David', 'Engineering', 70000),
    (5, 'Eve', 'Engineering', 80000),
    (6, 'Frank', 'Engineering', 75000),
    (7, 'Grace', 'HR', 45000),
    (8, 'Henry', 'HR', 50000),
    (9, 'Ivy', 'HR', 48000),
    (10, 'Jack', 'Sales', 60000);

DECLARE n INT64 DEFAULT 2;  -- Change this value to find the nth largest

 
    SELECT
        EmpId,
        Name,
        Department,
        Salary,
        ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) as RowNum
    FROM
        Employees
Qualify RowNum = n

Explanation:

  1. ROW_NUMBER() Window Function:
    • PARTITION BY Department: Divides the employee table into partitions based on the Department column.
    • ORDER BY Salary DESC: Orders the employees within each department partition by Salary in descending order (highest salary first).
    • ROW_NUMBER(): Assigns a unique rank to each employee within each department, starting from 1 for the highest salary.
  2. Qualify:
    • The Qualify filters the results of the window function to select only the rows where RowNum is equal to n (the desired nth largest salary).
  3. Result:
    • The query returns the Department, Name, and Salary of the employee with the nth largest salary in each department.
Using Subquery (Not recommended) but this might be an ask while hiring to provide alternative ways: 
SELECT e1.Department, e1.Salary
FROM Employee e1
WHERE (
    SELECT COUNT(DISTINCT e2.Salary)
    FROM Employee e2
    WHERE e2.Department = e1.Department
      AND e2.Salary > e1.Salary
) = N - 1

Question 5: Copying Data to CSV File Replacing NULLs

Context:

  • Tests knowledge of how to export data from BigQuery to a common file format.
  • Assesses the ability to handle NULL values during the export process.
  • Evaluates understanding of BigQuery export options.

Question:

How do you copy data from a table in BigQuery to a CSV file, replacing NULLs with a specific value (e.g., 'Unknown') during the export?

Answer:

BigQuery doesn't directly replace NULLs during the export to a CSV file. However, you can achieve this by using IFNULL or COALESCE in your query before exporting the data.

Here are two methods:

Method 1: Using bq extract

  1. Prepare the data with NULL replacement:
    • Use a SELECT statement with IFNULL or COALESCE to replace NULL values with your desired replacement value.
  2. Export the result to a CSV file:
    • Use BigQuery's export functionality (either via the UI, bq command-line tool, or client libraries) to export the result of the query to a CSV file in Cloud Storage.

Example (BigQuery and bq command-line tool):


--  1. Prepare the data in BigQuery
SELECT
    id,
    name,
    COALESCE(value, 'Unknown') AS value  -- Replace NULLs in the 'value' column
FROM
    your_table_name;
                    

# 2. Export the data to a CSV file in Cloud Storage using bq
bq extract --destination_format CSV \
    'your_project_id:your_dataset_id.your_table_name' \
    'gs://your_bucket_name/your_file_name.csv'
                    

Method 2: Using EXPORT DATA


EXPORT DATA
    OPTIONS (
        uri = 'gs://your_bucket/your_file_prefix*.csv',  -- Cloud Storage URI
        format = 'CSV',
        overwrite = TRUE,
        field_delimiter = ',',  -- Optional: Specify the delimiter
        null_marker = 'Unknown'   -- Specify string to replace nulls
    ) AS
SELECT
    id,
    name,
    COALESCE(value, 'Unknown') AS value
FROM your_table_name;

Explanation:

  • SELECT ... COALESCE(value, 'Unknown') ...: This query selects the data from your table and replaces any NULL values in the value column with 'Unknown'. This ensures that the CSV file doesn't contain any unhandled NULLs.
  • bq extract ...: This is the BigQuery command-line tool command to export data.
    • --destination_format CSV: Specifies that the data should be exported to a CSV file.
    • 'your_project_id:your_dataset_id.your_table_name': Identifies the BigQuery table you want to export.
    • 'gs://your_bucket_name/your_file_name.csv': Specifies the Cloud Storage location where the CSV file will be created. You'll need to replace these placeholders with your actual project ID, dataset ID, table name, bucket name, and desired file name.
  • EXPORT DATA: This SQL statement exports data from a BigQuery table.
    • uri: Cloud Storage URI.
    • format: 'CSV'.
    • overwrite: Overwrite existing files.
    • field_delimiter: Optional CSV delimiter.
    • null_marker: String to represent NULLs in the CSV.

Key Considerations:

  • Cloud Storage: BigQuery exports to Cloud Storage. You'll need a bucket.
  • Permissions: Your BigQuery service account needs permissions to export and write to Cloud Storage.
  • File Size: For large tables, consider partitioning or multiple exports.
  • Data Types: BigQuery data types are converted to strings in CSV. Be mindful of dates, etc.
  • CSV Formatting: Control formatting (delimiter, quotes) with bq extract or EXPORT DATA options.

Question 6: Finding the Maximum Value Across Columns

Context:

  • This question tests your ability to use functions to find max values across columns. It evaluates your understanding of how to handle multiple columns in a row-wise operation.

Question:

Write a BigQuery query to find the maximum value among several columns (e.g., col1, col2, col3) in a table for each row.

Answer:

In BigQuery, the GREATEST() function is your friend here:


CREATE TEMPORARY TABLE sample_table (
    id INT64,
    col1 INT64,
    col2 INT64,
    col3 INT64
);
INSERT sample_table VALUES
    (1, 10, 20, 15),
    (2, 5, 30, 25),
    (3, 100, 80, 90),
    (4, 50, NULL, 60);

SELECT
    id,
    GREATEST(col1, col2, col3) AS max_value
FROM
    sample_table;
                    

Explanation:

  • GREATEST(col1, col2, col3): This function takes the column names as arguments and returns the largest value among them for each row.
  • If any of the arguments are NULL, the GREATEST function will return NULL for that row.

Handling NULLs:

To treat NULLs as a specific value (e.g., 0) in the comparison:


SELECT
    id,
    GREATEST(IFNULL(col1, 0), IFNULL(col2, 0), IFNULL(col3, 0)) AS max_value
FROM
    sample_table;

Comments

Popular posts from this blog

Python Hiring QnA | Py101

Data Engineer SQL Hiring | 105