In QGIS, take a polygon grid (named 'grid') and a multipolygon layer (named 'surfaces').
For each feature in surfaces, I want to union all features of the grid that are disjoint (not intersected) with. I need to do this with a virtual layer (datasets regularly updated and exported with an atlas).
I have tried this two solutions, they work but are extremely slow (4-5 minutes):
select s.id, st_union(g.geometry)
from grid g, surfaces s
where not(st_intersects(g.geometry,s.geometry)) -- st_dissolve also works but is slower...
group by s.id
select s.id, st_union(g.geometry)
from grid g
join surfaces s on not(st_intersects(g.geometry,a.geometry)) -- st_dissolve also works but is slower...
group by s.id
The problem seems to be the intersects. The time is about the same with or without st_union.
For testing, I tried to add a rule-based symbology to my grid, with this rule:
not(intersects($geometry, @atlas_geometry ))
And I get the result instantly. Why intersects is slow on the Virtual Layer and fast in symbology? And how can I get a fast result in the Virtual layer?
EDIT
What I want to achieve (without union to see the grid):

And with union, to calculate the area of each part of the grid:

'grid'and'surfaces'layers? What are the technical characteristics of your system? – Taras May 02 '21 at 12:32'surfaces'and show the empty spaces symbolized by the grid - and calculate area for each. – romainbh May 02 '21 at 15:56'grid'there are a lot of features (dependig of my QGIS projects, 2000 to 10000). In'surfaces'are only max 10 features. And my computer is "standard" Win10x64 i7 8Go ram. – romainbh May 02 '21 at 15:57