Searching on Two Keys in MySQL


Let us understand how to search on two keys in MySQL

Searching on two keys can be achieved using the ‘OR’ with the help of single key which is well optimized or using ‘AND’ which is well optimized. Let us see how searching on two different keys can be done combining it with ‘OR’ operation −

SELECT field1_index, field2_index FROM tableName
WHERE field1_index = '1' OR field2_index = '1'

This is an optimized version of the query. It can also be done efficiently using the ‘UNION’ that combines the output of two separate ‘SELECT’ statements. Every ‘SELECT’ statement searches only for one key and it can be optimized. Let us see the query in action −

Query

SELECT field1_index, field2_index
FROM tableName WHERE field1_index = '1'
UNION
SELECT field1_index, field2_index
FROM tableName WHERE field2_index = '1';

Updated on: 09-Mar-2021

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements