[Solved] MySql query with OR condition
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

MySql query with OR condition

Database type:

I have one table with 2 unique indexed fields named "username" and "emailid". when I have fire one query on this table with OR condition like

SELECT * FROM tableName where (username = 'aaaa' OR emailid = 'aaaa')

the explain statement shows me for above query is

"Using union(UX_EMailID,UX_UserName); Using where" 

under "SIMPLE" as select_type.

Is it ok for performance, or something is wrong. One more way to do this with me. first call with one field and if no record found then try for second field like as follows.

IF EXISTS (SELECT 1 FROM tableName where username = 'aaaa' ) THEN
   //do code
ELSE
    IF EXISTS (SELECT 1 FROM tableName where emailid = 'aaaa' ) THEN
       //do code
    ELSE
       //throw error 
    END IF; 
END IF; 

So, Now I have confusion, which is better way for performance.

EDIT :

table: usermst
~~~~~~~~~~~~~~
id        int         //primary key 
username  varchar(20) //unique index
emailid   varchar(50) //unique index

EXPLAIN:

id: 1, 
select_type: 'SIMPLE'
table: 'usermst'
type: 'index_merge' 
possible_keys: 'ux_username,ux_emailid'
key: 'ux_emailid,ux_username' 
key_len: '153,63' 
ref: null
rows: 2
Extra: 'Using union(ux_emailid,ux_username); Using where'

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
        tableName 
    WHERE
        (
            tableName.username = 'aaaa' 
            OR tableName.emailid = 'aaaa'
        )

Related Articles



* original question posted on StackOverflow here.