Create a Single-Column Index
In this step, you will create a sample table named users
and then create a single-column index on the email
column. Indexes are crucial for improving the performance of database queries, especially when dealing with large tables.
First, connect to the PostgreSQL database as the postgres
user:
sudo -u postgres psql
Now, create the users
table. Execute the following SQL command:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100),
created_at TIMESTAMP
);
This command creates a table named users
with columns for id
, username
, email
, and created_at
. The id
column is the primary key and automatically increments.
Next, insert some sample data into the users
table. Execute the following SQL commands:
INSERT INTO users (username, email, created_at) VALUES
('john_doe', '[email protected]', NOW());
INSERT INTO users (username, email, created_at) VALUES
('jane_smith', '[email protected]', NOW());
INSERT INTO users (username, email, created_at) VALUES
('peter_jones', '[email protected]', NOW());
INSERT INTO users (username, email, created_at) VALUES
('mary_brown', '[email protected]', NOW());
You have now inserted four rows of data into the users
table.
To speed up queries based on the email
column, create an index on the email
column. Execute the following SQL command:
CREATE INDEX idx_users_email ON users (email);
This command creates an index named idx_users_email
on the email
column of the users
table.
To verify that the index has been created, you can use the \di
command in psql
. Execute the following command:
\di
You should see the idx_users_email
index listed in the output.
Finally, exit the psql
shell by typing:
\q