sqlunionuniverse

Single query gives more result than same query UNION another?


I'm not sure if I misunterstood a basic thing or if I have a problem with how my database interprets the query... Running universe

When I run

SELECT POIDSBRUT, PRIXBRUTU, FAMILLENU, TPSMOU, TPSMOUPLANIF, QTE1PLANIFMOU, OF5
FROM GPSOF
WHERE DFINPLANIFMOU >= '%1' AND DFINPLANIFMOU <= '%2' AND EQPLANIFMOU <> 'A placer' AND EQPLANIFMOU LIKE 'A%'

It gives me 5 results (everything is normal here).

But when I run

SELECT POIDSBRUT, PRIXBRUTU, FAMILLENU, TPSMOU, TPSMOUPLANIF, QTE1PLANIFMOU, OF5
FROM GPSOF
WHERE DFINPLANIFMOU >= '%1' AND DFINPLANIFMOU <= '%2' AND EQPLANIFMOU <> 'A placer' AND EQPLANIFMOU LIKE 'A%'
UNION 
SELECT POIDSBRUT, PRIXBRUTU, FAMILLENU, TPSMOU, TPSMOU2PLANIF, QTE2PLANIFMOU, OF5
FROM GPSOF
WHERE DFIN2PLANIFMOU >= '%1' AND DFIN2PLANIFMOU <= '%2' AND EQ2PLANIFMOU <> 'A placer' AND EQ2PLANIFMOU LIKE 'A%'
UNION 
SELECT POIDSBRUT, PRIXBRUTU, FAMILLENU, TPSMOU, TPSMOU3PLANIF, QTE3PLANIFMOU, OF5
FROM GPSOF 
WHERE DFIN3PLANIFMOU >= '%1' AND DFIN3PLANIFMOU <= '%2' AND EQ3PLANIFMOU <> 'A placer' AND EQ3PLANIFMOU LIKE 'A%'

I get only 2 results. Either I didn't understand how UNION is suposed to work or I have another problem with my database... Thanks


Solution

  • A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

    Source (nice blog post on UNION performance)