Sql Insert Generate And Return Primary Key Postgresql

  • PostgreSQL - Need a way to return all results Question: Tag. Querying a view with no primary key sql,oracle,entity-framework,view,ef-code-first Our customer has given the access to views in which there is no primary key is defined. I know Entity Framework needs a primary key for table to identify. For example I could create a task (this.
  • The PostgreSQL PRIMARY KEY is a column in a table which must contain a unique value which can be used to identify each and every row of a table uniquely. So it can be said that the PRIMARY KEY of a table is a combination of NOT NULL and UNIQUE constraint.
  1. Sql Insert Generate And Return Primary Key Postgresql 10
  2. Sql Insert Generate And Return Primary Key Postgresql Download

The contactid column has a default values provided by the uuidgeneratev4 function, therefore, whenever you insert new row without specifying the value for the contactid column, PostgreSQL will call the uuidgeneratev4 function to generate the value for it. Second, insert.

Summary: in this tutorial, you will learn how to insert new rows into a table using the PostgreSQL INSERT statement.

When you create a new table, it does not have any data. The first thing you often do is to insert new rows into the table. PostgreSQL provides the INSERT statement that allows you to insert one or more rows into a table at a time.

PostgreSQL INSERT syntax

The following illustrates the syntax of the INSERT statement:

First, you specify the name of the table that you want to insert a new row after the INSERT INTO clause, followed by a comma-separated column list.

Second, you list a comma-separated value list after the VALUES clause. The value list must be in the same order as the columns list specified after the table name.

To add multiple rows into a table at a time, you use the following syntax:

You just need to add additional comma-separated value lists after the first list, each value in the list is separated by a comma (,).

Return

To insert data that comes from another table, you use the INSERT INTO SELECT statement as follows:

The WHERE clause is used to filter rows that allow you to insert partial data from the another_table into the table.

PostgreSQL INSERT examples

Let’s create a new table named linkfor the demonstration.

You will learn how to create a new table in the later tutorial, just execute the statement for now.

PostgreSQL insert one-row examples

The following statement inserts a new row into the linktable:

To insert character data, you must enclose it in single quotes (‘) for example 'PostgreSQL Tutorial'. For the numeric data type, you don’t need to do so, just use plain numbers such as 1, 2, 3.

If you omit any column that accepts the NULLvalue in the INSERT statement, the column will take its default value. In case the default value is not set for the column, the column will take the NULL value.

PostgreSQL provides a value for the serial column automatically so you do not and should not insert a value into the serial column.

You can verify the inserted row by using the SELECT statement:

If you want to insert a string that contains a single quote character such as O'Reilly Media, you have to use a single quote (‘) escape character as shown in the following query:

PostgreSQL insert multiple rows example

The following statement inserts multiple rows into the linktable at a time:

PostgreSQL insert date example

Let’s add a new column named last_updateinto the linktable and set its default value to CURRENT_DATE.

The following statement inserts a new row with specified date into the link table. The date format is YYYY-MM-DD.

You can also use the DEFAULTkeyword to set the default value for the date column or any column that has a default value.

PostgreSQL insert data from another table example

First, create another table named link_tmpthat has the same structure as the linktable:

Second, insert rows from the link table whose values of the date column are not NULL:

Third, verify the insert operation by querying data from the link_tmptable:

Get the last insert id

To get the last insert id from the table after inserting a new row, you use the RETURNINGclause in the INSERTstatement. This is a PostgreSQL extension to SQL.

The following statement inserts a new row into the linktable and returns the last insert id:


The id matches with the last insert id in the linktable:
In this tutorial, you have learned how to use the PostgreSQL INSERT statement to insert new rows into a table.

By: Maria Zakourdaev | Updated: 2019-08-15 | Comments | Related: More >T-SQL

Problem

A few days ago, one of the developers asked me if that was possible to generate test data by performing multiple nested INSERT statements, each of them involving inserting new rows into several parent tables and in the same statement reusing the autogenerated primary keys for the foreign key columns in the child table. The developer was working with PostgreSql and so I tried to find a solution for both PostgreSql and SQL Server to learn the differences in the ANSI features implementation in these different database systems.

Solution

Disclaimers

  1. The fastest data generation solution is as follows:
    1. Insert the required number of rows into each parent table
    2. Get the ids according to the data generation logic and use them to add rows to the child table

In this tip I will not be using the technique above, but try to do this all with just one statement.

On my laptop, I generated 100,000 rows using the below technique. In SQL Server it took 86 seconds compared to the 3 statements logic (like below) which took approximately 5 minutes.

  1. insert into 1st parent table + store output into the variable
  2. insert into 2st parent table + store output into the variable
  3. insert into a child table

ANSI Solution

There is a great feature in the ANSI standards that can be used exactly for this challenge, using a common table expression or CTE. A CTE is a temporary named result set, created from a simple query defined within an execution scope of SELECT, INSERT, UPDATE or DELETE statement.

In PostgreSql, CTE implementation includes data modification query scope. But in SQL Server, the CTEs query definition must meet a view’s requirements which means we cannot modify data inside a CTE.

In this tip I will show you a single statement solution I came up with in PostgreSql and SQL Server and I would love to hear your comments on how you would solve this challenge.

PostgreSql Approach to Load Data into Parent and Child Tables at the Same Time

Before we get started, here is the syntax for creating the three tables.

In PostgreSql, the solution to this challenge is quite simple, we will update two tables in the CTE and use the generated ids as foreign key ids in the third table.

SQL Server Approach to Load Data into Parent and Child Tables at the Same Time

Before we get started, here is the syntax for creating the three tables.

As I mentioned earlier, in SQL Server a CTEs query definition must meet a view’s requirements which means we cannot modify data inside the CTE.

We can use INSERT...OUTPUT construction, but another limitation in SQL Server for capturing the results of an OUTPUT clause in a nested INSERT, UPDATE, DELETE or MERGE statement, a target table cannot participate on either side of a FOREIGN KEY constraint.

Query execution failed: The target table 'dbo.salesorderheader' of the INSERT statement cannot be on either side of a (primary key, foreign key) relationship when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement.

Since we are generating the test data and this is not a production system, we can temporary disable foreign keys as follows:

We still cannot have two layers of nested INSERTs, because it is not possible to have two OUTPUT INTO clauses in the same statement:

SQL Error [10717] [S0001]: The OUTPUT INTO clause is not allowed when the FROM clause contains a nested INSERT, UPDATE, DELETE, or MERGE statement.

To overcome the issue, I have used INSERT EXEC construction, but in order to use both autogenerated keys in the OUTPUT statement, I need to have both of them in the inserted table. I have added a new column to the table salesperson for storing theid generated during product creation.

Sql insert generate and return primary key postgresql tutorial

And here is my final statement:

We have succeeded to insert two separate rows into two tables, generate 2 ids and used them in the third insert all in one statement. Take into consideration that this solution required disabling referential integrity keys which is not suggested for production environments.

If you come up with another way to implement the above query, without disabling the keys and without an additional column – I would love to see it. Please enter feedback in the comments section below.

Sql Insert Generate And Return Primary Key Postgresql 10

Next Steps

Last Updated: 2019-08-15



About the author
Maria Zakourdaev has been working with SQL Server for more than 15 years. She is also managing other database technologies such as MySQL, Postgresql, Redis, RedShift, CouchBase and ElasticSearch.
View all my tips

Sql Insert Generate And Return Primary Key Postgresql Download