Top 30 SQL Query Interview Questions

Top 30 SQL Query Interview Questions
  • Author Avatar
    Written by:

    Nathan Rosidi

Today we’re having a look at the top 30 SQL query interview questions and concepts that you must prepare for an SQL coding interview.

Last summer we published the ultimate guide to the SQL Interview Questions You Must Prepare. In it, we covered all the SQL areas that are, from our experience, required by the interviewers. These, along with coding, include theoretical knowledge about SQL and databases.

Now we will concentrate only on coding skills. In a way, it’s a sequel to the ultimate guide mentioned above, with this one being dedicated only to writing queries in SQL.

This singular skill will be here divided into six distinct technical concepts which will be used to solve, in total, 30 business problems.

We’ll start with the easiest, add one concept to the previous one(s) and end up with the most complex queries that include most or all of the concepts at the same time. With five questions in each category, this means covering 30 SQL query interview questions.

Here are the concepts we’ll talk about:

  • Aggregating, Grouping, and Ordering Data
  • Filtering Data
  • Joins & Unions
  • Subqueries & CTEs
  • Window Functions
  • Text & Date Manipulation

Aggregating, Grouping, and Ordering Data

SQL Questions for Aggregating, Grouping, and Ordering Data

These three SQL concepts usually come hand in hand. When you’re aggregating data, it usually means you’ll have to group it, too, and that way provide data with more insight and in a presentable form. Ordering data is also one of the tools to make data more user-friendly.

SQL Query Interview Question #1: Total Number Of Housing Units

The Airbnb question gives you the following information:

EasyID 10167

Find the total number of housing units completed for each year. Output the year along with the total number of housings. Order the result by year in ascending order.

Note: Number of housing units in thousands.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/10167-total-number-of-housing-units

The dataset consists of the table housing_units_completed_us with the following columns:

Table: housing_units_completed_us
Loading Dataset

The completed housing units are recorded according to the region. If you sum all the regions you get all the completed units. If you group data by the year and order it by the year ascendingly, you’ll get the correct result in the desired format.

Here’s the solution and its output.

SELECT year,
       SUM(south + west + midwest + northeast)  AS n_units
FROM housing_units_completed_us
GROUP BY 1
ORDER BY 1
Go to the question on the platformTables: housing_units_completed_us

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

yearn_units
20061979.5
20071503
20081119.5
2009794.5
2010651.7
2011585
2012649
2013764.4
2014462.8

SQL Query Interview Question #2: Find the Number of Entries per Star

It’s a Yelp’s question that asks:

EasyID 10054

Find the number of entries per star. Output each number of stars along with the corresponding number of entries. Order records by stars in ascending order.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/10054-find-the-number-of-entries-per-star

Here you’ll also have to aggregate data, but this time using the COUNT() function. Output the columns question asks you to, then group and order data much as in the previous example.

Why don’t you use those hints in the widget below?

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Your output should look like the one below.

starsn_entries
?5
17
211
316
433
534

SQL Query Interview Question #3: Find the Average Number of Stars for Each State

This is again a question by Yelp:

EasyID 10052

Find the average number of stars for each state. Output the state name along with the corresponding average number of stars.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/10052-find-the-average-number-of-stars-for-each-state

Like in the previous questions, you have only one table at your disposal. Again, output only one column along with the aggregate values. Here you’ll have to use the AVG() function to get the solution. Also, the question doesn’t ask you to order data, so no need to use the ORDER BY clause.

Use the widget and hopefully you can get the output shown below it.

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Your output should look like this:

stateaverage_stars
PA3.7
QC4.33
ON3.78
EDH5
IL5
WI4.75
NC3.29
NV3.25
OH3.75
AZ3.82
BW4.17

SQL Query Interview Question #4: Find the Total Costs and Total Customers Acquired in Each Year

At Uber you could get a question like this:

EasyID 10009

Find the total costs and total customers acquired in each year. Output the year along with corresponding total money spent and total acquired customers.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/10009-find-the-total-costs-and-total-customers-acquired-in-each-year

This time you’ll be using the SUM() function two times: first to get the total costs and the second time to get the total customers. You need to show this data grouped on an annual level. No other calculations or ordering data is required.

The expected output has three columns and three rows:

yeartotal_money_spenttotal_customers_acquired
2017432920013400
2018171105512350
20191137300011751

Try to write the solution.

Go to the question on the platformTables: uber_advertising

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #5: Average Number Of Points

The last question in this category is by ESPN.

MediumID 9965

Find the average number of points earned per quarterback appearance in each year. Each row represents one appearance of one quarterback in one game. Output the year and quarterback name along with the corresponding average points. Sort records by the year in descending order.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9965-average-number-of-points

This example asks you to use the AVG() aggregate function. Since you need to output the year and the quarterback’s appearance, you’ll also have to group by two rows, not only one. You’ll have to order the output by two rows, too. This time it’s in descending order, unlike the previous questions.

Here’s the output.

yearqbaverage_points
2016Aaron RodgersA. Rodgers27
2015Aaron RodgersA. Rodgers23
2016Ben RoethlisbergerB. Roethlisberger25.43
2015Ben RoethlisbergerB. Roethlisberger28.42
2016Cam NewtonC. Newton23.93
2015Cam NewtonC. Newton31.25
2016Carson PalmerC. Palmer25.67
2015Carson PalmerC. Palmer29.8
2016Dak PrescottD. Prescott27.93
2016Drew BreesD. Brees29.31
2015Drew BreesD. Brees25.73
2016Drew StantonD. Stanton33
2016Jimmy GaroppoloJ. Garoppolo27
2016Joe FlaccoJ. Flacco21.44
2015Joe FlaccoJ. Flacco22.6
2015Josh FreemanJ. Freeman30
2016Marcus MariotaM. Mariota23.8
2015Marcus MariotaM. Mariota19.8
2016Matt RyanM. Ryan33.75
2015Matt RyanM. Ryan21.19
2016Philip RiversP. Rivers25.62
2015Philip RiversP. Rivers20
2016Tom BradyT. Brady30
2015Tom BradyT. Brady29.06
2016Tyrod TaylorT. Taylor25.79
2015Tyrod TaylorT. Taylor23.7

Do you think you can get it by using the hints we gave you?

Go to the question on the platformTables: qbstats_2015_2016

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Filtering Data and Conditional Statements

SQL Questions for Filtering Data and Conditional Statements

What we mean by filtering data is only the part of data that specifies set criteria. Even though using JOINs can also technically filter data, here we want to talk about the WHERE and HAVING clauses.

Conditional statements in PostgreSQL are represented through the CASE WHEN statements.

SQL Query Interview Question #6: Patrons Who Renewed Books

The City of San Francisco is interested in patrons and books.

EasyID 9931

Find the number of patrons who renewed books at least once but less than 10 times in April 2015. Each row is an unique patron.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9931-patrons-who-renewed-books

