postgresql create table insert data

6.1. Insert data

When a table is created, there is no data in it. The first thing to do before the database can be useful is to insert data into it. Data is conceptually inserted one row at a time. Of course we can insert multiple rows at a time, but there is really no way to insert less than one row of data at a time. Even if you only know the values ​​of a few fields, then you must create a complete row.

To create a new row, we use the  INSERT  command. This command requires the name of the table and a value for each field in the table. For example, suppose  the product table from  Chapter 5 :

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric
);

The following is an example of inserting a row into the table:

INSERT INTO products VALUES (1, 'Cheese', 9.99);

The data values ​​are listed in the order in which these fields appear in the table, and are separated by commas. Usually, the data value is text (constant), but scalar expressions are also allowed.

The disadvantage of the above syntax is that you have to know the order of the fields in the table. To avoid this problem, you can also explicitly list the fields. For example, the following two commands have the same effect as the above command:

INSERT INTO products (product_no, name, price) VALUES (1, 'Cheese', 9.99);
INSERT INTO products (name, price, product_no) VALUES ('Cheese', 9.99, 1);

Many users think it is a good habit to explicitly list the field names.

If you don't get the values ​​of all the fields, then you can omit some of them. At this time, these fields will be filled with their default values. such as,

INSERT INTO products (product_no, name) VALUES (1, 'Cheese');
INSERT INTO products VALUES (1, 'Cheese');

The second form is an extension of PostgreSQL. It fills the number of fields with the number of values ​​we give from the left, and the others will be the default.

To keep things clear, you can also explicitly require default values, either for individual fields or for entire rows:

INSERT INTO products (product_no, name, price) VALUES (1, 'Cheese', DEFAULT);
INSERT INTO products DEFAULT VALUES;

Guess you like

Origin blog.csdn.net/qq_42533216/article/details/112860701