Search code examples
sqlsubquerymulti-query

sqli multi-query combine two queries on a single one


I have a situation where I have a large table and Im making two queries and I want to combine them into a single one. Say I have a table like this:

Name |LastName|Address|State
---------------------------
John |Carter  |23 Blv | CA
Bill |Carter  |23 Blv | CA
Joe  |Carter  |23 Blv | CA
Steve|Carter  |23 Blv | CA

the first query is

SELECT * FROM table WHERE Name LIKE '%query%' OR  LastName LIKE '%query%'

the second is:

SELECT * FROM table WHERE Address LIKE '%query%' OR  State LIKE '%query%'

The reason why Im doing this is because I want results to be ordered based on Name|Surname first and then append more results based on Address|State.

Cany anybody help to make it a single query? I am using *SQLite by the way.*

Thanks alot.


Solution

  • SELECT * FROM table WHERE Name LIKE '%query%' OR  LastName LIKE '%query%'
    UNION ALL 
    SELECT * FROM table WHERE Address LIKE '%query%' OR  State LIKE '%query%'
    ORDER BY Name, Surname, State