Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the utility of array type?

Tags:

postgresql

I'm totally newbie with postgresql but I have a good experience with mysql. I was reading the documentation and I've discovered that postgresql has an array type. I'm quite confused since I can't understand in which context this type can be useful within a rdbms. Why would I have to choose this type instead of using a classical one to many relationship?

Thanks in advance.

like image 731
Nicola Cossu Avatar asked Apr 22 '11 15:04

Nicola Cossu


People also ask

What are arrays what is their utility?

An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

What is array and its type?

An array type is a user-defined data type consisting of an ordered set of elements of a single data type. An ordinary array type has a defined upper bound on the number of elements and uses the ordinal position as the array index.

What is array explain type and advantages of array?

1) Array stores data elements of the same data type. 2) Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable name. This avoid the confusion of using multiple variables. 3) Arrays can be used for sorting data elements.

What is an array explain?

An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. Five values of type int can be declared as an array without having to declare five different variables (each with its own identifier).


1 Answers

I've used them to make working with trees (such as comment threads) easier. You can store the path from the tree's root to a single node in an array, each number in the array is the branch number for that node. Then, you can do things like this:

SELECT id, content
FROM nodes
WHERE tree = X
ORDER BY path -- The array is here.

PostgreSQL will compare arrays element by element in the natural fashion so ORDER BY path will dump the tree in a sensible linear display order; then, you check the length of path to figure out a node's depth and that gives you the indentation to get the rendering right.

The above approach gets you from the database to the rendered page with one pass through the data.

PostgreSQL also has geometric types, simple key/value types, and supports the construction of various other composite types.

Usually it is better to use traditional association tables but there's nothing wrong with having more tools in your toolbox.

like image 53
mu is too short Avatar answered Oct 01 '22 05:10

mu is too short