Here we have a table named library_usage with the columns:

library_usage

Table: library_usage
Loading Dataset

Now, to answer the question’s requirements, we’ll use something we already know. The COUNT() function, that is. We’ll use it to count rows which will equal to number of patrons. There’s only one table and it will appear in the FROM clause. The question doesn’t ask to output all patrons. No, the output must show patrons whose total renewals are between one and nine. These renewals all have to be in April 2015. To filter data in such way we’ll have to use three WHERE clauses:

SELECT count(*) AS n_patrons
FROM library_usage
WHERE total_renewals BETWEEN 1 AND 9
  AND circulation_active_month = 'April'
  AND circulation_active_year = '2015'

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

The output is one number:

n_patrons
3

It means there are three patrons that renewed books less than ten times in April 2015.

SQL Query Interview Question #7: Find Out Search Details for Apartments Designed for a Sole-Person Stay

Airbnb is interested in knowing the answer to this question:

EasyID 9615

Find the search details for apartments where the property type is Apartment and the accommodation is suitable for one person.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9615-find-out-search-details-for-apartments-designed-for-a-sole-person-stay

Here you have to output all the columns from the table. However, the rows have to be filtered. Use the WHERE clause to find the accommodation that is for only one person and that is classified as an apartment in the table.

Go to the question on the platformTables: airbnb_search_details

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

And these are the first few rows of the output you should aim for.

idpriceproperty_typeroom_typeamenitiesaccommodatesbathroomsbed_typecancellation_policycleaning_feecityhost_identity_verifiedhost_response_ratehost_sinceneighbourhoodnumber_of_reviewsreview_scores_ratingzipcodebedroomsbeds
5059214431.75ApartmentPrivate room{TV,"Wireless Internet","Air conditioning",Kitchen,"Free parking on premises",Breakfast,Heating,"Smoke detector","Carbon monoxide detector","First aid kit","Fire extinguisher",Essentials,Shampoo,"Lock on bedroom door",Hangers,"Laptop friendly workspace","Private living room"}13Real BedstrictFALSENYCf2014-03-14Harlem01003021
10923708340.12ApartmentPrivate room{TV,Internet,"Wireless Internet","Air conditioning",Kitchen,"Pets live on this property",Cat(s),"Buzzer/wireless intercom",Heating,"Family/kid friendly",Washer,"Smoke detector","Carbon monoxide detector","First aid kit","Fire extinguisher",Essentials}11Real BedstrictFALSENYCt100%2014-06-30Harlem166911003111
1077375400.73ApartmentPrivate room{"Wireless Internet",Heating,"Family/kid friendly","Smoke detector","Carbon monoxide detector","Fire extinguisher",Essentials,Shampoo,Hangers,Iron,"Laptop friendly workspace","translation missing: en.hosting_amenity_50"}11Real BedmoderateTRUENYCt2015-04-04Sunset Park11001122011
13121821501.06ApartmentPrivate room{TV,"Cable TV",Internet,"Wireless Internet","Air conditioning",Kitchen,Heating,"Smoke detector","First aid kit",Essentials,Hangers,"Hair dryer",Iron,"Laptop friendly workspace"}11Real BedflexibleFALSENYCf2014-09-20Park Slope01121511
19245819424.85ApartmentPrivate room{Internet,"Wireless Internet",Kitchen,"Pets live on this property",Dog(s),Washer,Dryer,"Smoke detector","Fire extinguisher"}11Real BedmoderateFALSESFt2010-03-16Mission District12909411011
11157369409.43ApartmentPrivate room{TV,Internet,"Wireless Internet","Air conditioning",Kitchen,Heating,Essentials,Shampoo,Iron,"Laptop friendly workspace"}11Real BedflexibleTRUENYCt2014-06-30Harlem01002611
12386097366.36ApartmentShared room{TV,Internet,"Wireless Internet","Air conditioning",Kitchen,Heating,"Smoke detector",Essentials,Shampoo}11Real BedmoderateTRUENYCt100%2015-10-02Harlem18961002712

SQL Query Interview Question #8: Departments With Less Than 4 Employees

Amazon is interested in knowing the answer to this question:

MediumID 9860

Find departments with less than 4 employees.

Output the department along with the corresponding number of workers.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9860-find-departments-with-less-than-4-employees

They give you the table worker:

worker

Table: worker
Loading Dataset

To answer the question, you’ll again have to filter data. This time you need to use HAVING instead of WHERE. They work the same in terms of syntax, but the main difference is WHERE is used before while HAVING is used after the GROUP BY clause. It’s also important to note that you need to use the COUNT() function two times: once in the SELECT statement and the second time in the HAVING clause.

Or translated to an SQL code:

SELECT 
    department,
    COUNT(worker_id) AS num_of_workers 
FROM worker
GROUP BY 
    department 
HAVING 
    COUNT(worker_id) < 4

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Run it to get the output we’re looking for.

departmentnum_of_workers
Account3

This is the department with less than four employees.

SQL Query Interview Question #9: Departments With 5 Employees

Now it’s your turn to use the HAVING() clause and answer the Salesforce question:

Last Updated: May 2019

EasyID 9911

Find departments with at more than or equal 5 employees.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9911-departments-with-5-employees

It’s not that different from the previous question. This time, you don’t need to show the number of employees, only the departments with five or more of them. It’s again the COUNT() function in the HAVING() clause.

Show us your solution here:

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

If you get it right, your solution will be this.

department
Sales

SQL Query Interview Question #10: Make a Report Showing the Number of Survivors and Non-survivors by Passenger Class

This interesting question is asked by Google:

MediumID 9881

Make a report showing the number of survivors and non-survivors by passenger class. Classes are categorized based on the pclass value as:

• First class: pclass = 1 • Second class: pclass = 2 • Third class: pclass = 3

Output the number of survivors and non-survivors by each class.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9881-make-a-report-showing-the-number-of-survivors-and-non-survivors-by-passenger-class

The table titanic has these columns:

titanic

Table: titanic
Loading Dataset

This question does want us to filter data, in a way. It wants us to find certain data and allocate values to these data. It gives us a hint that we’ll have to use the CASE WHEN clause. We need to take the column pclass and check the values in it. If the value is 1, then it will be recorded as 1 in the new column first_class. If there’s value 2 in the column pclass, the value of 1 has to appear in the new column second_class. The same principle applies to the third class.

After you get this, you only need to the sum these values using the SUM() function. The data need to be grouped so that it shows survivors and non-survivors, which is shown in the column survived.

Finally, you’ll get this code:

SELECT survived,
       sum(CASE
               WHEN pclass = 1 THEN 1
               ELSE 0
           END) AS first_class,
       sum(CASE
               WHEN pclass = 2 THEN 1
               ELSE 0
           END) AS second_class,
       sum(CASE
               WHEN pclass = 3 THEN 1
               ELSE 0
           END) AS third_class
