Q
Problem solve Get help with specific problems with your technologies, process and projects.

Customers who bought X at least once and Y at least twice

I have a table CUSTOMERS (customer_id) and a table PURCHASES (customer_id, purchase_date, product_id). I am trying...

to find the distinct customers that have bought at least once product_id=X and, in the 12 previous months, bought at least twice product_id=Y. Any idea that could do the job in a minimum time?

Solutions that do the job "in a minimum time" are always challenging. Success depends on the existence of proper indexes. Assuming these are in place, we can still sometimes see markedly different results for solutions written with different query constructions.

The first step towards a solution, the most important step, is to make sure we understand the exact requirements. In this case, we don't care about purchase data, just that it exists. We aren't actually retrieving anything from the PURCHASES table! If you had said "give the date of the latest Product X purchase, and the total number of Product Y purchases" then we'd need to write a totally different query.

Here's one solution:

```select customer_id
from CUSTOMERS as C
where exists
( select *
from PURCHASES
where customer_id
= C.customer_id
and product_id = 'X' )

and 2 <=
( select count(*)
from PURCHASES
where customer_id
= C.customer_id
and product_id = 'Y'
and purchase_date
between date1
and date2 )```

Each of the two subqueries above is a correlated subquery. This means that it considers only those purchases which match the customer_id of the correlated row in the main query.

One advantage of using correlated subqueries is that it's fairly easy to understand what they're doing. They "read" well. In this case, though, there are two of them, which leaves open the possibility that the database optimizer will generate two separate joins in order to execute them. (Correlated subqueries are usually executed as joins.)

Here's a different solution:

```select C.customer_id
from CUSTOMERS as C
inner
join PURCHASES as P
on C.customer_id
= P.customer_id
group
by C.customer_id
having 0 <
sum(
case when P.product_id = 'X'
then 1 else 0 end
)
and 2 <=
sum(
case when P.product_id = 'Y'
and P.purchase_date
between date1
and date2
then 1 else 0 end
)```

Here you can see we've taken matters into our own hands and performed one join explicitly. Note that we're still just selecting from the CUSTOMERS table. The WHERE EXISTS construction is replaced by taking a count and making sure it's not zero. The counts are achieved by obtaining the SUM of a column of 1's and 0's.

Which of the solutions is faster? Try them both, and see.

This was last published in March 2005

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

SearchDataManagement

• Hyperledger Fabric offers path to enterprise blockchain future

Blockchain arose from bitcoin, but it's looking to find a place in the enterprise. Frameworks like Hyperledger Fabric could ...

• MongoDB 4.0 takes ACID transactions to multi-document level

MongoDB is taking a deeper step into SQL-style processing waters with a 4.0 update that brings increased support for ...

• Data lake concept needs firm hand to pay big data dividends

Data lakes pose technology deployment and data management challenges that can leave analytics users high and dry if the ...

• AI functionality limited today but could be a game-changer

Limited AI capabilities could soon give way to technology that is truly transformative for enterprises, surpassing the overhyped ...

SearchSAP

• ControlPanelGRC app eases Steelcase's compliance pain

When Steelcase's SAP environment grew in size and complexity, it turned to Symmetry ControlPanelGRC to save time, have more ...

• Translytical data platforms emerge with SAP HANA as a leader

SAP HANA is a leading translytical platform, according to Forrester, and consulting firm Convergent IS says the combination of ...

• SAP HANA and Esri combine for geospatial database platform

SAP and Esri are combining SAP HANA's in-memory database capabilities with Esri geospatial applications, and utilities are taking...

SearchSQLServer

SQL Operations Studio simplifies routine administration of SQL Server and Azure SQL databases, making database development and ...

• Meltdown and Spectre fixes eyed for SQL Server performance issues

Microsoft has responded to the Spectre and Meltdown chip vulnerabilities with patches and other fixes. But IT teams need to sort ...

• Five SQL Server maintenance steps you should take -- ASAP

Putting off SQL Server administration tasks can lead to database problems. Enact these often-neglected maintenance items to help ...

TheServerSide.com

• Pluralsight IQ, Stack Overflow boost developer street cred

Tying the Pluralsight IQ skills test to the Stack Overflow Developer Story helps developers measure their technical skills and ...

• Why this quantum computing breakthrough is a security risk

Quantum computing will void pretty much all security encryption techniques and open the door to hackers. Here's how to protect ...

• Database automation drives DevOps into the persistence layer

A new breed of software tools is driving DevOps processes deep into the persistence layer, as database automation and continuous ...

SearchDataCenter

• Evaluate read-intensive and write-intensive SSD use cases

Consider write wear, performance and other factors when choosing between read-intensive, write-intensive and mixed-use ...

• Some hyper-converged infrastructure use cases pose pitfalls

Hyper-converged infrastructure adoption is skyrocketing, but that doesn't mean that the technology is the best choice for every ...

• Dell hyper-converged reorg streamlines products, ups CI odds

Market pressures and manufacturing synergies drove Dell to integrate its HCI and CI products with its core business units, but ...

SearchContentManagement

• Content management in the cloud a main theme in 2018

The future of content management resides in the cloud and with AI, as several 2018 conferences will assure you.

• Six things to know about today's SharePoint implementations

As companies migrate their on-premises Microsoft SharePoint sites to the cloud, here are some things they should know about the ...

• Upgrades for the SharePoint Online portal

As more organizations migrate SharePoint sites to the cloud, Microsoft has increased at-a-glance dashboard data and analytics to ...

SearchHRSoftware

• Don't overlook the many benefits of Microsoft Excel for HR

The maligned spreadsheet tool is no substitute for enterprise apps like HRMS and people analytics, but it will do in a pinch and ...

• HR is failing to use people analytics tools, new report says

Human resource departments fail to use people analytics tools effectively, a new global study concludes. The findings were called...

• Does your company need new human resource management tools?

Finding the best human resource management tools starts with identifying your company's present and future needs, before ...

Close