- 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.
- Sql Insert Generate And Return Primary Key Postgresql 10
- 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 (,).
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 link
for 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 link
table:
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 NULL
value 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 link
table at a time:
PostgreSQL insert date example
Let’s add a new column named last_update
into the link
table 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 DEFAULT
keyword 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_tmp
that has the same structure as the link
table:
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_tmp
table:
Get the last insert id
To get the last insert id from the table after inserting a new row, you use the RETURNING
clause in the INSERT
statement. This is a PostgreSQL extension to SQL.
The following statement inserts a new row into the link
table and returns the last insert id:
The id matches with the last insert id in the link
table:
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
- The fastest data generation solution is as follows:
- Insert the required number of rows into each parent table
- 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.
- insert into 1st parent table + store output into the variable
- insert into 2st parent table + store output into the variable
- 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.
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:
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.
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
View all my tips