SQL Interview Question: Creating Column of Arrays

This problem statement is a part of our SQL Interview Questions series. In this series we are committed to bring out a collection of real-world SQL interview questions to help job seekers improve their coding skills and gain confidence.

To check all the interview questions available in this series, click here.

Problem Statement:

Write an SQL query to return an array of Order Id’s for every company. The output should contain the Company name, array of all order id’s for the company and the total order count. Sort the output by the number of orders for each company in descending order.

Table:

Company_Orders

CompanyOrderIDOrderAmount
EbayE431720
FlipkartF197250
WayfairW190660
EbayE161620
AlibabaA364420
AlibabaA246180
EbayE2611100
AmazonA145445
AmazonA237985
EbayE166360
FlipkartF182950
AmazonA130530
FlipkartF298675
WayfairW2632100
FlipkartF492395
AmazonA318220
AmazonA155680
FlipkartF466110
EbayE130065
AlibabaA149995
WayfairW230790
AlibabaA106720
AmazonA156515
AmazonA463925
AmazonA317495

Solution:

1. Microsoft SQL Server
SELECT Company,
     STRING_AGG(OrderID, ', ') AS Orders_Array,
     COUNT(OrderID) AS Orders_Count
FROM Company_Orders
GROUP BY Company
ORDER BY COUNT(OrderID) DESC

STRING_AGG() is an aggregate function in SQL Server that takes all values from rows and concatenates them into a single string in the output result set. All row values are first converted into a string data type and then concatenated. The syntax for the function is:

STRING_AGG (expression, separator)

To learn about STRING_AGG() function in detail, check the Microsoft’s documentation here.

2. PostgreSQL

SELECT Company,
ARRAY_AGG(OrderID) AS Orders_Array
COUNT(OrderID) AS Orders_Count
FROM Company_Orders
GROUP BY Company
ORDER BY COUNT(OrderID) DESC

ARRAY_AGG() is an aggregate function in PostgreSQL, it accepts a set of values and returns an array where each value in the input set becomes an element of the array. The syntax for the function is:

ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...])

For more information on this function, check the PostgreSQL documentation here.

Output:

MS SQL Server output is shared below.

Let us know your queries in the comment section below. We will keep adding more SQL interview questions in this series over time.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *