How to Combine Two QUERY Results in Google Sheets

Published on

When you want to combine two QUERY results in Google Sheets, there are a few things to keep in mind:

First, you can combine two QUERY results vertically (one below another) or horizontally (side by side). For this, you can use the following functions:

  • VSTACK
  • HSTACK

Alternatively, you can use the Curly Braces operator ({}). However, the Curly Braces operator has two drawbacks:

  • It can be difficult to read and maintain.
  • It can cause confusion depending on locale settings, such as comma instead of semicolon or backslash.

Therefore, we recommend using the VSTACK and HSTACK functions instead.

To combine two QUERY outputs vertically, the number of columns in the result must match. To combine two QUERY outputs horizontally, the number of rows must match.

Second, combining two or more Query results won’t work correctly if either of the Queries returns a #N/A error. This is because it would cause an array mismatch.

The VSTACK and HSTACK functions may return a few #N/A error values when there is a mismatch of rows or columns. However, you can easily remove these errors using an additional layer of filter.

How to Properly Combine Two QUERY Results in Google Sheets

Below are a few examples of how to combine two QUERY results vertically.

For these examples, I will use two QUERY formulas and the following data in A1:C:

Query Combine - Sample Data

Today’s date is December 5, 2018.

Note: If you use the above data on a future date, it will not work correctly. Therefore, change the dates in column A above to match today’s date when you use this tutorial. For example, you can use the following formulas:

=TODAY()-2 // in A2
=TODAY() // in A3 and A4
=TODAY()+1 // in A5
=TODAY()+2 // in A6

Here are the two QUERY formulas:

Formula #1:

=QUERY({A2:C},"Select * where Col1>date '"&text(today(),"yyyy-mm-dd")&"'",0)

Formula #2:

=QUERY({A2:C},"Select * where Col1<date '"&text(today(),"yyyy-mm-dd")&"'",0)

Outputs of Query Formula 1 and 2:

Combine Two Query Results in Google Sheets

We can combine these two Query outputs vertically using the following formulas.

Combine Two Query Results Vertically in Google Sheets

We will start with Curly Braces.

Using Curly Braces

You can normally combine the two QUERY formulas above as follows:

={QUERY({A2:C},"Select * where Col1>date '"&text(today(),"yyyy-mm-dd")&"'",0);QUERY({A2:C},"Select * where Col1<date '"&text(today(),"yyyy-mm-dd")&"'",0)}

Just place a semicolon between the two QUERY formulas and then wrap the entire formula with Curly Braces. This will work in most cases.

However, if either of the formulas returns an #N/A error (empty output), the combined formula will return an #VALUE! error.

Must read: Different error types in Google Sheets.

Here is a solution to properly combine two QUERY results vertically in Google Sheets:

First, I will show you the changes to each QUERY formula, and then we can combine them.

Modified Formula #1:

IFERROR(QUERY({A2:C},"Select * where Col1>date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0),A2:C2/0)

Modified Formula #2:

IFERROR(QUERY({A2:C},"Select * where Col1<date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0),A2:C2/0)

If there is an #N/A error, both formulas will divide the values in A2:C2 by 0. The result will be as follows:

#DIV/0! #VALUE! #DIV/0!

This is to match the error to the number of total columns in our output. This makes the combining valid.

However, in the combined output, we should remove these error codes with another IFERROR function, as follows:

=ARRAYFORMULA(IFERROR({IFERROR(QUERY({A2:C},"Select * where Col1>date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0),A2:C2/0);     IFERROR(QUERY({A2:C},"Select * where Col1<date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0),A2:C2/0)}))

Finally, we must wrap the combined two Query formulas with the ARRAYFORMULA function.

Additionally, you may need to select the date column in the result and apply Format > Number > Date.

To remove the blank rows in the result, name the formula using LET and apply a filter. Here is an example:

=LET(qc,ARRAYFORMULA(IFERROR({IFERROR(QUERY({A2:C},"Select * where Col1>date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0),A2:C2/0);IFERROR(QUERY({A2:C},"Select * where Col1<date '"&TEXT(TODAY(),"yyyy-mm-dd")&"'",0),A2:C2/0)})),FILTER(qc,CHOOSECOLS(qc,1)<>""))

We used the LET function to name the combined QUERY as qc and filtered out rows in qc if the first column in qc is blank. We used the FILTER function to filter qc and the CHOOSECOLS function to extract the first column for the blank test.

To combine two or more QUERY results vertically using the VSTACK function, you can use the following syntax:

=VSTACK(qery1,query2,query3,...)

To remove errors because either of the formulas returns errors, we can wrap the formula with an IFERROR and use an additional layer of FILTER as per the following syntax:

=LET(qc,IFERROR(VSTACK(qery1,query2,query3,...),FILTER(qc,CHOOSECOLS(qc,1)<>"")))

Formula:

=LET(qc,IFERROR(VSTACK(QUERY({A2:C},"Select * where Col1>date '"&text(today(),"yyyy-mm-dd")&"'",0),QUERY({A2:C},"Select * where Col1<date '"&text(today(),"yyyy-mm-dd")&"'",0))),FILTER(qc,CHOOSECOLS(qc,1)<>""))

You need to format the result column date values to date using the Format > Number > Date option.

I suggest using VSTACK to combine two or more QUERY results vertically because of the following:

  • It is simple and straightforward.
  • There is no issue if the columns are not equal. For example, QUERY 1 result can be two columns and QUERY 2 result can be three columns. The curly braces won’t work in this case.

Combine Two Query Results Horizontally in Google Sheets

When you combine two QUERY outputs horizontally, an error may occur if the number of rows is mismatched. In the previous example, the number of columns was mismatched.

For example;

Formula #1:

=QUERY({A2:C},"Select * Where Col2='Sherry'")

Formula #2:

=QUERY({A2:C},"Select * Where Col2='Kevin'")
Combine Two Query Results horizontally

As you can see in the above example, the first formula returns two rows, and the second one has three rows.

Therefore, we need to add one row to the first formula. This is not practical, as the number of rows may be different in different formulas.

If the number of rows is equal, then you can combine two QUERY results horizontally as follows:

={QUERY({A2:C},"Select * Where Col2='Sherry'"),QUERY({A2:C},"Select * Where Col2='Kevin'")}

Just put a comma between the Query formulas.

However, I suggest using HSTACK to combine two or more QUERY results horizontally because it is more reliable and easier to use.

Syntax:

=IFERROR(HSTACK(query1,query2,query3,...)))

Formula:

=IFERROR(HSTACK(QUERY({A2:C},"Select * Where Col2='Sherry'"),QUERY({A2:C},"Select * Where Col2='Kevin'")))

It’s that simple! The HSTACK function doesn’t have the number of rows issue.

That’s all about how to combine two QUERY results in Google Sheets. If you have any doubts on this topic, feel free to post them in the comments. Enjoy!

Prashanth KV
Prashanth KV
Your Trusted Google Sheets and Excel Guide Prashanth KV brings a wealth of experience in Google Sheets and Excel, cultivated through years of work with multinational corporations in Mumbai and Dubai. As a recognized Google Product Expert in Docs Editors, Prashanth shares his expertise through insightful blogging since 2012. Explore his blog for practical tips and guidance on maximizing your spreadsheet skills.

Lookup Values Under Categories in Excel and Google Sheets

We can use a combination of XLOOKUP and VLOOKUP in both Excel and Google...

Extract Items Under a Category from the Same Column in Excel

In Excel, you can use a combination of the XLOOKUP and DROP functions to...

How to Create a Searchable Table in Excel Using the FILTER Function

Finding specific records, or rows containing the required information, is straightforward in Excel using...

Time Sequences in Excel by Minute, Hour, or Second Increments

Creating time sequences, whether by hour, minute, or second increments in Excel, can be...

More like this

XMATCH Row by Row: Finding Values Across a Range in Google Sheets

Using the BYROW function with XMATCH in Google Sheets allows us to match values...

Limit Formula Expansion to a Specific Row in Google Sheets

In this tutorial, I’ll explain how to limit the expansion of an array formula...

3-D Referencing Structured Data Tables in Google Sheets

When you have several tables within a single sheet—not across multiple sheets in a...

63 COMMENTS

  1. I was wondering if you are also able to add a row in between these two vertically stacked queries and auto-insert some text? Like so:

    {(Query 1);

    "Header for Query 2"

    Query 2;

    "Header text for query 3"

    Etc..)}

    • Hi David,

      Of course we can.

      Before that please note that I’ve just updated this tutorial. It was essential because we can now use VSTACK for this purpose.

      Here is the syntax for a formula that returns three columns:

      =VSTACK(qyery1,HSTACK(" "," "," "),query2,HSTACK(" "," "," "),query3)

      You can fill the blank spaces with the required headers. If you have two columns, replace HSTACK(" "," "," ") with HSTACK(" "," ").

  2. I was expecting the two queries to sort together one column, but instead, sort organizes them as separate queries.

    =sort({query(B8:O20,"Select B,M,O Where M Is Not Null");
    query(B8:O20,"Select B,N,O Where N Is Not Null")},2,TRUE)

    M and N are both dates.

    • Hi, Justin,

      I don’t find any issue with the SORT.

      This QUERY will also do the same sorting.

      =Query({query(B8:O20,"Select B,M,O Where M Is Not Null");
      query(B8:O20,"Select B,N,O Where N Is Not Null")},
      "Select * order by Col2 asc")

  3. Hi! But, if I need to combine more than 2 query formulas (for example, 3 or 4)?

    The spreadsheet returns me the Iferror formula that can contain not more than two elements.

    • Hi, Alberto,

      I need to see your data layout/structure before commenting.

      If possible, share a copy of your Sheet in the “Reply” below, which won’t be posted.

  4. I’m looking for a little help with a similar query.

    I am stacking two queries, where I have different criteria for each. It loads fine.

    This time I add a third query below the second to return the unique values of one column. It is to use for my data validation on the dashboard.

    I have worked around ‘Array Literal’ issues before by placing blank columns ‘ ‘ in the query results, but this isn’t working here. Ideas?

  5. Thanks, Prashanth! It works like a charm, but I’m having another problem now.

    If one query (I’m doing 29 queries to 29 different sheets in my formula) gives an empty output because no row matches the ‘where’ criteria, then I have a ‘VALUE’ error. I think exactly what this post is about 🙂

    Right now, I’m trying to figure out where to put the IFERROR to skip this problem in the syntax…

  6. Hi!

    Thanks a lot for your hard work! Your tutorials are guiding me to accomplish things I didn’t know we can do with Google Sheets!

    I have a question. I’m pretty sure the solution is easy, but I cannot find it.

    In this query:

    ={QUERY(IMPORTRANGE("URL1";"Hoja1!A10:P70");
    "select Col1,Col6,Col7,Col8,Col9,Col10,Col13,Col14,
    Col15 where Col6>0 or Col7>0 or Col8>0");
    QUERY(IMPORTRANGE("URL2";"Hoja1!A10:P70");
    "select Col1,Col6,Col7,Col8,Col9,Col10,Col13,Col14,
    Col15 where Col6>0 or Col7>0 or Col8>0")}

    How do I introduce a ‘blank row’ between the first query and the second one? My intention is visually separate the first result from the next one.

    Thank you again!

    • Hi, TassaDarK,

      Please follow the below syntax.

      ={query_1;ArrayFormula(iferror((sequence(1;9)/0)));query_2}

      Note:-

      1. query_1 and query_2 are your existing two Query Importrange formulas.
      2. The number 9 within Sequence represents the nine columns in your output. Change that when you select more columns in the SELECT clause.

  7. Thank you SO much for your help! This is a huge service you are doing, helping me understand the google sheet formulas better and giving me handheld guidance. May you continue having the energy to continue your good work!

  8. Thank you very much for this tutorial. It’s been very helpful!

    I am still stuck on a Query returning no data, it’s not displaying anything when I get to it.

    If I force it by putting in the match on that column, it works again, so I don’t think it’s a formula writing error.

    My query is this:

    =ARRAYFORMULA(IFERROR({iferror(QUERY('Form Responses'!A1:GH997, "SELECT AH, AI, AK, AL, AM, AZ, AW, AX, AY WHERE AL='Nursery (3 yr)' ",1), 'Form Responses'!AL/0); iferror(QUERY('Form Responses'!A1:GH997, "SELECT BA, BB, BD, BE, BF, BS, BP, BQ, BR WHERE BE='Nursery (3 yr)' LABEL BA '', BB '', BD '', BE '', BF '', BS '', BP '', BQ '', BR ''",1), 'Form Responses'!BE/0); iferror(QUERY('Form Responses'!A1:GH997, "SELECT BT, BU, BW, BX, `BY`, CL, CI, CJ, CK WHERE BX='Nursery (3 yr)' LABEL `BY` '', BT '', BU '', BX '', BW '', CL '', CI '', CJ '', CK ''",1),'Form Responses'!BX/0)}))

    If BX is not matched, nothing displays. If it does match, it renders beautifully. I’d appreciate any insight as I have another few queries to add to this!

      • I appreciate your help. I played around with it a little so my formula changed somewhat, but it’s still not working.

        Error

        “Circular dependency detected. To resolve with iterative calculation, see File > Spreadsheet Settings”

          • Wow, thank you! That was what I was missing! So my sheet works fine on that instance until I tried doing it for another grade level….then since there was no match on the first query, the labels showed, but none of the data.

            If I take out the first query where no match is found, the data displays fine. Why would that be?

            I am going to put it on the test page I shared before and I gave edit access since it’s not a publicly available link I see. I really appreciate your assistance with this!! You’ve been extremely helpful in helping me understand nested queries.

            • Hi, LN,

              Your combined Query formula returns the required results but moves down the rows due to the blank rows. See the rows 999 and 1000 in your sheet named “3s”.

              So, use SORT instead of ARRAYFORMULA. Further, remove the header row from each Query as it may cause issues while sorting.

              Please see “Copy of 3s – infoinspired” for the updated formula.

  9. I’ve scrolled through all the comments to see if I could find one with a similar issue but I can’t seem too.

    I’m using this spreadsheet [link removed by admin]

    Tab one is my form data, I’m trying to create a separate tab for each Grade. Because each row can contain multiple grades a simple filter won’t work.

    Instead, I’m using

    =SORT(IFERROR({IFERROR(QUERY('Form Results'!B:F,"Select B,C,D,E,F where E='Third'",0),B2:F2/0)}))

    which works fine until I expand it to include all the rest of the columns like this

    =SORT(IFERROR({IFERROR(QUERY('Form Results'!B:F,"Select B,C,D,E,F WHERE E='THIRD'",0),B1:F1/0);IFERROR(QUERY('Form Results'!H:J,"Select H,I,J WHERE I='THIRD'",0),H1:J1/0);IFERROR(QUERY('Form Results'!L:N,"Select L,M,N WHERE M='THIRD'",0),L1:N1/0);IFERROR(QUERY('Form Results'!P:R,"Select P,Q,R WHERE Q='THIRD'",0),P1:R1/0)}))

    At that point the query turns blank…can someone help?

    • Hi, Rachael Garbee,

      Your first Query formula itself is not correct! It should be like this.

      =SORT(IFERROR({IFERROR(QUERY('Form Results'!B:F,"Select B,C,D,E,F where E='Third'",0),'Form Results'!B2:F2/0)}))

      I hope you can understand the difference.

      Your scenario is entirely different. You want to combine two or more Query results but the number of columns from the second Query onwards are 3 (the first Query has 5 columns).

      You can find the tutorials related to your scenario here.

      1. Combine Two Tables with Different Number of Columns in Query.
      2. How to Insert Blank Columns in Google Sheets Query.

      Based on the above, here is my recommended formula for you to use.

      =ArrayFormula(Query({'Form Results'!B1:F;iferror({{" "," "}/row('Form Results'!A1:A)}),'Form Results'!H1:J;iferror({{" "," "}/row('Form Results'!A1:A)}),'Form Results'!L1:N;iferror({{" "," "}/row('Form Results'!A1:A)}),'Form Results'!P1:R},"Select * where lower(Col4)='third'",0))

      See if this helps?

      • I really appreciate your help.

        However, I’m still having an issue with my data.

        If a child in third grade (or any grade) is in one of the later queries it isn’t capturing the parent data that is in column a b/c that part of the query is happening first I think?

        Or if a parent has more than 1 child in third grade they are not populating in the sheet next to each other.

        I was hoping I could figure it out on my own but hours later I still haven’t *facepalm*

        • Hi, Rachael Garbee,

          If possible once again share that earlier file (sample file) with Edit mode. So that I can try and enter my formula.

          Note: I won’t publish the link.

  10. Hello, Genius out there.

    I have a problem and I don’t know how to solve it. In the below formula my data will only appear if the first set ASM has data.

    If ASM A2:AA is blank the rest of the sheet which has data doesn’t appear.

    =ARRAYFORMULA(IFERROR({IFERROR(QUERY({ASM!$A$2:$AA},"SELECT * WHERE Col4 IS NOT NULL",0),ASM!$A$2:$AA/0);IFERROR(QUERY({LAM!$A$2:$AA},"SELECT * WHERE Col4 IS NOT NULL",0),LAM!$A$2:$AA/0)}))

      • Hello Prashanth

        Thanks for your response. What I did is I consolidate all dates in the tab ASM, LAM, MY… to the tab Matching Table.

        ASM is the first tab and I notice that if there is no data in the first set ASM the vertically combined formula wouldn’t work.

        • Hi, Desmond,

          Thanks for sharing your sheet. Without that, I would be in the dark.

          See the tab “Prashanth” for the formula.

          Your Queried data is ASM!$A$2:$AA. So it must be ASM!$A$2:$AA2/0 not ASM!$A$2:$AA/0. It’s applicable to all the tabs (Query Data) that you are combining with Query.

  11. Did not work, as it turned all numbers into date format.

    Col7 is a date column on X Sheet & Col7, Col8 are dates on Y sheet

    • Now the picture is clear to me 🙂

      You just want to format certain date columns. In that case, the To_date function won’t work.

      Here is the workaround!

      From my formula remove the Iferror function. Then wrap the entire formula with another Query as below.

      =query(your_formula_here,"Select *",1)

      It worked for me. See the tab “Sheet3” in my example sheet (the sheet link you can find within the post shared in one of the previous replies to you).

      See if this helps?

      • Worked well for the date columns and the columns with numbers. But now the Col1, Col2, Col6 which contain ‘Text’, gives an error for the unfilled rows like “#DIV/0!”

        • Hi, VJ,

          I am sorry that I didn’t test my formula with columns that contain different types of values. As you have mentioned earlier, the issue was with IFERROR outside Query. So the solution is to use the IFERROR with the Sequence formula itself, that within the Query.

          I have modified “Sheet3” and the corresponding tutorial (link already shared above) to incorporate the changes. It was that much simple 🙂

          Thanks for your patience and your queries helped me to make the formula foolproof.

          • Worked flawlessly. I would like to thank you very much. Will be glad if you can share your email id. I might certainly have more queries in the sheet which am developing for myself. Thanks again.

  12. Thanks for the explanations, I would like to understand how to do a search and compare the results within the same query, or something similar to find out who is present in one subset and not present in another subset.

    Explanation of the query I need to produce:

    I have a table with 3 columns A=C_Name, B=Month, C=P_Amount, I need to find out which customers were present in a month, and not in the next month.

    "Select A,C Where A is present in Month(1) and not present in Month(2)"

    • Hi, Daniel Nanton Barral,

      Try this Query Pivot.

      =query(A1:C,"Select A, count(A) where A is not null group by A Pivot B",1)

      This Query will return a customer name column and month columns. In the month columns, the formula will return the count of the occurrence of the customers. Blank means, the customer does not appear in that month.

      • Thank you very much for the answer, will look into it, how would I be able to find out the customer name that appears say in the previous month, but not in the current month?

        • Hi, Daniel Nanton Barral,

          In my earlier answer, I’ve considered month names (text) in the month column.

          To answer this question, I just want to know the actual value in the month column. Is that date or month names in text like “Jan” or “January”?

  13. Hi, Prashanth!

    I’m trying this with an “importrange” function on my query, but I can’t figure out how to make it work. Any comment?

    – formula removed by admin –

  14. Is there a way to do this same thing but not have the header show up on the second query? I’m doing a SUM(J) in mine so the SUM shows have a header regardless of the 0 for the header option in the query.

    ={QUERY(Data1,"Select H, SUM(M) where H is not null and L is not null group by H order by H", 1);QUERY(Data2,"Select E, SUM(J) where E is not null and I is not null group by E order by E",0)}

    • Hi, Jason Dahl,

      Use the LABEL clause to remove that header.

      It will be something like this.

      ={QUERY(Data1,"Select H, SUM(M) where H is not null and L is not null group by H order by H", 1);QUERY(Data2,"Select E, SUM(J) where E is not null and I is not null group by E order by E label SUM(J)''",0)}

  15. Hello, I need to have a Query look in the same data to pull up different information from 2 columns … I’m using but it gives me a Parse error…. please help.

    ={QUERY({COMBINE!A1:G},"SELECT * WHERE LOWER(D) LIKE LOWER("""&B1&""")",1),QUERY({COMBINE!A1:G}, "SELECT * WHERE LOWER(A) LIKE LOWER("""&B1&""")",1})

    • Remove the curly braces around the range {COMBINE!A1:G}. Also, there is one more correction in the last part of the Query.

      ={QUERY(COMBINE!A1:G,"SELECT * WHERE LOWER(D) LIKE LOWER("""&B1&""")",1),QUERY(COMBINE!A1:G, "SELECT * WHERE LOWER(A) LIKE LOWER("""&B1&""")",1)}

      If you use the curly braces, then you must change the column identifiers. For example LOWER(D) to LOWER(Col4).

  16. Hi,

    I have combined 2 queries out of which returns blank data or N/A#

    Then I have tried using IFERROR for both queries and a common IFERROR for the entire formula along with ARRAYFORMULA at the beginning, the result is blank.

    I have also added the A2:C/0 at the end of the IFERROR to balance out. Still, the result is blank.

  17. I have the following simple query:

    ={QUERY(Sheet1!D2:E;"Select E");QUERY(Sheet2!A2:B;"Select A")}

    While both queries separately return a result, combining the 2 only returns the result from the first query.
    If I switch them in position, the results change, again only showing the outcome of the first query.

    p.s. adding commas instead of semicolons as per the example returns a formula parse error.

    Any thoughts?

    Kind regards,
    Christophe

    • Hi, Christophe,

      It’s because of the blank rows after the first Query output. Try this formula.

      ={QUERY(Sheet1!D2:E;"Select E where E is not null");QUERY(Sheet2!A2:B;"Select A where A is not null")}

      or this;

      =Query({QUERY(Sheet1!D2:E;"Select E ");QUERY(Sheet2!A2:B;"Select A")};"Select Col1 where Col1 is not null")

      Best,

      • Thanks!

        The issue was true that there were exactly 1000 rows between the 2 results. This means that all results where fetched but simply with the empty rows in between. Hard to spot.

        Thanks for this solution, that works indeed!

  18. I’m trying to set unique values and after that show the data by the last date. I’ve got to query the last date about my data, but I can’t get UNIQUE VALUES and after show the interested view.

    =QUERY(dataBase!$A$2:$N$20138;"select A, G, H, I, J, K, L where G > date '"&("2009-01-01")&"' and G <= date '"&("2030-12-31")&"'";1))

  19. I’ve learned about combining data horizontally, but why is the result showing mismatched row size? What should I do?

  20. Sorry, read your article again and understood!

    =SORT({QUERY( Sheet1!C2:P300 , "Select M where N = 'Ext'" , 1 );QUERY( Sheet1!D2:Q300 , "Select O where P = 'Ext'" , 1 )})

    Brilliant, thank you!

  21. Hi, thank you for this, I was able to combine the results of two columns into one list with this:

    ={QUERY( Sheet1!C2:P300 , "Select M where N = 'Ext'" , 1 );QUERY( Sheet1!D2:Q300 , "Select O where P = 'Ext'" , 1 )}

    Which is great, but I would love to be able to order them together alphabetically. I tried:

    ={QUERY( Sheet1!C2:P300 , "Select M where N = 'Ext' order by M" , 1 );QUERY( Sheet1!D2:Q300 , "Select O where P = 'Ext' order by O" , 1 )}

    But it just sorted each set individually and not together. Is there a way? Thanks for your help so far!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.