[Solved] SQL Conditions, one definite others variable
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

SQL Conditions, one definite others variable

I have the following SQL query:

SELECT *
  FROM UserTags
    INNER JOIN Events ON UserTags.E_ID=Events.E_ID
WHERE ID = 2
  AND Tag='coffee'
  OR Tag='breakfast_brunch'
  OR Tag='scandinavian'

This is returning the incorrect result, as it is returning columns where `ID!=2'. I believe this its trying to match the first two, followed by the others? I would like the query to only match when ID=2 in any situation.

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 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
        UserTags 
    INNER JOIN
        Events 
            ON UserTags.E_ID = Events.E_ID 
    WHERE
        ID = 2 
        AND Tag = 'coffee' 
        OR Tag = 'breakfast_brunch' 
        OR Tag = 'scandinavian'

Related Articles



* original question posted on StackOverflow here.