DE SQL Hiring Questions and Answers for Data Engineers - part 103

 

#DE SQL Hiring Questions and Answers for Data Engineers

Data engineering is a hot field, and mastering advanced SQL is crucial for anyone looking to make a splash. This blog post dives into some of the most challenging SQL interview questions, designed to test your ability to wrangle data, optimize performance, and solve real-world problems. We'll explore cutting-edge techniques and future-proof your SQL skills.

Q: How do you identify non-managerial employees (the lowest rung of the hierarchy)?

In today's data-centric organizations, understanding the pecking order is essential. This question isn't just about SQL; it's about how you approach organizational structure in a database. We need to find those individual contributors who don't have anyone reporting to them. Here's how we can do it:


-- Using the elegant LEFT JOIN
SELECT e.employee_id, e.name
FROM employees e
LEFT JOIN employees m ON m.manager_id = e.employee_id #Focus
WHERE m.manager_id IS NULL; --#Important -- For the subQuery-savvy: NOT EXISTS SELECT e.employee_id, e.name FROM employees e WHERE NOT EXISTS (SELECT 1 FROM employees m WHERE m.manager_id = e.employee_id);

Explanation:

  • LEFT JOIN: Think of this as saying, "Show me all employees, and if they're also a manager, show me that too." Then, we filter out the ones where the manager info is missing (NULL), because those are our non-managers. It's a very intuitive way to express this relationship.
  • NOT EXISTS: This is a bit more of a brain-bender, but it can be faster, especially with large tables. It's like saying, "Show me the employees for whom it does not exist that they are in the managers table." It's a double negative, which sometimes takes a moment to click, but it's very efficient.

Q: SQL query to detect records with lowercase names.

Data quality is super important. If you've got names in all sorts of weird formats, it can mess up reports, applications, and everything else. This question is about how you use SQL to clean up that kind of mess. Here's how you can find those pesky records where the first name isn't all uppercase:


-- Standard SQL (highly portable)
SELECT *
FROM employees
WHERE first_name <> UPPER(first_name);

-- PostgreSQL, MySQL, SQL Server
SELECT *
FROM employees
WHERE first_name <> UPPER(first_name);

-- BigQuery (for cloud-native engineers)
SELECT *
FROM employees
WHERE first_name != UPPER(first_name);
                

Explanation: The key here is the UPPER() function. It's a neat trick that lets you convert any text to uppercase. We then compare the original name to its uppercase version. If they're different, we know the original name had some lowercase letters in it.

Q: What does a Hash Join in an estimated plan signify?

Okay, let's talk about how databases actually do their work. When you ask a database to combine information from two tables, it has several ways it could do it. The "estimated plan" is the database's prediction of how it will do it. If you see a "Hash Join" in that plan, it's a sign the database is feeling confident it can do things very quickly.

Answer: A "Hash Join" in a query's estimated execution plan means the database intends to use a hash join algorithm to efficiently combine rows from two tables. It's a bit like a super-organized way of matching things up.

Explanation:

  • Hash Join: Imagine you're matching up students from two different classes based on their ID numbers. A hash join is like this:
    1. The database takes one class (usually the smaller one) and makes a special table called a "hash table." It's like assigning each student to a specific slot in a classroom based on a calculation of their ID.
    2. Then, the database goes through the other class. For each student, it does the same calculation and instantly knows which slot to look in to see if there's a match. It's way faster than checking every single student in the other class.
  • Estimated Plan: Before the database even starts doing this, it figures out the best way to do it. That's the estimated plan. If it chooses a hash join, it's a good sign the database thinks this is the quickest way to get your answer.

Q: Deciphering the difference: Actual vs. Estimated Plans

Think of it like planning a road trip. Before you leave, you map out the route, estimate how long it will take, and so on. That's your "estimated plan." Once you actually drive the route, you see how long it really took, where you hit traffic, and so on. That's your "actual plan." Databases do the same thing!

Answer: Both plans describe how a database executes a query, but they are created at different times and with different levels of accuracy:

  • Estimated Plan:
    • Created before the query runs.
    • Based on the database's best guess, using available information about the data.
    • Like that initial road trip plan - it's a prediction.
    • The database uses this to decide how to run the query.
  • Actual Plan:
    • Created while or after the query runs.
    • A record of what actually happened.
    • Like the record of your road trip with all the real-world details.
    • We use this to see if the database made good choices, and to make things faster in the future.

Q: Generate a sequence: The SQL way to produce numbers 1 to 100.

Sometimes you need a list of numbers in SQL, and there are a few different ways to do it, depending on the database you're using. It's a bit like knowing a few different ways to count to 100!


-- MySQL
SELECT n FROM (SELECT @n := @n + 1 AS n FROM (SELECT @n := 0) AS init, information_schema.COLUMNS LIMIT 100) AS numbers;

-- PostgreSQL (the clean and efficient way)
SELECT generate_series(1, 100);

-- SQL Server
SELECT number FROM master..spt_values WHERE type = 'P' AND number BETWEEN 1 AND 100;

-- Oracle (for PL/SQL aficionados)
SELECT LEVEL AS n FROM DUAL CONNECT BY LEVEL <= 100;

-- BigQuery (for cloud scale)
SELECT n FROM UNNEST(GENERATE_ARRAY(1, 100)) AS n;
                

Explanation: Each database has its own quirks:

  • MySQL: This one is a bit of a trick, using variables and a system table.
  • PostgreSQL: PostgreSQL has a function specifically for this, which is the cleanest way.
  • SQL Server: This uses a system table that contains a bunch of numbers.
  • Oracle: This uses a hierarchical query to generate the sequence.
  • BigQuery: This uses array generation

Q: Delta Indexes and the Power of UPDATE STATISTICS

Databases are constantly juggling speed and accuracy. When you're dealing with tons of data that changes all the time, it's a real challenge to keep everything up-to-date. Delta indexes and UPDATE STATISTICS are two tools that help with this balancing act.

Answer:

  • Delta Index:
    • Imagine you have a huge library, and instead of re-shelving every single book every day, you just have a small cart where you put the books that were returned that day. That cart is like a delta index. It holds the changes.
    • A delta index is a small, separate index that stores recent changes to a table.
    • This makes it super fast to record new information.
    • When someone wants to read the data, the database combines the information from the main library (the main index) and the cart (the delta index) to give them the latest information.
    • Periodically, you take the books from the cart and put them back on the shelves in the main library. This is like merging the delta index into the main index.
  • UPDATE STATISTICS:
    • Now, imagine that the library has a card catalog (remember those?). The card catalog helps you find books quickly. But if you don't update the card catalog when books are added or removed, it becomes less useful.
    • UPDATE STATISTICS is like updating that card catalog. The database uses statistics about your data to figure out the best way to retrieve it. When the data changes a lot, those statistics can get old and wrong.
    • UPDATE STATISTICS recalculates those statistics, so the database can keep finding your data quickly. This is especially important when you're using delta indexes, because the data is changing rapidly.

Q: Is a Hash Join always the hero in estimated plans?

It's tempting to think that one particular technique is always the best, but in the world of databases, it's rarely that simple. A Hash Join is often a great choice, but it's not a magic bullet.

Answer: A Hash Join in the estimated plan usually indicates the database believes it's an efficient way to combine tables for that specific query.

Explanation:

  • Hash Join Efficiency: Hash joins are like a specialized tool. They work really well when:
    • You're dealing with large tables.
    • The tables aren't already sorted in a helpful way.
    • You're looking for exact matches between rows.
  • Optimizer Preference: When the database sees those conditions, it often chooses a hash join because it can be very fast.
  • Not Always Best: But other tools exist! Sometimes, a more basic method called a "nested loop join" is actually faster, especially if one of the tables is really small. And if the tables are already sorted, a "merge join" can be the most efficient.

Q: Calculating Monthly Cumulative Sales by Department and Year

This is a classic problem in business intelligence: how do you track progress over time? We want to see not just how much each department sold in a given month, but how their sales have been adding up over the year. This requires a bit of SQL wizardry!

Answer: To get the monthly cumulative sales, use:


SELECT
    department,
    EXTRACT(YEAR FROM date) AS sale_year,
    EXTRACT(MONTH FROM date) AS sale_month,
    SUM(sale) AS monthly_sale,
    SUM(sale) OVER (PARTITION BY department, EXTRACT(YEAR FROM date), EXTRACT(MONTH FROM date) ORDER BY date) AS cumulative_sale
FROM
    sales_table  -- Replace with your table name
GROUP BY
    department,
    sale_year,
    sale_month
ORDER BY
    department,
    sale_year,
    sale_month;
                

Explanation: Let's break this down:

  • EXTRACT(): We use this to get the year and month from the date, so we can group our sales data.
  • SUM(sale) AS monthly_sale: This gives us the total sales for each department in each month. That's the easy part.
  • Window Function: This is where the magic happens. The SUM(sale) OVER (...) part is a window function, which lets us do calculations across a "window" of rows. In this case:
    • PARTITION BY department, EXTRACT(YEAR FROM date): This divides our data into separate groups for each department and year. We want to calculate cumulative sales within each department and year.
    • ORDER BY date: This is crucial! It tells SQL to add up the sales in chronological order within each month. So, for January, it adds up the sales from the 1st, then the 2nd, then the 3rd, and so on.

Comments

Popular posts from this blog

Python Hiring QnA | Py101

Data Engineer SQL Hiring | 105

DE SQL Hiring Questions and Answers - part 101