[Solved] SQL Searching - Two Columns Varying Values
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

SQL Searching - Two Columns Varying Values

Based on a poor database design beyond my control, I am now having to deal with something new (for me). I am hoping someone can assist me.

We have two columns in the database: "Column1" and "Column2" Column1 can have a value of Breakfast/Lunch/Dinner. Column2 is free text and can contain many things.

How can I write a query where I can look for more than one specific value in Column1 and Column2 where both conditions must be true?

Example Code:

Select *
from TestDb
where (Column1 = 'Breakfast' and Column2 like '%banana%')
and (Column1 = 'Lunch' and Column2 like '%pizza%')

The expected result is that we find all subjects who had a banana for breakfast and pizza for lunch (which is why both conditions must be true). We don't want to find subject who just had a banana for breakfast or just pizza for lunch.

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 LIKE Searches With Leading Wildcard (query line: 8): The database will not use an index when using like searches with a leading wildcard (e.g. '%banana%'). Although it's not always a satisfactory solution, please consider using prefix-match LIKE patterns (e.g. 'TERM%').
  2. Avoid LIKE Searches With Leading Wildcard (query line: 12): The database will not use an index when using like searches with a leading wildcard (e.g. '%pizza%'). Although it's not always a satisfactory solution, please consider using prefix-match LIKE patterns (e.g. 'TERM%').
  3. 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.
  4. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `TestDb` ADD INDEX `testdb_idx_column1` (`Column1`);
The optimized query:
SELECT
        * 
    FROM
        TestDb 
    WHERE
        (
            TestDb.Column1 = 'Breakfast' 
            AND TestDb.Column2 LIKE '%banana%'
        ) 
        AND (
            TestDb.Column1 = 'Lunch' 
            AND TestDb.Column2 LIKE '%pizza%'
        )

Related Articles



* original question posted on StackOverflow here.