DE SQL Hiring Questions and Answers - part 101
DE SQL Hiring Questions and Answers - part 101
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
NULLand 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:
Table B:
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:
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:
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:
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, withNULLs for non-matching columns.NULLvs.'':NULLrepresents 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
UPDATEstatement 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
UPDATEstatement modifies thesexcolumn inyour_table_name. - The
CASEexpression checks the current value ofsex:- If it's 'male', it's updated to 'female'.
- If it's 'female', it's updated to 'male'.
- The
ELSEclause ensures that any other values in thesexcolumn (includingNULL) remain unchanged. This is important to prevent unintended data changes.
- The
WHEREclause restricts the update to only the rows where thesexis either 'male' or 'female'. This is good practice forUPDATEstatements.
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:
ROW_NUMBER()Window Function:PARTITION BY Department: Divides the employee table into partitions based on theDepartmentcolumn.ORDER BY Salary DESC: Orders the employees within each department partition bySalaryin descending order (highest salary first).ROW_NUMBER(): Assigns a unique rank to each employee within each department, starting from 1 for the highest salary.
- Qualify:
- The Qualify filters the results of the window function to select only the rows where
RowNumis equal ton(the desired nth largest salary).
- The Qualify filters the results of the window function to select only the rows where
- Result:
- The query returns the
Department,Name, andSalaryof the employee with the nth largest salary in each department.
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
NULLvalues 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
- Prepare the data with
NULLreplacement:- Use a
SELECTstatement withIFNULLorCOALESCEto replaceNULLvalues with your desired replacement value.
- Use a
- Export the result to a CSV file:
- Use BigQuery's export functionality (either via the UI,
bqcommand-line tool, or client libraries) to export the result of the query to a CSV file in Cloud Storage.
- Use BigQuery's export functionality (either via the UI,
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 anyNULLvalues in thevaluecolumn with 'Unknown'. This ensures that the CSV file doesn't contain any unhandledNULLs.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 representNULLs 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 extractorEXPORT DATAoptions.
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, theGREATESTfunction will returnNULLfor 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
Post a Comment