FROM titanic
GROUP BY survived

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

It results in the two-row output showing the survivors and non-survivors according to class.

survivedfirst_classsecond_classthird_class
011642
1101219

There were 11 non-survivors in the first class, six in the second class, and 42 in the third class. Of the survivors, ten were traveling in the first class. The second and the third class had 12 and 19 survivors, respectively.

JOINs and UNIONs

SQL Questions for JOINs and UNIONs

The following topics we’ll cover here is joining tables and merging query outputs.

As you already know, SQL JOINs are used to combine data from two or more tables, thus allowing much more possibilities in querying data than when working with only one table.

We use UNION and UNION ALL to merge the outputs of two or more SELECT statements. For this merging to work, the outputs of the queries must have the same number of columns and their data types have to be of the same data type. The difference between them is that UNION ALL merges all the records, including duplicate, while UNION keeps unique records.

SQL Query Interview Question #11: Find the Team Division of Each Player

The interview question which we’ll use to show you how the JOINs work is the one by ESPN.

EasyID 9884

Find the team division of each player. Output the player name along with the corresponding team division.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9884-find-the-team-division-of-each-player

The data is divide into two tables.

Table: college_football_teams
Loading Dataset

Table: college_football_players
Loading Dataset

How do we approach this question? We select the column player_name from the second table and the column division from the first table. To get the data from these columns, we need to INNER JOIN the tables on the columns school_name from both tables. There’s nothing else to this solution.

SELECT players.player_name,
       teams.division
FROM college_football_teams teams
INNER JOIN college_football_players players ON teams.school_name = players.school_name
Go to the question on the platformTables: college_football_teams, college_football_players

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

player_namedivision
Shakim AlonzoFBS (Division I-A Teams)
Javon HarrisonFBS (Division I-A Teams)
Jacob GiltrowFBS (Division I-A Teams)
Blake AnnenFBS (Division I-A Teams)
Travis JohnsonFBS (Division I-A Teams)
Nate ColeFBS (Division I-A Teams)
Chris BurtonFBS (Division I-A Teams)
Max MorrisonFBS (Division I-A Teams)
DJ DowdyFBS (Division I-A Teams)
Alex ChisumFBS (Division I-A Teams)
Andre CuretonFBS (Division I-A Teams)
Parker EhingerFBS (Division I-A Teams)
Austen BujnochFBS (Division I-A Teams)
Kevin SchloemerFBS (Division I-A Teams)
Justin MurrayFBS (Division I-A Teams)
Ryan LeahyFBS (Division I-A Teams)
Garrett CampbellFBS (Division I-A Teams)
Eric LefeldFBS (Division I-A Teams)
Brandon MitchellFBS (Division I-A Teams)
Dominic MainelloFBS (Division I-A Teams)
Kyle WilliamsonFBS (Division I-A Teams)
David NiehausFBS (Division I-A Teams)
Connor DonniniFBS (Division I-A Teams)
Tyreek BurwellFBS (Division I-A Teams)
Will SteurFBS (Division I-A Teams)
Dan SpragueFBS (Division I-A Teams)
Cory KeeblerFBS (Division I-A Teams)
Kirk WillisFBS (Division I-A Teams)
Sam LongoFBS (Division I-A Teams)
Deyshawn BondFBS (Division I-A Teams)
Dwight JacksonFBS (Division I-A Teams)
Sam GeraciFBS (Division I-A Teams)
Clemente CasseusFBS (Division I-A Teams)
Mark WilsonFBS (Division I-A Teams)
Andrew GantzFBS (Division I-A Teams)
Franklin BruscianelliFBS (Division I-A Teams)
Elijah ShulerFBS (Division I-A Teams)
Greg BlairFBS (Division I-A Teams)
Alex PaceFBS (Division I-A Teams)
Anthony KingFBS (Division I-A Teams)
Jeff LucFBS (Division I-A Teams)
Jon VincentFBS (Division I-A Teams)
Mitch MeadorFBS (Division I-A Teams)
Ey'Shawn McClainFBS (Division I-A Teams)
Corey MasonFBS (Division I-A Teams)
Nick TempleFBS (Division I-A Teams)
Jared GoldenFBS (Division I-A Teams)
Kevin HylandFBS (Division I-A Teams)
Kevin BrownFBS (Division I-A Teams)
Kyle NutterFBS (Division I-A Teams)
EJ JuniorFBS (Division I-A Teams)
Mason AntounFBS (Division I-A Teams)
Lindsay CrookFBS (Division I-A Teams)
Marcus FosterFBS (Division I-A Teams)
Josh RussFBS (Division I-A Teams)
Dylan CoombsFBS (Division I-A Teams)
Tim HeltonFBS (Division I-A Teams)
Solomon TentmanFBS (Division I-A Teams)
Zach HiggenbothamFBS (Division I-A Teams)
Darren DostonFBS (Division I-A Teams)
Andre JonesFBS (Division I-A Teams)
Drake BrunsFBS (Division I-A Teams)
Braxton LaneFBS (Division I-A Teams)
Rob RiceFBS (Division I-A Teams)
Arryn ChenaultFBS (Division I-A Teams)
John LloydFBS (Division I-A Teams)
Chris BurrellFBS (Division I-A Teams)
Eric WilsonFBS (Division I-A Teams)
Hosey WilliamsFBS (Division I-A Teams)
Zach EdwardsFBS (Division I-A Teams)
Rodriguez MooreFBS (Division I-A Teams)
Tshumbi JohnsonFBS (Division I-A Teams)
Shaq WashingtonFBS (Division I-A Teams)
Derek CoxFBS (Division I-A Teams)
Tyler CogswellFBS (Division I-A Teams)
Jeremy GravesFBS (Division I-A Teams)
Michael ColosimoFBS (Division I-A Teams)
Chris MooreFBS (Division I-A Teams)
Tony MilianoFBS (Division I-A Teams)
Grant ColemanFBS (Division I-A Teams)
Leviticus PayneFBS (Division I-A Teams)
Brendon KayFBS (Division I-A Teams)
Deven DraneFBS (Division I-A Teams)
Jordan LuallenFBS (Division I-A Teams)
Dionne Thrweatt-VassarFBS (Division I-A Teams)
Patrick CoyneFBS (Division I-A Teams)
Adrian WittyFBS (Division I-A Teams)
Gunner KielFBS (Division I-A Teams)
Mike TysonFBS (Division I-A Teams)
Tion GreenFBS (Division I-A Teams)
Anthony McClungFBS (Division I-A Teams)
Aaron BrownFBS (Division I-A Teams)
Mark BarrFBS (Division I-A Teams)
Munchie LegauxFBS (Division I-A Teams)
Howard WilderFBS (Division I-A Teams)
Johnny HoltonFBS (Division I-A Teams)
Bennie ConeyFBS (Division I-A Teams)
Trenier OrrFBS (Division I-A Teams)
Mekale McKayFBS (Division I-A Teams)
Ralph AbernathyFBS (Division I-A Teams)

