Professional Documents
Culture Documents
Table of Contents
Basics of PostgreSQL............................................................................................................................................3
What is PostgreSQL?..........................................................................................................................................................3
Tutorial Overview...............................................................................................................................................................3
PostgreSQL Features......................................................................................................................................................... 3
PostgreSQL Database Administration........................................................................................................................5
psql....................................................................................................................................................................................5
phpPgAdmin................................................................................................................................................................. 5
pgAdmin......................................................................................................................................................................... 5
Advantages of PostgreSQL.............................................................................................................................................. 6
Disadvantages of PostgreSQL........................................................................................................................................ 6
PostgreSQL Download and Installation.........................................................................................................7
PostgreSQL Installation on Windows.........................................................................................................................7
PostgreSQL Installation on Mac....................................................................................................................................9
Managing Databases in PostgreSQL............................................................................................................. 11
Getting up and Running with PostgreSQL............................................................................................................. 11
Connect to a PostgreSQL Server................................................................................................................................ 11
PostgreSQL Create DB.................................................................................................................................................... 12
PostgreSQL Creating a Table....................................................................................................................................... 14
CRUD Operations in PostgreSQL................................................................................................................... 17
Creating or Inserting some records into the newly created table -............................................................17
Reading/viewing the data from the table -...........................................................................................................18
Updating a record in the table -................................................................................................................................. 19
Deleting a record in the table -...................................................................................................................................19
PostgreSQL CRUD in PHP................................................................................................................................. 21
Index Page........................................................................................................................................................................... 21
Create.................................................................................................................................................................................... 25
Read....................................................................................................................................................................................... 27
Update...................................................................................................................................................................................29
Delete.................................................................................................................................................................................... 32
PostgreSQL CRUD in Python........................................................................................................................... 35
Understanding PostgreSQL..........................................................................................................................................35
Understanding psycopg2..............................................................................................................................................35
Connecting Python to PostgreSQL............................................................................................................................ 35
Creating a table in PostgreSQL................................................................................................................................... 35
Executing Basic PostgreSQL Queries in Python.................................................................................................. 35
Advanced PostgreSQL Queries in Python.............................................................................................................. 35
Getting Started with SQLAlchemy.............................................................................................................................36
Basics of PostgreSQL
What is PostgreSQL?
PostgreSQL is a lightweight and open-source RDBMS (Relational Database Management System). It
is extremely well accepted by the industry.
Tutorial Overview
In this tutorial, we are going to start with the installation of PostgreSQL. Then, we will learn
beginner-level topics of PostgreSQL language, such as creating a database, dropping a database,
selecting a database, selecting a table, updating a record, creating a table, deleting a record,
dropping a table, inserting a record, etc. Finally, we will implement Create, Read, Update and Delete
(CRUD) operations using a scripting language (e.g., Python or PHP).
PostgreSQL Features
It is one of the most popular databases supporting JSON (non-relational) and SQL for (relational)
queries. PostgreSQL is an object-relational database management system (ORDBMS). It contains
various advanced data types and robust feature sets, increasing the software's extensibility,
reliability, and integrity.
PostgreSQL includes multiple features designed to help the developers to develop the applications,
manage our data in the datasets, and managers can keep the data integrity and create Risk-tolerant
environments. Whenever a new release comes into the market, the PostgreSQL Global group of
developers will enhance the previous features and adds some new features based on the user's
demand.
Free to download: It is open-source, and we can easily download it from the official website of
PostgreSQL.
Compatible with several operation systems: PostgreSQL runs on all major operating systems
such as Microsoft Windows, Linux, MacOS X, UNIX (AIX, BSD, HP-UX, SGI IRIX, Solaris, and Tru64),
etc.
Compatible with Data Integrity: It supports data integrity which includes the following:
● Primary Keys
● UNIQUE, NOT NULL
● Foreign Keys
● Explicit Locks, Advisory Locks
● Exclusion Constraints
Support multiple features of SQL: PostgreSQL supports various features of SQL, which include the
followings:
Compatible with multiple data types: PostgreSQL support various data types, such as:
● Structured: Array, Date and Time, UUID (Universally Unique Identifier), Array, Range.
● Primitives: String, Integer, Boolean, Numeric.
● Customizations: Custom Types, Composite.
● Geometry: Polygon, Circle, Line, Point,
● Document: XML, JSON/JSONB, Key-value.
Highly extensible: PostgreSQL is highly extensible in several phases, which are as follows:
Secure: It is safe because it follows several security aspects, which are as follows:
Highly Reliable: It is highly reliable and also provides disaster recovery such as:
psql
It is a terminal-based front-end command-line tool; where we can directly enter the SQL queries or
run them from a file and we can also see the query results. It offers us many Meta commands and
several shells, such as automating extensive ranges of tasks and facilitating writing scripts.
phpPgAdmin
It is a web-based management tool for PostgreSQL and is built on the phpMyAdmin interface, which
was initially written for MySQL administration. The phpPgAdmin is written in PHP programming
language. It can be configured easily and provides simple data manipulation. It keeps up the slony
master-slave replication machine and is available in 27 languages. Here, we can import the SQL
scripts and Copy the data.
pgAdmin
It is one of PostgreSQL's most famous and open-source management and development platforms. It
can be used on various operating systems such as UNIX, Linux, Mac OS X, and Windows to achieve
PostgreSQL 9.2 and above versions.
Advantages of PostgreSQL
The benefits of PostgreSQL are as follows:
Disadvantages of PostgreSQL
The drawbacks of PostgreSQL are as follows:
● PostgreSQL does not support the various open-source applications as compared to MySQL.
● Creating replication is a bit complex.
● It is not maintained by one company.
● PostgreSQL speed performance is not as good as compared to different tools.
● It is slow compared to MySQL.
● Sometimes, the installation process is not easy for the learner.
Note: While you are installing PostgreSQL take note of the password and port number that you are
entering.
2. Select the Version: Choose the version of PostgreSQL you want to install. It is generally
recommended to select the latest stable version available.
3. Choose the Windows Platform: On the download page, scroll down to the Windows section
and select the Windows version that matches your operating system (32-bit or 64-bit).
4. Download the Installer: Click on the download link for the Windows installer package. The
installer package will have a name similar to "postgresql-[version]-[platform].exe".
5. Run the Installer: Once the download is complete, locate the downloaded installer package
and double-click it to start the installation process.
6. Follow the Installation Steps: The PostgreSQL installer will guide you through the
installation process. Follow the on-screen instructions and review and accept the license
agreement.
7. Choose the Installation Directory: During the installation, you will be prompted to select the
installation directory for PostgreSQL. You can choose the default directory or specify a
different one according to your preference.
8. Set the Password: During the installation process, you will also be prompted to set a
password for the PostgreSQL superuser (usually called "postgres"). This password is
important for accessing and managing the PostgreSQL database.
9. Choose the Components: In the component selection screen, you can choose the specific
components you want to install. By default, all components are selected, which is
recommended for most cases.
10. Select the Data Directory: The installer will ask you to select a data directory where
PostgreSQL will store its database files. You can choose the default location or specify a
different one if needed.
11. Complete the Installation: Once you have selected the desired options, click the "Next" or
"Install" button to start the installation. The installer will copy the necessary files and
complete the installation process.
12. Start PostgreSQL: After the installation is complete, you will be prompted to start the
PostgreSQL service. Ensure the "Launch Stack Builder at exit" option is checked and click
"Finish". This will open the Stack Builder utility.
13. Stack Builder Utility: In the Stack Builder utility, you can choose additional components,
extensions, or updates for PostgreSQL. You can skip this step for now and close the utility.
14. Verify the Installation: To verify that PostgreSQL is running, you can open the "pgAdmin"
tool. It should be available in the Start menu or you can search for it. Once opened, you
should see the PostgreSQL server listed in the server dashboard.
Congratulations! You have successfully installed PostgreSQL on your Windows system. You can now
use tools like pgAdmin or connect to the PostgreSQL server using SQL clients to interact with
databases and perform database operations.
Note: It is important to keep your PostgreSQL installation up to date with the latest security patches
and updates. Regularly check for updates on the PostgreSQL website and follow the recommended
upgrade process when new versions are released.
2. Select the Version: Choose the version of PostgreSQL you want to install. Typically, it's
recommended to select the latest stable version available.
3. Choose the macOS Platform: On the download page, scroll down to the macOS section and
select the macOS version that corresponds to your operating system.
4. Download the Installer: Click on the download link for the macOS installer package. The
installer package will have a name similar to "postgresql-[version]-[platform].dmg".
5. Run the Installer: Once the download is complete, locate the downloaded installer package
in your Downloads folder or the specified download location. Double-click the installer
package to start the installation process.
6. Follow the Installation Steps: The PostgreSQL installer will guide you through the
installation process. Follow the on-screen instructions, and make sure to review and accept
the license agreement.
7. Choose the Installation Type: During the installation, you will be prompted to choose the
installation type. Select the PostgreSQL installation option to install the PostgreSQL
database server.
8. Set the Password: During the installation process, you will also be prompted to set a
password for the PostgreSQL superuser (usually called "postgres"). This password is
important for accessing and managing the PostgreSQL database.
9. Complete the Installation: Once the installation is complete, you can exit the installer.
10. Start PostgreSQL: To start PostgreSQL, open the "Terminal" application on your Mac. You can
find it in the "Applications" folder under "Utilities". In the Terminal, type the following
command and press Enter:
pg_ctl -D /usr/local/var/postgres start
This command starts the PostgreSQL database server.
11. Verify the Installation: To verify that PostgreSQL is running, you can enter the following
command in the Terminal:
ps auxwww | grep postgres
If PostgreSQL is running properly, you should see several lines of output related to the
PostgreSQL server processes.
Congratulations! You have successfully installed and started PostgreSQL on your Mac. You can now
begin using PostgreSQL and interacting with databases using SQL queries.
Note: It's important to keep your PostgreSQL installation up to date with the latest security patches
and updates. Regularly check for updates on the PostgreSQL website and follow the recommended
upgrade process when new versions are released.
PostgreSQL Create DB
Your first task will be to create a database, and you can do so by right-clicking on the Databases tab
and then selecting New Database from the drop-down options. Let's create a database named
UIU_Courses.
On the SQL tab of the Create Database popup window you can see the SQL code for creating the
database.
WITH
OWNER = postgres
ENCODING = 'UTF8'
CONNECTION LIMIT = -1
IS_TEMPLATE = False;
Once the database is created, you can proceed with the next sections of this tutorial.
The specification gives us quite a little information on the columns of the table -
● The table's primary key should be course_id (note that only this one is bold) and its data
type should be an integer. A primary key is a constraint which enforces the column values to
be non-null and unique. It lets you uniquely identify a specific set of instances present in the
table.
● The rest of the information in the specification should be easy to interpret now.
To create a table, right-click on the newly created database UIU_Courses and select CREATE Script
from the options. You should get something similar to the following -
);
The general structure of a table creation query in PostgreSQL looks like this -
table_constraint table_constraint
We did not specify any table constraints while creating the table. That can be avoided for now.
Everything else is quite readable except for the keyword SERIAL. Serial in PostgreSQL lets you
create an auto-increment column. By default, it creates values of type integer. Serial frees us from
the burden of remembering the last inserted/updated primary key of a table, and it is a good
practice to use auto-increments for primary keys.
● A course name
● Faculty's name
● Course topic
The values for the column course_id will be handled by PostgreSQL itself. The general structure of
an insert query in PostgreSQL looks like this -
Note that you did not specify the primary keys explicitly. You will see its effects in a moment.
When you execute the above two queries, you should get the following result upon successful
insertions -
INSERT 0 1
Query returned successfully in 40 msec.
This is generally called a select query, and the generic structure of a select query looks like this -
SELECT
column_1,
column_2,
...
FROM
table_name;
If you want just to see the names of the courses, you can do so by -
UPDATE table
SET column1 = value1,
column2 = value2 ,...
WHERE
condition;
You will update the record where course_faculty = "Dr. Md. Saddam Hossain Mukta" and set the
course_name to "CSE-6001 Advanced Database Systems". You will then verify if the record is
updated. The query for doing this would be -
Let's see if your update query had the intended effect by running a select query -
You are going to delete the record where course_name = "Deep Learning in Python" and then verify
if the record is deleted. Following the structure, you can see that the following query should be able
to do this -
Keep in mind that the keywords are not case-sensitive in SQL, but the data is case-sensitive. This is
why you see a mixture of upper and lower case in the queries.
Index Page
<!DOCTYPE html>
<html>
<head>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap
.min.css" rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK
2Kadq2F9CUG65" crossorigin="anonymous">
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.b
undle.min.js"
integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYX
K/7HAuoJl+0I4" crossorigin="anonymous"></script>
</head>
<body>
<h4>Create Data</h4>
<div class="mb-3">
</div>
<div class="mb-3">
</div>
<div class="mb-3">
</div>
</form>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Course Name</th>
<th>Course Faculty</th>
<th>Topics</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$host = 'localhost';
$dbname = 'UIU_Courses';
$user = 'postgres';
$password = 'cse6001';
try {
$dsn = "pgsql:host=$host;dbname=$dbname";
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
die();
$stmt = $pdo->query($query);
echo "<tr>";
echo "<td>{$row['course_id']}</td>";
echo "<td>{$row['course_name']}</td>";
echo "<td>{$row['course_faculty']}</td>";
echo "<td>{$row['topics']}</td>";
echo "</tr>";
$pdo = null;
?>
</tbody>
</table>
</div>
</body>
</html>
Create
<?php
$host = 'localhost';
$dbname = 'UIU_Courses';
$user = 'postgres';
$password = 'cse6001';
try {
$dsn = "pgsql:host=$host;dbname=$dbname";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
die();
$course_name = $_POST['course_name'];
$course_faculty = $_POST['course_faculty'];
$topics = $_POST['topics'];
try {
$stmt = $pdo->prepare($query);
$stmt->bindValue(':column1', $course_name);
$stmt->bindValue(':column2', $course_faculty);
$stmt->bindValue(':column3', $topics);
$stmt->execute();
die();
$pdo = null;
?>
<button type="submit">Create</button>
</form>
Read
<?php
$host = 'localhost';
$dbname = 'UIU_Courses';
$user = 'postgres';
$password = 'cse6001';
try {
$dsn = "pgsql:host=$host;dbname=$dbname";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
die();
try {
$stmt = $pdo->query($query);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<br>";
die();
$pdo = null;
?>
Update
<?php
$host = 'localhost';
$dbname = 'UIU_Courses';
$user = 'postgres';
$password = 'cse6001';
try {
$dsn = "pgsql:host=$host;dbname=$dbname";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
die();
$id = $_POST['course_id'];
$course_name = $_POST['course_name'];
$course_faculty = $_POST['course_faculty'];
$topics = $_POST['topics'];
try {
$stmt = $pdo->prepare($query);
$stmt->bindValue(':column1', $course_name);
$stmt->bindValue(':column2', $course_faculty);
$stmt->bindValue(':column3', $topics);
$stmt->bindValue(':id', $id);
$stmt->execute();
die();
$pdo = null;
?>
<button type="submit">Update</button>
</form>
Delete
<?php
$host = 'localhost';
$dbname = 'UIU_Courses';
$user = 'postgres';
$password = 'cse6001';
try {
$dsn = "pgsql:host=$host;dbname=$dbname";
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
die();
$id = $_POST['course_id'];
try {
$stmt = $pdo->prepare($query);
$stmt->bindValue(':id', $id);
$stmt->execute();
die();
$pdo = null;
?>
<button type="submit">Delete</button>
</form>