A brief introduction to PostgreSQL in the array _ database other

Source: Internet
Author: User
Tags numeric postgresql

PostgreSQL has many rich out-of-the-box data types, from standard numeric data types to geometric types and even network data types. Although many people ignore these data types, they are one of my favorite features. The array data type, as you would expect, can store array data in PostgreSQL, and with this feature you can implement storage requirements in a single table that require multiple tables in the past.

Why use arrays to store data, and if you're an application developer, use the same model in your database to store data in your program. Moreover, this approach can improve performance. Here we will describe how to use the PostgreSQL array type.


Suppose you purchase items on a website, the information you buy can be expressed in the following table:

CREATE TABLE purchases (
  ID integer not NULL,
  user_id integer,
  items Decimal (10,2) [100][1],
  occurred_ at timestamp
);

In this table, you have an array field to hold multiple merchandise records, including:

    • Number of items purchased
    • Number
    • Price

The SQL to insert data into this table is as follows:

INSERT into Purchases VALUES (1, Notoginseng, ' {{15.0, 1.0, 25.0}, {15.0, 1.0, 25.0}} ', now ());
INSERT into Purchases VALUES (2, 2, ' {{11.0, 1.0, 4.99}} ', now ());
A more practical example is the use of labels, which you can use to identify items you buy:


CREATE TABLE products (
  ID integer not NULL,
  title character varying (255),
  description text,
  tags text[] , price
  numeric (10,2)
);

You can use basic query statements to get the data:


SELECT title, Unnest (tags) items from


You can also use the Postgres Gin and Gist Index to quickly search for a product based on a specified label:

--Search where product contains tag IDs 1
and 2 SELECT
*  from product
where  tags @> array[1 2]
 
--Search where product contains tag IDs 1 OR 2
SELECT * from product
where  tags && Amp Array[1, 2]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.