Inserting data into the table
PostgreSQL is a powerful, open-source object-relational database system. One of the fundamental operations that you'll need to learn when working with databases is how to insert data into a table. This tutorial will guide you through the process step by step, explaining all the necessary details to understand how to insert data into a PostgreSQL table.
Creating a Table
Before we can insert data into a table, we need to have a table. For this tutorial, let's create a simple table named students
. This table will have three columns: id
, name
, and age
.
In PostgreSQL, you can create a new table using the CREATE TABLE
statement. The syntax is as follows:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Let's use this to create our students
table:
CREATE TABLE students (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
age INT
);
In this SQL statement, SERIAL
is an auto-incrementing integer, VARCHAR
is a variable length string, and INT
is an integer. PRIMARY KEY
is a constraint that enforces the uniqueness of the id
column.
Inserting Data
Now that we have a table, we can begin to insert data. In PostgreSQL, we use the INSERT INTO
statement to insert data into a table. The syntax is as follows:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Let's insert some data into our students
table:
INSERT INTO students (name, age)
VALUES ('John Doe', 20),
('Jane Doe', 22),
('Jim Doe', 19);
In this SQL statement, we're inserting three rows into the students
table. We don't need to specify a value for the id
column because it's an auto-incrementing integer.
Verifying the Insertion
To make sure our data was inserted correctly, we can retrieve it using the SELECT
statement. The syntax is as follows:
SELECT column1, column2, ...
FROM table_name;
Let's retrieve all data from our students
table:
SELECT *
FROM students;
This SQL statement will return all rows from the students
table. The *
is a wildcard character that means "all columns".
Conclusion
In this tutorial, you learned how to create a table in PostgreSQL and how to insert data into it. You also learned how to retrieve the inserted data to verify its correctness. These are fundamental skills you'll need when working with databases, and with practice, they'll soon become second nature.