The Beginner’s Guide to Acing SQL Interviews for Data Scientists
By: Pedram Ataee
Tags: Data, Sql, Data Science, Careers, Interview

At most data science interviews, your SQL skill will be examined in some way. You must write some SQL queries in your technical interviews and many of them in your day-to-day job. It does not matter whether you work at a small or a big company, SQL programming is an important tool in your toolbox. You can use SQL programming to work with small and huge datasets especially with advanced query engines such as Spark SQL.

Spark (an open-source unified analytics engine for large-scale data processing) has a module named Spark SQL (a distributed SQL query engine) that lets you manage SQL queries in big data efficiently. Databricks, one of the top growing enterprise software to manage data warehouses, has a user-friendly environment to set up Spark SQL engines. So be prepared to learn SQL programming soon in your career.

A data science interview usually has three technical steps: SQL programming, ML development, and an onsite technical interview. The SQL programming and ML development steps are pretty standard these days. The onsite interview varies across different companies. In this article, I aim to help you ace the SQL programming interview.

If you find this article useful, you can subscribe through the link below. This will help me to create high-quality content for you.

The structure of this article is as follows:

Let’s start.

— What are the Basics of SQL Coding?

You should learn the basics of SQL programming from any resource that you are comfortable with. I learned a lot from w3school website, and I highly recommend it check it out later.

1. SELECT

The SELECT statement is used to extract data from a database as follows SELECT column1_name FROM table_name . You can also use * after SELECT if you want to extract everything in the database. The SELECT DISTINCT statement can be used to extract unique values. A column often contains many duplicate values, and sometimes you only need to extract the unique or distinct values.

2. WHERE

The WHERE statement is used to filter records from a database as follows SELECT column1_name FROM table_name WHERE condition; It returns only those records that fulfill the condition written after that. You can use various operators in the condition such as: > , = , IN , LIKE , or BETWEEN . You can also combine several conditions with AND , OR , and NOT operators to narrow down the filter.

3. ORDER BY

The ORDER BY statement is used to sort the result in ascending ASC or descending DESC order. By default, it sorts the records in ascending order though. You can try the following code to extract everything from a table ordered by column1_name and column2_name : SELECT * FROM table_name ORDER BY column1_name ASC, columne2_name DESC

4. COUNT

The COUNT() function returns the number of rows that matches a specified criterion as follows: SELECT COUNT(column_name) FROM table_name WHERE condition; You can try other SQL functions, instead of COUNT , such as AVG or SUM to return the average value or the total sum of a numeric column.

5. GROUP BY

The GROUP BY statement extracts rows that have the same values in a column and groups them into summary rows, like "find the number of students in each school". The GROUP BY statement is often used with aggregate functions such as COUNT() , MAX() , MIN() , SUM() , AVG() to group the results. You can check the code below.

SELECT column_name(s)

FROM table_name

WHERE condition

GROUP BY column_name(s)

ORDER BY column_name(s);

There are more SQL commands that you can learn from w3school such as JOIN or CASE . A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Or, the CASE statement goes through several conditions and returns a value when the first condition is met exactly similar to if-then-else statement in other programming languages.

Photo by Olav Ahrens Røtne on Unsplash

— A Simple Example of a SQL Problem

The problem below is taken from Leetcode, a fantastic website where you can practice your coding skills. You can find many more problems on that website.

Problem: We have a table named Activity that contains 4 fields from a series of gamers: palyer_id , device_id , event_date and games_played . Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using the same device. Write an SQL query that reports the first login date for each player.

Solution: As you can see, the solution uses commands that you learn above.

SELECT

player_id

MIN(event_date) AS first_login

FROM Activity

GROUP BY player_id

Photo by Anton Maksimov juvnsky on Unsplash

— A Useful Technique: “Parametrized Query”

When you must write a large number of similar queries, you can use a technique called “parameterized query”. This will help you write more efficient code and also show your expertise in programming. Here, I describe how to write parameterized SQL queries using Python.

Let’s say you want to write a COUNT query that can be used with different fields and tables. In this case, you can save part 1 in the code below under, for example, count.txt . Then, you must parse (load and fill) the parameterized query in Python using part 2, the code coming right after.

------------------------------------------------------

# PART 1 (SQL) - PARAMETRIZED QUERY saved as count.txt

------------------------------------------------------

SELECT {var}, count({var}) as count

FROM {table_name}

GROUP BY {var}

ORDER BY count DESC ---------------------------------

# PART 2 (PYTHON) - QUERY PARSER

---------------------------------

class Query:

def __init__(self, table_name, var):

self.table_name = table_name

self.var = var

self.parsed = None def parser(self):

file_path_query = os.path.join(FILE_DIR, 'count.txt')

with open(file_path_query, 'r') as file:

template = file.read().replace('

', ' ')

self.parsed = template.format(table_name=self.table_name,

var=self.var)

— Last Words

A SQL programming interview can be live or offline. If it is offline, you will be evaluated based on whether your code is executable or not. Otherwise, you will be evaluated based on the code quality in general and how well you can communicate. Let’s dig into each of them.

Code Quality

The interviewers will judge your code quality (and, certainly not you!) based on several angles. First, they want to see whether the code is executable without any syntax error. Then, they check whether your code is clean and concise. Third, the interviewer checks whether you considered edge cases. If you can not write clean code or consider edge cases in a timebox, make sure to be aware of the best practices and share them with your interviewer. In the end, they check whether your solution is optimized in terms of efficiency. For example, you could get the same result using one Join or using three Join. The former is more optimized.

Communication

In every interview, it is important to have effective communication with your interviewer. What does effective communication mean though? The first step in effective communication is to clearly share your thought process with your interviewer before diving into coding. Plus, you must be able to elaborate your reasoning for each choice of yours. I can not emphasize more how important is the power of sharing thought processes and elaboration on reasoning. I can work with a person whose code is not executable in the coding interview but can not work with whom fail on communication.

Thanks for Reading!

If you like this post and want to support me…