Info |
---|
Collection types in databases refer to data types that can store multiple values or elements in a single column. They're often used when an attribute is multivalued, i.e., can take on more than one value at a time. It's worth noting that not all databases support collection types, and how they are implemented can vary widely. |
Three common types of collection types are:
Arrays: An array in a database is an ordered list of elements, all of the same data type. It is indexed, meaning you can access individual elements using their positions Each element in the array has an index, which is a number corresponding to its position in the array. PostgreSQL, for instance, supports arrays as a data typeIndexes usually start at 1 or 0, depending on the database system. Arrays can be one-dimensional (a simple list), or they can be multi-dimensional (an array of arrays). For example, you could define a column of type
integer[]
to hold an array of integers.Here is an example usage in PostgreSQL:
Code Block language sql CREATE TABLE inventory ( item_name text, quantities integer[] ); INSERT INTO inventory (item_name, quantities) VALUES ('ItemA', ARRAY[10, 20, 30]);
In the above example,
quantities
is an array that holds an integer array.Sets: A set is a collection of unique elements. Unlike arrays, sets are not ordered, so they do not have indexes. In terms of databases, some NoSQL databases like MongoDB and Cassandra use sets in their data modelsnot necessarily in any specific order. The distinguishing feature of a set is that it contains no duplicate values.
For example, you might use a set to represent a list of tags associated with a blog post:
Code Block language cql CREATE TABLE blog ( id uuid PRIMARY KEY, title text, tags set<text> ); INSERT INTO blog (id, title, tags) VALUES (uuid(), 'My First Blog Post', {'tag1', 'tag2', 'tag3'});
In the above example,
tags
is a set that holds a set of text.Multisets or Bags: A multiset (or bag) is Multisets are similar to a set but allows duplicate elements. Like a set, a multiset is not ordered.
...
sets, but they allow duplicate elements. They're not widely supported directly in relational database systems, but can be modeled using separate tables. For example, if you had a
blog
table and atag
table, you could create ablog_tag
table that allows duplicate tags:Code Block language sql CREATE TABLE blog_tag ( blog_id int, tag_id int, PRIMARY KEY (blog_id, tag_id) );
In the above example, a single blog could have the same tag multiple times, creating a multiset of tags.