Exclude mapped array elements

How can I exclude the consistent elements of one array from another?

Postgres Code:

a1 := '{1, 2, 5, 15}'::int[];
a2 := '{1, 2, 3, 6, 7, 9, 15}'::int[];

a3 := a2 ??magic_operator?? a1;

In a3I expect exactly "{3, 6, 7, 9}"

Final result

My and lad2025 solutions work great.

A solution with PostgreSQL 9.5array_position() is required , and then x3 runs faster.

+4
source share
3 answers

The add-on module intarrayprovides a simple and quick subtraction - for whole arrays, exactly the magic_operator you are looking for:

test=# SELECT '{1, 2, 3, 6, 7, 9, 15}'::int[] - '{1, 2, 5, 15}'::int[] AS result;
 ?column?
-----------
 {3,6,7,9}

You need to install the module once for each database:

CREATE EXTENSION intarray;

:

, :

... .

+1

XOR :

WITH set1 AS
(
 SELECT * FROM unnest('{1, 2, 5, 15}'::int[])
), set2 AS
(
 SELECT * FROM unnest('{1, 2, 3, 6, 7, 9, 15}'::int[])
), xor AS
(
  (SELECT * FROM set1
   UNION 
   SELECT * FROM set2)
  EXCEPT
  (SELECT * FROM set1
   INTERSECT 
   SELECT * FROM set2)
)
SELECT array_agg(unnest ORDER BY unnest)
FROM xor

:

"{3,5,6,7,9}"

:

  • SUM
  • INTERSECT
  • SUM - INTERSECT

():

(A+B) - (A^B)
<=>
(A-B) + (B-A)

FULL JOIN:

WITH set1 AS
(
 SELECT *
FROM unnest('{1, 2, 5, 15}'::int[])
), set2 AS
(
 SELECT *
 FROM unnest('{1, 2, 3, 6, 7, 9, 15}'::int[])
)
SELECT array_agg(COALESCE(s1.unnest, s2.unnest) 
                 ORDER BY COALESCE(s1.unnest, s2.unnest))
FROM set1 s1
FULL JOIN set2 s2
  ON s1.unnest = s2.unnest
WHERE s1.unnest IS NULL
  OR s2.unnest IS NULL;

EDIT:

, , , EXCEPT:

SELECT array_agg(unnest ORDER BY unnest)
FROM (SELECT * FROM unnest('{1, 2, 3, 6, 7, 9, 15}'::int[])
      EXCEPT
      SELECT * FROM unnest('{1, 2, 5, 15}'::int[])) AS sub

:

"{3,6,7,9}"
+2

.

SQL .

with elements (element) as (
   select unnest(ARRAY[1, 2, 3, 6, 7, 9, 15])
)
select array_agg(element)
from elements
where array_position(ARRAY[1, 2, 5, 15],element) is null

PostgreSQL 9.5 .

+1

Source: https://habr.com/ru/post/1624503/


All Articles