Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Three common types of collection types are:

  1. 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 type.Indexes 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
    languagesql
    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.

  2. 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
    languagecql
    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.

  3. 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.

...

  1. 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 a tag table, you could create a blog_tag table that allows duplicate tags:

    Code Block
    languagesql
    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.