Let’s try another one!

SQL Query Interview Question #12: Sales With Valid Promotion

Here’s a question by Meta/Facebook:

Last Updated: October 2021

EasyID 2069

The marketing manager wants you to evaluate how well the previously ran advertising campaigns are working.

Particularly, they are interested in the promotion IDs from the online_promotions table.

Calculate the percentage of orders in the online_orderstable that used a promotion from the online_promotions table.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2069-sales-with-valid-promotion

Here you’ll again have to JOIN two tables. This time it’s the LEFT JOIN, but it works the same way as the INNER JOIN syntax-wise. To get the percentage, you’ll have to use the COUNT() function both in the numerator and the denominator. Also, convert the result and multiply it by 100 to get the percentage with decimal points.

Here’s what your code needs to do.

percentage
75.86

Write the solution in the widget.

Go to the question on the platformTables: online_promotions, online_orders

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #13: Transactions by Billing Method and Signup ID

Here’s a bit more complicated JOIN question by Noom.

Last Updated: April 2021

MediumID 2031

Provide a list of signups with a transaction start date earlier than May 2020.

For these users, calculate the average transaction value using only transactions that occurred before May 2020, grouped by billing cycle.

The output should include the billing cycle, signup ID, and average transaction amount, sorted by billing cycle in reverse alphabetical order and signup ID in ascending order

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2031-transactions-by-billing-method-and-signup-id

The solution has to use the AVG() aggregate function, no doubt. Also, you’ll want to use two INNER JOINs here, because you need to output data from all three available tables. The question tells you to filter data according to start date. Calculate ten months before March 2021 and use the result in the WHERE clause. Also, you’ll need to group data by the billing cycle and signup_id. When you order data, you need to do it both ascendingly and descendingly.

Try to write your own solution and see if it returns the same few rows as the result below.

billing_cyclesignup_idavg_amt
quarterly10024.9
quarterly10124.9
quarterly10324.9
quarterly10924.9
quarterly11024.9
quarterly11424.9
quarterly11624.9
quarterly11924.9
quarterly12024.9
quarterly12424.9
quarterly12624.9
quarterly13124.9
quarterly13524.9
quarterly14024.9
quarterly14224.9
monthly1029.9
monthly1059.9
monthly1089.9
monthly1129.9
monthly1229.9
monthly1239.9
monthly1259.9
monthly1329.9
monthly1339.9
monthly1379.9
annual106109.9
annual107109.9
annual111109.9
annual113109.9
annual117109.9
annual118109.9
annual121109.9
annual129109.9
annual130109.9
annual144109.9

SQL Query Interview Question #14: Make the Friends Network Symmetric

We didn’t talk about the UNION and UNION ALL, but this will change with the next two questions. The first one is by Google.

MediumID 9813

Make the friends network symmetric. For example, if 0 and 1 are friends, have the output contain both 0 and 1 under 1 and 0 respectively.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9813-make-the-friends-network-symmetric

The question wants you to only use the table google_friends_network and its two columns.

Table: google_friends_network
Loading Dataset

This is a rather easy question to solve if you know how to use UNION. All you got to do is output the user ID and the friend ID with the first SELECT statement. The second SELECT statement will be the same, only the order of the columns in the output will be reversed. To get these two results in one output, you’d want to use the UNION operator like this:

SELECT user_id,
       friend_id
FROM google_friends_network
UNION
SELECT friend_id AS user_id,
       user_id AS friend_id
FROM google_friends_network
Go to the question on the platformTables: google_friends_network

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

It should return the following result.

user_idfriend_id
20
02
307
330
303
121
05
80
01
62
230
95
76
302
73
47
67
15
30
730
04
59
210
81
89
50
60
26
51
03
06
10
37
40
91
18
19
112
08
98
102
74

The users 0 and 2, for example, appear both as users and friend, which is the point. The same is true for all other users.

SQL Query Interview Question #15: Find Employees in the HR Department and Output the Result With One Duplicate

Here we’ll show the question asked by Amazon.

MediumID 9858

Generate a list of employees who work in the HR department, including only their first names and department in the output. Each employee should appear twice in the list, meaning their first name and department should be duplicated in the output.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9858-find-employees-in-the-hr-department-and-output-the-result-with-one-duplicate

The approach to the solution should be similar to the example above. This time you’ll use UNION ALL instead of UNION. Why? Because the question asks you to return the duplicate results. Both SELECT statements that you’ll write should be exactly the same because they select two columns from the table. Also, you need only data from the HR department, so use that info in the WHERE clause.

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Did you get this result?

first_namedepartment
MonikaHR
VishalHR
MoeHR
JaiHR
JuraHR
MonikaHR
VishalHR
MoeHR
JaiHR
JuraHR

Subqueries and CTEs

SQL Interview Questions for Subqueries and CTEs

We’re building up your readiness for the SQL interview, so we’ll freely start using all the previous concepts. You should be comfortable with them by now.

The subqueries are the queries written in the other query. They usually appear in the SELECT, FROM, and WHERE.

The SQL Common Table Expressions or CTEs are the tidier version of subqueries. They result in a table similar to the temporary table. This table isn’t stored anywhere and can be accessed only after the CTE is executed. One of the main benefits compared to the subqueries is that the CTEs are reusable and can be referenced in the coming SELECT statement like any other table.

SQL Query Interview Question #16: Successfully Sent Messages

The first question we’re going to show here is one by Meta/Facebook.

Last Updated: June 2018

MediumID 9777

Find the ratio of successfully received messages to sent messages.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9777-successfully-sent-messages

The question gives you two tables to work with.

Table: facebook_messages_sent
Loading Dataset

Table: facebook_messages_received
Loading Dataset

Now we have to use the subqueries. Both will be used in the same SELECT statement: one as the numberer the other one as the numerator, the other one as the denominator. Yes, we’re going to divide one subquery with the another one.

SELECT
  (SELECT CAST(COUNT(*) AS decimal)
   FROM facebook_messages_received)/
  (SELECT COUNT(*)
   FROM facebook_messages_sent)
Go to the question on the platformTables: facebook_messages_sent, facebook_messages_received

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

One query will return the number of the received messages by using the COUNT() function. Its result will be:

Answer to SQL Question to find Successfully Sent Messages

The other subquery will also use the COUNT() function, but to return the number of the sent messages:

Answer 2 to SQL Question to find Successfully Sent Messages

Run together as the question solution and they will return this output.

?column?
0.6

Really, three divided by 5 is 0.6.

SQL Query Interview Question #17: Find the Most Profitable Company in the Financial Sector of the Entire World Along With Its Continent

If you want to work at Forbes, you should expect this question.

EasyID 9663

Find the most profitable company from the financial sector. Output the result along with the continent.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9663-find-the-most-profitable-company-in-the-financial-sector-of-the-entire-world-along-with-its-continent

To solve it, you’ll again need to use the subquery. This time, it’ll be a subquery in the WHERE clause. You should use it to get the highest profit in the financial sector. The other criteria in the outer query’s WHERE clause should also be the company’s sector.

Use the widget and try to get the following result.

Go to the question on the platformTables: forbes_global_2010_2014

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

companycontinent
ICBCAsia

SQL Query Interview Question #18: Top 10 Songs

Here’s an interview question by Spotify.

MediumID 9743

Find the number of unique songs of each artist which were ranked among the top 10 over the years. Order the result based on the number of top 10 ranked songs in descending order.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9743-top-10-songs

To solve this question, use the COUNT() function. It will get you the distinct songs by the artists. This time you’ll not be listing the table in the FROM clause, but you’ll write a subquery there. Use it to find artists and their songs that were ranked 10 or higher. In the main SELECT statement you’ll need to group and order data like this, at least partially.

artisttop10_songs_count
Elvis Presley9
Mariah Carey7
Usher6
Whitney Houston5
Beatles5
Elton John5
Toni Braxton4
Boyz II Men4
TLC4
Madonna4
Rod Stewart4
Bee Gees4
Katy Perry4
Paul McCartney4
Michael Jackson4
Beyonce4
Rihanna3
Paula Abdul3
Lady Gaga3
Diana Ross3
Ludacris3
Gwen Stefani3
Lionel Richie3
Ace Of Base3
The Black Eyed Peas3
Nelly3
Kelly Clarkson3
En Vogue3
Andy Gibb3
Dean Martin3
John Oates3
Maroon 53
Alicia Keys3
Temptations3
matchbox twenty3
Daryl Hall3
Kanye West3
Taio Cruz2
Color Me Badd2
Akon2
Captain and Tennille2
Bette Midler2
Perry Como2
Bobby Vinton2
Phil Collins2
Timbaland2
John Cougar2
Rolling Stones2
Ashanti2
Mac Davis2
Macklemore2
Puff Daddy2
T-Pain2
Mama's and The Papa's2
Train2
Association2
Wham!2
Justin Timberlake2
Righteous Brothers2
Wings2
R. Kelly2
Celine Dion2
Roberta Flack2
Everly Brothers2
50 Cent2
Barbra Streisand2
John Denver2
Monica2
Roy Orbison2
Ryan Lewis2
Monkees2
Beach Boys2
Savage Garden2
Mr. Mister2
Sean Paul2
Fergie2
Fleetwoods2
Nelly Furtado2
Flo Rida2
Chicago2
Simon and Garfunkel2
Bobby Darin2
Nicki Minaj2
Jackson 52
Bruno Mars2
Four Tops2
Olivia Newton-John2
Sly and The Family Stone2
Snoop Dogg2
Chris Brown2
Frankie Valli2
Janet2
OutKast2
Pat Boone2
Janet Jackson2
Christina Aguilera2
Chubby Checker2
Jay-Z2
Supremes2
Donna Summer2
Survivor2
Ciara2
Bryan Adams2
Fifth Dimension1
Florida Georgia Line1
Foreigner1
Foundations1
Four Seasons1
Frankie Avalon1
Frank Sinatra1
Freda Payne1
Freddy Fender1
fun.1
Gale Garnett1
Gary Wright1
George Harrison1
George Michael1
Gilbert O'Sullivan1
Glen Campbell1
Gloria Gaynor1
Gnarls Barkley1
Gogi Grant1
GoonRock1
Gotye1
Grand Funk Railroad1
Green Day1
Gregory Abbott1
Guess Who1
Guns N' Roses1
Guy Mitchell1
Hayley Williams1
Heart1
Herb Alpert1
Herman's Hermits1
Hi-Five1
Highwaymen1
Hoobastank1
Hot1
Hugo Montenegro1
Human League1
Imagine Dragons1
Impressions1
INXS1
Irene Cara1
James Blunt1
James Ingram1
Jamie Foxx1
Janelle Monae1
Ja Rule1
Jason Mraz1
Jennifer Lopez1
Jewel1
J. Frank Wilson and The Cavaliers1
J. Geils Band1
Jim Croce1
Jimmy Dorsey1
Jimmy Gilmer and The Fireballs1
Jimmy Jones1
Jim Reeves1
Jive Five1
Joan Jett and The Blackhearts1
Joe Dowell1
Joe Tex1
John Lennon1
Johnnie Taylor1
Johnny Horton1
Johnny Preston1
Johnny Rivers1
Jon Bon Jovi1
Jon Secada1
Jordin Sparks Duet With Chris Brown1
Kay Starr1
K-Ci and JoJo1
Ke$ha1
Keith Sweat1
Kelly Rowland1
Kenny Loggins1
Kenny Nolan1
Kenny Rogers1
Kid Rock1
Kiki Dee1
Kimbra1
Kim Carnes1
Klymaxx1
Knack1
Kool and The Gang1
Krayzie Bone1
Kris Kristofferson1
Kris Kross1
Lady Antebellum1
Lauren Bennett1
LeAnn Rimes1
Lenny Kravitz1
Leona Lewis1
Les Baxter1
Lifehouse1
Lil Jon1
Lil Wayne1
Linkin Park1
Lipps, Inc.1
Lisa Loeb1
Little Eva1
Little Stevie Wonder1
Lloyd Price1
LMFAO1
Lonestar1
Los Del Rio1
Louis Armstrong1
Love Unlimited Orchestra1
Lulu1
Manhattans1
Mario1
Mario Winans1
Mark Dinning1
Mark Morrison1
Marvin Gaye1
Mary MacGregor1
Mary Wells1
Melanie1
Men At Work1
MFSB1
Michael McDonald1
Michael Sembello1
Milli Vanilli1
Missy Elliott1
Montell Jordan1
Mr. Acker Bilk1
Nancy Sinatra1
Natasha Bedingfield1
Nayer1
Neil Sedaka1
Nelson Riddle1
Next1
Ne-Yo1
Nickelback1
Nilsson1
Nine Stories1
Olivia1
One Direction1
OneRepublic1
Osmonds1
Otis Redding1
Patsy Cline1
Patti Austin1
Patti Labelle1
Paula Cole1
Paul and Paula1
Paul Anka1
Paul Mauriat1
Paul McCoy1
Paul Simon1
P. Diddy1
Peaches and Herb1
Percy Faith1
Perez Prado1
Petey Pablo1
Petula Clark1
Pharrell1
Pink Floyd1
Pitbull1
Plain White T's1
Platters1
Player1
Poison1
Police1
Prince1
Puddle Of Mudd1
Queen1
Raiders1
Rare Earth1
Rascals1
Ray Charles1
Ray Dalton1
Ray Parker Jr.1
Ray Stevens1
Real McCoy1
Redbone1
Red Hot Chili Peppers1
REO Speedwagon1
Rick Astley1
Rick Springfield1
Ricky Martin1
Rita Coolidge1
Robbie Nevil1
Robert John1
Robert Palmer1
Robin Thicke1
Roxette1
Sammy Davis Jr.1
Sam The Sham and The Pharaohs1
Sara Bareilles1
Seal1
Sensations1
Sgt. Barry Sadler1
Shai1
Shakira1
Shania Twain1
Shelley Fabares1
Sheryl Crow1
Shirelles1
Silk1
Sinead O'Connor1
Sir Mix-a-Lot1
Sixpence None The Richer1
Skeeter Davis1
Sleepy Brown1
Slim Thug1
Snow1
Sonny James1
Spice Girls1
Starship1
Static Major1
Steve Miller Band1
Steve Winwood1
Stevie Wonder1
Sting1
String-a-longs1
Sugar Ray1
Surface1
SWV1
Tab Hunter1
Tag Team1
Taylor Swift1
Tears For Fears1
Terror Squad1
Terry Jacks1
The All-American Rejects1
The Calling1
Thelma Houston1
The Miracles1
The Pussycat Dolls1
The Wanted1
Three Dog Night1
T.I.1
Tiffany1
Timmy T1
Tina Turner1
Tom Jones1
Tommy Edwards1
Tommy James and The Shondells1
Tommy Roe1
Tony Orlando and Dawn1
Tony Rich Project1
Tracy Chapman1
Turtles1
UB401
Vanessa Carlton1
Vanessa Williams1
Van Halen1
Village People1
Village Stompers1
Walter Murphy and The Big Apple Band1
Wanz1
Wayne Newton1
We Five1
Whitesnake1
Wilbert Harrison1
Wild Cherry1
will.i.am1
Will To Power1
Wilson Phillips1
Wiz Khalifa1
Wreckx-N-Effect1
Wyclef Jean1
Yes1
Young Jeezy1
Young Rascals1
3 Doors Down1
Yung Joc1
Aaliyah1
Adele1
Afrojack1
a-ha1
Alan O'Day1
All-4-One1
Amy Grant1
? and The Mysterians1
Anita Baker1
Anita Ward1
Archie Bell and The Drells1
Archies1
A Taste Of Honey1
Baauer1
Bangles1
Belinda Carlisle1
Bell Biv Devoe1
Bill Withers1
Billy Idol1
Billy Joel1
Billy Preston1
Billy Vaughn1
B.J. Thomas1
Blondie1
B.o.B1
Bobby Brown1
Bobby Gentry1
Bobby Goldsboro1
Bobby Lewis1
Bob Seger1
Bone Thugs-N-Harmony1
Bon Jovi1
Bonnie Tyler1
Box Tops1
Brandy and Monica1
Breathe1
Brenda Lee1
Britney Spears1
Browns1
Bruce Hornsby and The Range1
Busta Rhymes1
Calvin Harris1
Carly Rae Jepsen1
Carly Simon1
Carole King1
Carpenters1
Carrie Underwood1
Cascades1
C+C Music Factory1
Cee Lo Green1
Chaka Khan1
Chamillionaire1
Champs1
Cher1
Chic1
Chiffons1
Chingy1
Colby O'Donis1
Commodores1
Coolio1
Cream1
Culture Club1
Daniel Powter1
David Bowie1
David Rose1
David Seville1
Dawn1
Debby Boone1
Deborah Cox1
Dee Clark1
Dee Dee Sharp1
Del Shannon1
Destiny's Child1
Diamonds1
Dido1
Dionne and Friends1
Dire Straits1
Dolly Parton1
Domenico Modugno1
Don McLean1
Donna Lewis1
Donny Osmond1
Doors1
Doris Day1
Eagles1
Earth, Wind and Fire1
Eddie Murphy1
Eddie Rabbitt1
Edwin Starr1
Ellie Goulding1
EMF1
Eminem1
Emotions1
Enya1
Eric Clapton1
Eurythmics1
Evanescence1
Eve1
Exile1
Extreme1
Faith Evans1
Fat Joe1

