sqlbeginner10 minutes

Create a SQL Function to Return the Total Number of Orders for a Customer

Write a simple SQL function that takes a customer ID as input and returns the total count of orders placed by that customer.

Challenge prompt

You have a table named Orders with columns OrderID, CustomerID, and OrderDate. Write a SQL function named GetCustomerOrderCount that accepts a CustomerID as input and returns the total number of orders placed by that customer. Your function should return an integer representing this count.

Guidance

  • Use the COUNT aggregate function to count the number of orders for the given CustomerID.
  • Filter the Orders table by CustomerID inside your function.
  • Ensure your function returns an integer value.

Hints

  • Start by writing a SELECT COUNT(*) query filtered by CustomerID.
  • Remember to define the input parameter and return type for your function.

Starter code

CREATE FUNCTION GetCustomerOrderCount(@CustomerID INT)
RETURNS INT
AS
BEGIN
    -- Your code here
END;

Expected output

For example, calling GetCustomerOrderCount(5) returns 12 if customer with ID 5 has 12 orders.

Core concepts

SQL functionsSELECT queryCOUNT aggregate

Challenge a Friend

Send this duel to someone else and see if they can solve it.