Create and Populate a Database
In this step, you will create a PostgreSQL database named mydatabase
and populate it with some sample data. This database will be used for the backup and restore exercises in the following steps.
First, create the mydatabase
database using the following command:
sudo -u postgres psql -c "CREATE DATABASE mydatabase;"
This command connects to the PostgreSQL server as the postgres
user and executes the SQL command CREATE DATABASE mydatabase
.
Next, connect to the mydatabase
database using the psql
command:
sudo -u postgres psql -d mydatabase
You should now be in the psql
shell, connected to the mydatabase
database. You'll see a prompt like mydatabase=#
.
Now, create a table named users
with an id
and name
column:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(255)
);
This SQL command creates a table named users
with two columns: id
(an automatically incrementing integer) and name
(a string).
Next, insert some sample data into the users
table:
INSERT INTO users (name) VALUES ('Alice');
INSERT INTO users (name) VALUES ('Bob');
These SQL commands insert two rows into the users
table, with the names 'Alice' and 'Bob'.
Finally, create another table named products
and insert some data:
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(255)
);
INSERT INTO products (name) VALUES ('Laptop');
INSERT INTO products (name) VALUES ('Tablet');
To verify that the tables and data have been created successfully, you can run the following SQL queries:
SELECT * FROM users;
SELECT * FROM products;
You should see the data you just inserted.
Exit the psql
shell by typing:
\q
You are now back in the Linux terminal.