Can you get the same result?

Go to the question on the platformTables: billboard_top_100_year_end

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #19: Liking Score Rating

The question by Meta/Facebook is perfect to show you how the CTE works.

Facebook SQL query interview question

Link to the question: https://platform.stratascratch.com/coding/9775-liking-score-rating

The table facebook_reactions has the columns:

facebook_reactions

posterint
friendint
reactionvarchar
date_dayint
post_idint

Here’s the sample of the data.

dataset for sql question to find liking score rating

Another table you’ll have to use is facebook_friends:

user1int
user2int

Below is the data.

dataset 2 for sql question to find liking score rating

What you got to do here to write a correct solution is write a CTE. You do that by using the keyword WITH, after which comes the CTE name, then follows the AS keyword that introduces the CTE definition. (The CTE’s SELECT statement, in other words).

In our case, the CTE is named p.

WITH p AS
  (SELECT SUM(CASE
                  WHEN reaction = 'like' THEN 1
                  ELSE 0
              END)/COUNT(*)::decimal AS prop,
          friend
   FROM facebook_reactions
   GROUP BY 2)

We use this CTE to calculate the propensity by dividing the number of likes with the number of all reactions. If you run only this SELECT statement, you’ll get this:

Output for sql question to find liking score rating

It’s a propensity per friend.

To get the average propensity, along with the date and poster, you’ll need to join the CTE with the table facebook_reactions, and use the AVG() function. This second part of the solution is:

SELECT date_day,
       poster,
       avg(prop)
FROM facebook_reactions f
JOIN p ON f.friend= p.friend
GROUP BY 1,
         2
ORDER BY 3 DESC

It can’t be run separately from the CTE because it references the CTE and its result can’t be, you’ll remember that, used unless the query has been run. So the complete solution is:

WITH p AS
  (SELECT SUM(CASE
                  WHEN reaction = 'like' THEN 1
                  ELSE 0
              END)/COUNt(*)::decimal AS prop,
          friend
   FROM facebook_reactions
   GROUP BY 2)
SELECT date_day,
       poster,
       avg(prop)
FROM facebook_reactions f
JOIN p ON f.friend= p.friend
GROUP BY 1,
         2
ORDER BY 3 DESC

And here’s the output.

Final output for sql question to find liking score rating

SQL Query Interview Question #20: Common Friends Friend

This is a hard question by Google, but give it a try.

Last Updated: February 2019

HardID 9821

Find the number of a user's friends' friend who are also the user's friend. Output the user id along with the count.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9821-common-friends-friend

To solve this question, again use the CTE. This time, it will consist of two SELECT statements and you’ll merge their results using the UNION. That way you get users and their friend, something that we already did in one of the questions above.

Once you write the CTE, use the COUNT() function to find the number of friends. This will be a bit more complex query that will use subquery in the FROM clause. The subquery will reference the CTE three times, which means the CTE will be self-joined and then grouped by the user ID.

Go to the question on the platformTables: google_friends_network

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Here’s what you get if the solution is correct.

user_idn_friends
05
14
22
32
53
62
72
83
93
302

Window Functions

Window Functions SQL Query Questions

The SQL window functions are a valuable SQL feature most useful when you want to show the aggregated and the non-aggregated data at the same time. They share some similarities with the aggregate functions. However, the SQL aggregate functions lose the individual rows while the window functions don’t.

SQL Query Interview Question #21: Most Profitable Companies

We’ll use the Forbes question to show you the window functions.

Forbes SQL query interview question

Link to the question: https://platform.stratascratch.com/coding/9680-most-profitable-companies

The table forbes_global_2010_2014 consists of the following columns:

forbes_global_2010_2014

companyvarchar
sectorvarchar
industryvarchar
continentvarchar
countryvarchar
marketvaluefloat
salesfloat
profitsfloat
assetsfloat
rankint
forbeswebpagevarchar

The data is:

Dataset for SQL Query Interview Question from Forbes

Here’s how we’re going to approach the solution. We’ll write two subqueries: one in the main query’s FROM clause and the other one in the subquery’s. Their purpose is to find the companies and their profit, then rank them according to that. Here’s how these two subqueries look.

SELECT *,
       dense_rank() OVER (
                          ORDER BY profit DESC) AS rank
FROM
  (SELECT company,
          sum(profits) AS profit
   FROM forbes_global_2010_2014
   GROUP BY company) sq

Even though the first SELECT statement now looks like the regular SELECT statement, it is a subquery, though. You’ll realize that once we write the main SELECT statement.

Notice there’s a window function DENSE_RANK(). This and other window functions are introduced by the OVER() clause. This clause can remain empty, but it also can contain PARTITION BY and/or the ORDER BY clause. The ORDER BY here tells the window function to rank according to profit from the highest to the lowest one.

This the subqueries’ partial output.

Dataset 2 for SQL Query Interview Question from Forbes

We got the companies rank and their profit. Now we have to put these subqueries within the main query that will output the company and its profit, and then use the WHERE clause to show only the companies with the ranking 3 or higher.

The complete solution to this question is:

SELECT company,
       profit
FROM
  (SELECT *,
          dense_rank() OVER (
                             ORDER BY profit DESC) AS rank
   FROM
     (SELECT company,
             sum(profits) AS profit
      FROM forbes_global_2010_2014
      GROUP BY company) sq) sq2
WHERE rank <=3

It should give you the output shown below.

Dataset 3 for SQL Query Interview Question from Forbes

This tells us the three most profitable companies are ICBC, Gazprom, and Apple.

SQL Query Interview Question #22: Lowest Priced Orders

Another example where you’ll have to use the window functions is this question by Amazon.

Last Updated: May 2019

EasyID 9912

Find the lowest order cost of each customer. Output the customer id along with the first name and the lowest order price.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9912-lowest-priced-orders

To find the lowest order, use the FIRST_VALUE() window function. It will give you the first value in the set of values. Also, you’ll have to use both the PARTITION BY and the ORDER BY clauses. To get all data you need you’ll have to join the tables you have at your disposal.

If you got everything right, your output will be the same.

cust_idfirst_namelowest_price_per_group
12Eva20
1Mark125
4William60
5Henry80
15Mia20
3Farida15
7Jill25

Go to the question on the platformTables: customers, orders

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #23: Fastest Hometowns

Deloitte asks you the following:

Last Updated: October 2021

MediumID 2066

Find the hometowns with the top 3 average net times. Output the hometowns and their average net time. Keep in mind that a lower net_time is better. In case there are ties in net time, return all unique hometowns.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2066-fastest-hometowns

Write the solution so that you use the subquery. Use it to find the hometown, average net time and the rank according to it. To achieve that, use the AVG() and DENSE_RANK() window functions. Embed this subquery within the query that will filter only data with the top 3 rank.

Try to get this output.

hometownavg_net_time
Kenya .1789.67
Oakton VA1828
Ardmore PA1878
Oxon Hill MD1878

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #24: Days at Number One

Things will get more complicated with this and the next question. Spotify gives you these instructions:

HardID 10173

Find the number of days a US track has stayed in the 1st position for both the US and worldwide rankings on the same day. Output the track name and the number of days in the 1st position. Order your output alphabetically by track name.

If the region 'US' appears in dataset, it should be included in the worldwide ranking.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/10173-days-at-number-one

Use the subquery in the FROM clause to get the track name and the number of days at the 1st position. You’ll have to do it by using the SUM() function and the CASE WHEN statement inside it. Also, this SUM() function will not be the ordinary aggregate one, but the window function. Join the tables you have and filter data to only get those where the position is 1.

The main query will then use this subquery and the MAX() function to get the result:

tracknamenum_days
Bad and Boujee (feat. Lil Uzi Vert)1
HUMBLE.3

Go to the question on the platformTables: spotify_daily_rankings_2017_us, spotify_worldwide_daily_song_ranking

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #25: Most Expensive and Cheapest Wine

Here’s the final interview question for practicing the window functions. The question is by Wine Magazine.

Last Updated: March 2020

HardID 10041

Find the cheapest and the most expensive variety in each region. Output the region along with the corresponding most expensive and the cheapest variety. Be aware that there are 2 region columns, the price from that row applies to both of them.

Note: The results set contains no ties.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/10041-most-expensive-and-cheapest-wine

Approach writing a code in the following way. First write two CTEs. The first CTE will have two SELECT statements and they will show the wine variety, region and price. Combine their outputs into one.

The second CTE will reference the first one to rank wines using the ROW_NUMBER() window function and getting the rank from the most expensive to the cheapest wine and vice versa.

After that comes the SELECT statement that references the second CTE. To get the desired output, you have to use the CASE WHEN statement in two MAX() functions: one to get the variety of the most expensive wine, the other to get the cheapest wine’s variety. You’re interested only in the cheapest and the most expensive wine, so you’ll have to filter data using the WHERE clause.

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

If you get the below result, then you got everything right.

