DEV Community

Malik M
Malik M

Posted on

1

INSERT statement in PostgreSQL

In this tutorial, We will be exploring how to add new row in the existing table.
Let's get started...

The INSERT statement is used to insert a new row in the table.

Syntax

INSERT INTO table_name(column1, column2, …)
VALUES (value1, value2, …);
Enter fullscreen mode Exit fullscreen mode

In the above syntax, we can see that first we have specify the table name with the INSERT INTO keywords and the table will have list of comma-separated columns in the brackets.
Second, we have to provide values against each column after VALUES keyword, that must be in the same orders as columns are.
If you want to return the row that is just inserted use the following code in the end:

RETURNING *;
Enter fullscreen mode Exit fullscreen mode

If you want to return just some information, just specify the one or more column names after 'RETURNING' keyword like this:

RETURNING id;
Enter fullscreen mode Exit fullscreen mode

In the above code I am returning ID only.

EXAMPLE
Getting the last insert 'id':
Suppose we want to return the id of the last in the table Named links that has url and the name, 'id' and 'description' as columns.

INSERT INTO links (url, name)
VALUES('http://www.postgresql.org','PostgreSQL') 
RETURNING id;
Enter fullscreen mode Exit fullscreen mode

In the above code we are inserting 'url' and 'name' values and returning the id of the last insert.
OUTPUT

Image description

Conclusion

In this article we learnt about the 'INSERT' statement and it's example.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay