Managing a PostgreSQL Database with pgAdmin
Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).
This tutorial will guide you through the steps to create and manage a table in PostgreSQL using pgAdmin. We will cover creating a table, inserting data, querying data, updating data, deleting records, altering the table, and dropping the table.
Prerequisites
pgAdmin Installed: Ensure you have pgAdmin installed and running.
PostgreSQL Database: You should have access to a PostgreSQL database.
Steps
Step 1: Accessing pgAdmin
Open pgAdmin and log in with your credentials.
In the left sidebar, navigate to your PostgreSQL server and expand the database where you want to create the table.
Step 2: Creating a Table
Right-click on the Schemas folder, then choose Create > Table.
In the Create - Table dialog:
Name your table (e.g.,
employees).Go to the Columns tab.
Click on the Add button to create the following columns:
id: Type
SERIAL, check the Primary Key box.name: Type
VARCHAR, length100.position: Type
VARCHAR, length50.salary: Type
NUMERIC.
Click Save to create the table.
Step 3: Inserting Data
Right-click on the employees table and select Query Tool.
In the query editor, enter the following SQL command to insert data:
sql
Copy
INSERT INTO employees (name, position, salary) VALUES ('Alice', 'Developer', 70000), ('Bob', 'Manager', 80000);Click the Execute/Refresh button (lightning bolt icon) to run the query.
Step 4: Querying Data
In the Query Tool, you can retrieve all data from the employees table with:
sql
Copy
SELECT * FROM employees;To filter results, use a
WHEREclause. For example, to find employees with a salary greater than 75,000:sql
Copy
SELECT * FROM employees WHERE salary > 75000;Execute the query to view the results.
Step 5: Updating Data
To modify existing data, use the
UPDATEstatement. In the Query Tool, enter:sql
Copy
UPDATE employees SET salary = 75000 WHERE name = 'Alice';Execute the query to apply the changes.
Step 6: Deleting Data
To delete records, use the
DELETE FROMstatement. For example, to remove Bob from the table:sql
Copy
DELETE FROM employees WHERE name = 'Bob';Execute the query to delete the record.
Step 7: Altering the Table
To add a new column (e.g.,
hire_date), use theALTER TABLEstatement:sql
Copy
ALTER TABLE employees ADD COLUMN hire_date DATE;To drop a column, use:
sql
Copy
ALTER TABLE employees DROP COLUMN hire_date;Execute the queries as needed.
Step 8: Dropping a Table
If you no longer need the table, you can remove it with:
sql
Copy
DROP TABLE employees;Execute the query to permanently delete the table.