regionmost_expensive_varietycheapest_variety
Alexander ValleyCabernet SauvignonMerlot
Anderson ValleyPinot NoirPinot Noir
BarbarescoNebbioloNebbiolo
Brunello di MontalcinoSangioveseSangiovese
CaliforniaPinot NoirSauvignon Blanc
California OtherPinot NoirSauvignon Blanc
CarinenaRed BlendRed Blend
Central CoastPinot NoirPinot Noir
ChablisChardonnayChardonnay
ChalonePinot NoirPinot Noir
ChampagneChampagne BlendChampagne Blend
Chianti ClassicoSangioveseSangiovese
Columbia ValleySyrahGewarztraminer
Columbia Valley (WA)MerlotGewarztraminer
Conegliano ValdobbiadeneGleraGlera
Diamond Mountain DistrictCabernet SauvignonCabernet Sauvignon
Edna ValleyPinot NoirPinot Noir
Forla‚Sauvignon BlancSauvignon Blanc
FranciacortaChardonnaySparkling Blend
Long IslandMerlotMerlot
Luja?n de CuyoMalbecMalbec
Mazis-ChambertinPinot NoirPinot Noir
Mendocino/Lake CountiesPinot NoirPinot Noir
MendozaMalbecCabernet Sauvignon
MeursaultChardonnayChardonnay
MontsantRed BlendRed Blend
NapaCabernet SauvignonMoscato
Napa ValleyCabernet SauvignonMoscato
North Fork of Long IslandMerlotMerlot
OakvilleCabernet SauvignonCabernet Sauvignon
Paso RoblesCabernet SauvignonCabernet Sauvignon
Pays d'OcMerlotMerlot
Pouilly-FuisseChardonnayChardonnay
Prosecco di ValdobbiadeneProseccoProsecco
Rao Negro ValleyMalbecMalbec
RasteauRhone-style Red BlendRhone-style Red Blend
Ribera del DueroRed BlendRed Blend
RiojaTempranilloTempranillo
Russian River ValleyPinot NoirZinfandel
RutherfordRed BlendCabernet Sauvignon
San JuanMalbecMalbec
San Luis Obispo CountyPinot NoirPinot Noir
Shenandoah Valley (CA)SangioveseSangiovese
SiciliaNero d'AvolaNero d'Avola
Sierra FoothillsSangioveseSangiovese
Soave ClassicoGarganegaGarganega
SonomaPinot NoirMerlot
Sonoma CoastPinot NoirPinot Noir
Sonoma CountySauvignon BlancSauvignon Blanc
South Eastern AustraliaChardonnayChardonnay
Sta. Rita HillsPinot NoirPinot Noir
The Hamptons, Long IslandMerlotMerlot
Uco ValleyViognierViognier
Valpolicella ClassicoCorvina, Rondinella, MolinaraCorvina, Rondinella, Molinara
Vin MousseuxWhite BlendWhite Blend
VirginiaMerlotMerlot
Walla Walla Valley (WA)SyrahSemillon
WashingtonCabernet SauvignonCabernet Sauvignon
Washington OtherCabernet SauvignonCabernet Sauvignon
Willamette ValleyRieslingRiesling

Text & Date Manipulation

Text & Date Manipulation SQL Questions

The last topic we’ll cover here is different ways of working with the date and text data types.

SQL Query Interview Question #26: Combine the First and Last Names of Workers

One of the most common things you can be asked to do when working with text data is to concatenate two or more columns from the table. Here’s what exactly Amazon wants you to do.

EasyID 9834

Combine the first and last names of workers with a space in-between in a column 'full_name'.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9834-combine-the-first-and-last-names-of-workers

The table at your disposal is worker.

Table: worker
Loading Dataset

You see they want you to put the employee’s first and last name in one column. Here’s how you do it:

SELECT first_name || ' ' || last_name AS full_name
FROM worker

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Select the employee’s first name, then follow it up with two vertical lines ||. What follows after that will be concatenated with the first name. We want the blank space to come after the first name, so we put blank space in the single quotation marks. After that again comes the sign for concatenation, and then the employee’s last name.

This will give their names in the new column full_name.

full_name
Monika Arora
Niharika Verma
Vishal Singhal
Amitah Singh
Vivek Bhati
Vipul Diwan
Satish Kumar
Geetika Chauhan
Agepi Argon
Moe Acharya
Nayah Laghari
Jai Patel
Jura Jomun

SQL Query Interview Question #27: Print the First Three Characters of the First Name

We’re staying with Amazon and their question that again give you the same table as the question above.

EasyID 9828

Print the first three characters of the first name.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9828-print-the-first-three-characters-of-the-first-name

This question is easy to solve if you know how the SUBSTRING() function works. Use it to get the following result:

substring
Mon
Nih
Vis
Ami
Viv
Vip
Sat
Gee
Age
Moe
Nay
Jai
Jur

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #28: Count the Number of Words per Row in Both Words Lists

Here’s one Google question that’s more complicated.

MediumID 9812

Count the number of words per row in both words lists.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9812-count-the-number-of-words-per-row-in-both-words-lists

Use the LENGTH() and the REPLACE() function to get the answer. Remember, LENGTH() is used to count the number of characters in string. REPLACE() searches one character in a string, and replaces it with another.

Here’s what you need to output:

n_words
6
4
5
4

Go to the question on the platformTables: google_word_lists

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

SQL Query Interview Question #29: Users Activity per Month Day

This question by Meta/Facebook will test your knowledge on working with dates.

Last Updated: January 2021

EasyID 2006

Return the total number of posts for each month, aggregated across all the years (i.e., posts in January 2019 and January 2020 are both combined into January). Output the month number (i.e., 1 for January, 2 for February) and the total number of posts in that month.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2006-users-activity-per-month-day

You’re given the facebook_posts table.

Table: facebook_posts
Loading Dataset

How do you solve this question? The trick here is to use the DATE_PART() function. It will get you the day from the column post_date. The COUNT() function is there to find the number of posts. Also, convert the data type to date. Finally, group the result by the day and you get the correct solution.

SELECT date_part('day', post_date::date),
       count(*)
FROM facebook_posts
GROUP BY date_part('day', post_date::date)

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Its output is here.

date_partcount
13
23

SQL Query Interview Question #30: Find All Workers Who Joined on February 2014

We’ll finish this off with the question by Amazon. It asks you:

EasyID 9844

Find all workers who joined on February 2014.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9844-find-all-workers-who-joined-on-february-2014

Here you’ll need to use the EXTRACT function to get the year and month for the data available and do it in the WHERE clause. The data also has to be cast to a date type.

Here’s the output:

worker_idfirst_namelast_namesalaryjoining_datedepartment
1MonikaArora1000002014-02-20HR
3VishalSinghal3000002014-02-20HR
4AmitahSingh5000002014-02-20Admin

And the answer? Write it in the widget and let’s see what’ll happen.

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Conclusion

With covering 30 questions we gave you a thorough understanding of the SQL coding interview questions. These questions cover six major topics you have to be skilled in.

They cover data aggregation, grouping, ordering, filtering, and using the conditional statements. To combine data there are JOINs and UNION. As the queries get more complex, you’ll start using subqueries, CTEs, and the window functions. All that has also include the knowledge on working with text and dates.

It’s not enough to know all these SQL concepts. To score more points you should be able to structure your SQL code well when providing the answer to the interview question.

Share