{x}
blog image

Find Customers With Positive Revenue this Year

Solution Explanation and Code

This problem requires retrieving the customer_id of customers who had positive revenue in the year 2021 from the Customers table. The solution leverages the SQL WHERE clause to filter the results based on the specified criteria.

Approach

The most straightforward approach involves using a SQL query with a WHERE clause to filter the data. The WHERE clause will specify two conditions:

  1. year = 2021: This condition ensures that only records from the year 2021 are considered.
  2. revenue > 0: This condition filters out customers with non-positive revenue, leaving only those with positive revenue.

The SELECT statement then retrieves the customer_id for the remaining records.

Time Complexity Analysis

The time complexity of this SQL query is dependent on the database engine's query optimizer and the size of the Customers table. In the best-case scenario (where an index exists on the year column and perhaps a composite index on (year, revenue)), the query would have a time complexity of O(log n + m), where 'n' is the number of rows in the table, and 'm' is the number of rows satisfying the WHERE clause conditions. The O(log n) part comes from index lookup; the O(m) comes from retrieving the rows that satisfy the conditions. In the worst-case scenario (no suitable indexes), the query would have a time complexity of O(n) as it would have to scan the entire table.

Space Complexity Analysis

The space complexity is largely determined by the size of the result set (the number of customers with positive revenue in 2021). In the worst case, this could be O(n) if all customers had positive revenue, but in most realistic scenarios, it would be significantly smaller. The space used by the query itself is relatively constant and not significant.

Code (MySQL)

SELECT customer_id
FROM Customers
WHERE year = 2021 AND revenue > 0;

This query directly implements the described approach. It selects the customer_id column from the Customers table and filters the results using the WHERE clause to only include entries where the year is 2021 and the revenue is greater than 0. The result is a table containing only the customer_id of the customers meeting these criteria.

Other Database Systems

The core SQL query remains the same for other database systems (PostgreSQL, SQLite, SQL Server, Oracle, etc.). Minor syntax differences might exist depending on the specific system, but the underlying logic stays consistent. For instance, the query would be functionally identical in PostgreSQL or other SQL dialects.