[Solved] Query to select all rows containing a value that appears less than 8 times
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Query to select all rows containing a value that appears less than 8 times

I'm trying to set up a system that has a parent and 8 children. I've done this by having a table of user_id and tier_id. Now I need to get a list of all the tier_id's that appear less than 8 times, so I know that tier is incomplete and then I can go to another list and get replacements.

SELECT * FROM tiers WHERE COUNT(SELECT tier_id) < 8;

I know this isn't right, but maybe it can help explain to a genius what I'm trying to do.

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Correlated Subqueries (query line: 6): A correlated subquery is a subquery that contains a reference (column: tier_id) to a table that also appears in the outer query. Usually correlated queries can be rewritten with a join clause, which is the best practice. The database optimizer handles joins much better than correlated subqueries. Therefore, rephrasing the query with a join will allow the optimizer to use the most efficient execution plan for the query.
  2. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
SELECT
        * 
    FROM
        tiers 
    WHERE
        COUNT(SELECT
            tier_id) < 8

Related Articles



* original question posted on StackOverflow here.