Created
February 23, 2016 16:45
-
-
Save teeparham/a5f430d0e5a878f449e9 to your computer and use it in GitHub Desktop.
PostgreSQL ARRAY
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# migrate | |
add_column :doges, :friends, :text, array: true, default: [] | |
# add an index | |
add_index :doges, :friends, using: :gin | |
# create a Doge | |
Doge.create(name: "Doge", friends: ["snoop", "snoopy"]) | |
# any Doge contains a friend snoop | |
Doge.where("friends @> array [?]", "snoop") | |
# ignore empty friends to speedup queries | |
Doge.where("friends <> '{}'").where("friends @> array [?]", "snoop") | |
# unique friends | |
Doge.where("friends <> '{}'").pluck("DISTINCT(UNNEST(friends))") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE doges ( | |
id integer, | |
name text, | |
friends text[] DEFAULT '{}'::text[] | |
); | |
# doges with friends containing "snoop": | |
SELECT * FROM doges WHERE (friends @> ARRAY['snoop']); | |
# uniq friends in all doges | |
SELECT DISTINCT(UNNEST(friends)) FROM doges WHERE (friends <> '{}'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment