Trabla: PostgreSQL: ARRAY: compare two arrays in query (array operators )
Solving:
For example we have table tbl_user_accounts
userid | accounts
1 | { 100, 101, 102 }
2 | { 200, 201, 202 }
3 | { 300, 301, 302 }
SQL:
CREATE TABLE tbl_user_accounts(
userid int NOT NULL PRIMARY KEY,
accounts int[] NOT NULL
);
INSERT INTO tbl_user_accounts(userid, accounts) VALUES ( 1, ARRAY[100,101,102]);
INSERT INTO tbl_user_accounts(userid, accounts) VALUES ( 2, ARRAY[200,201,202]);
INSERT INTO tbl_user_accounts(userid, accounts) VALUES ( 3, ARRAY[300,301,302]);
Operations:
1. Equal =
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts = ARRAY[ 100, 101, 102 ]
Result:
1 | "{100,101,102}"
2. Not Equal <>
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts <> ARRAY[ 100, 101, 102 ]
Result:
2 | "{200,201,202}"
3 | "{300,301,302}"
3. Less than <
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts < ARRAY[ 300, 101, 102 ]
Result:
1 | "{100,101,102}"
2 | "{200,201,202}"
4. Greater Than >
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts > ARRAY[ 300, 101, 102 ]
Result:
3 | "{300,301,302}"
5. Less Than Or Equal <=
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts <= ARRAY[ 101, 200 ]
Result:
1 | "{100,101,102}"
6. Greater than or equal >=
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts >= ARRAY[ 101, 200 ]
Result:
2 | "{200,201,202}"
3 | "{300,301,302}"
7. Contains @>
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts @> ARRAY[ 200, 202 ]
Result:
2 | "{200,201,202}"
8. Is Contained by <@
SELECT t.*
FROM tbl_user_accounts AS t
WHERE t.accounts <@ ARRAY[ 100, 101, 102, 200, 201, 202, 300, 301 ]
Result:
1 | "{100,101,102}"
2 | "{200,201,202}"
No comments:
Post a Comment