Skip to content

Instantly share code, notes, and snippets.

@teeparham
Created February 23, 2016 16:45
Show Gist options
  • Save teeparham/a5f430d0e5a878f449e9 to your computer and use it in GitHub Desktop.
Save teeparham/a5f430d0e5a878f449e9 to your computer and use it in GitHub Desktop.
PostgreSQL ARRAY
# 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))")
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