0% found this document useful (0 votes)
44 views14 pages

Ceng301 Dbms Session 10

Uploaded by

grupsakli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views14 pages

Ceng301 Dbms Session 10

Uploaded by

grupsakli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CENG301 Database Management Systems

Session-10
Asst. Prof. Mustafa YENIAD
[email protected]
Creating a database
• The CREATE DATABASE statement allows you to create a new PostgreSQL database:
CREATE DATABASE database_name
WITH
[OWNER = role_name(the user)]
[TEMPLATE = template]
[ENCODING = encoding]
[LC_COLLATE = collate]
[LC_CTYPE = ctype]
[TABLESPACE = tablespace_name]
DBMS

[ALLOW_CONNECTIONS = true | false]


[CONNECTION LIMIT = max_concurrent_connection]
[IS_TEMPLATE = true | false ];

• To execute the CREATE DATABASE statement you need to have a superuser role or a special CREATEDB privilege!
• Additional parameters can be assigned for the new database (defaults to the template database):
• OWNER: Assign a role that will be the owner.
• TEMPLATE: The template database from which the new database is created (by default, PostgreSQL uses the template1).
• ENCODING: The character set encoding in the new database (i.e. UTF8).
• LC_COLLATE: Specify the local collation order (affects the sort order of string in the queries that contain the ORDER BY clause. i.e. tr_TR.UTF-8).
• LC_CTYPE: Specify the character classification (affects the classification of character e.g., lower, upper, and digit i.e. tr_TR.UTF-8).
• TABLESPACE: Specify the tablespace name for the new database (the default is the tablespace of the template database).
• ALLOW_CONNECTIONS: It is a boolean value (if it is false, you cannot connect to the database).
• CONNECTION LIMIT: Specify the maximum concurrent connections to the new database (-1 i.e. is unlimited. This parameter is useful in the shared
hosting environments where you can configure the maximum concurrent connections for a particular database).
• IS_TEMPLATE: If it is true, any user with the CREATEDB privilege can clone it. If false, only superusers or the database owner can clone it.
Creating a database
CREATE DATABASE mydb OWNER postgres;
\l # get list of databases

CREATE DATABASE my_lost_turkish


WITH
ENCODING='UTF8'
LC_COLLATE='tr_TR.UTF-8'
LC_CTYPE='tr_TR.UTF-8'
DBMS

CONNECTION LIMIT=-1
TEMPLATE=template1;

CREATE TABLE words (


turkish_words text LC_COLLATE 'tr_TR.UTF-8',
german_words text COLLATE 'de_DE.UTF-8',
);

See also: Connection Pooling: Using PgBouncer to improve performance and reduce the load on PostgreSQL
Creating a tablespace
• A tablespace is a location on the disk where PostgreSQL stores data files containing database objects e.g., indexes, and tables. PostgreSQL
uses a tablespace to map a logical name to a physical location on disk.
• PostgreSQL comes with two default tablespaces:
• pg_default: tablespace stores user data.
• pg_global: tablespace stores global data.
• Tablespaces allow you to control the disk layout of PostgreSQL. There are two main advantages of using tablespaces:
1. If a partition on which the cluster was initialized is out of space, you can create a new tablespace on a different partition and use it
until you reconfigure the system.
2. Second, you can use statistics to optimize database performance. For example, you can place the frequent access indexes or tables
DBMS

on devices that perform very fast e.g., solid-state devices, and put the tables containing archive data which is rarely used on
slower devices.

CREATE TABLESPACE tablespace_name


OWNER user_name
LOCATION directory_path;
• The following statement creates a new tablespace called ts_mydata with the physical location /usr/local/pgsql/mydata
CREATE TABLESPACE ts_mydata
LOCATION '/usr/local/pgsql/mydata';
\db; # list all tablespaces
# for example, to create a logistics database that uses the ts_primary tablespace:
CREATE DATABASE logistics
TABLESPACE ts_mydata;
Deleting a database
• Once a database is no longer needed, you can drop it by using the DROP DATABASE statement as follows:

DROP DATABASE IF EXISTS database_name;


• The DROP DATABASE statement deletes catalog entries and data directory permanently.
• This action cannot be undone so you have to use it with caution!
• Only superusers and the database owner can execute the DROP DATABASE statement.
• Additionally, you cannot execute the DROP DATABASE statement if the database still has active connections.
In this case, you need to disconnect from the database and connect to another database e.g., postgres to execute the DROP DATABASE
DBMS

statement.
• PostgreSQL also provides a utility program named dropdb that allows you to remove a database. (The dropdb executes the DROP
DATABASE statement behind the scenes).
DROP DATABASE logistics; # drops a database that has no active connection
• To delete the database that has active connections, you can follow these steps:
• First, find the activities associated with the database by querying the pg_stat_activity view:
SELECT * FROM pg_stat_activity WHERE datname = 'database_name';
• Second, terminate the active connections by issuing the following query and finally drop the database:
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'database_name';

DROP DATABASE database_name;


Change the structure of an existing table
• To change the structure of an existing table, you use PostgreSQL ALTER TABLE statement:

ALTER TABLE table_name action;


• PostgreSQL provides you with many actions:
• Add a column
• Drop a column
• Change the data type of a column
DBMS

• Rename a column
• Set a default value for the column.
• Add a constraint to a column.
• Rename a table
DROP TABLE IF EXISTS distros;

CREATE TABLE distros (


distro_id SERIAL PRIMARY KEY,
name VARCHAR(512) NOT NULL,
origin VARCHAR (1024) NOT NULL
);
Truncating an existing table
• To remove all data from a table, you use the DELETE statement. However, when you use the DELETE
statement to delete all data from a table that has a lot of data, it is not efficient and it may be very slow.
• In this case, you need to use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name;


• The TRUNCATE TABLE statement deletes all data from a table without scanning it. This is the reason why it is
faster than the DELETE statement.
DBMS

• In addition, the TRUNCATE TABLE statement reclaims the storage right away so you do not have to perform a
subsequent VACUUM operation, which is useful in the case of large tables.
• The TRUNCATE TABLE statement deletes all data from a table without scanning it. This is the reason why it is
faster than the DELETE statement.
• To delete all data from the i.e. invoices table:
TRUNCATE TABLE invoices;
• To delete all data from multiple tables (invoices, customers, etc.):

TRUNCATE TABLE invoices, customers;


Change the structure of an existing table
ALTER TABLE distros ADD COLUMN active BOOLEAN;

ALTER TABLE distros DROP COLUMN active BOOLEAN;

ALTER TABLE distros RENAME COLUMN name TO title;


DBMS

ALTER TABLE distros ALTER COLUMN title VARCHAR(100);

ALTER TABLE distros ALTER COLUMN title SET DEFAULT 'Linux';

ALTER TABLE distros RENAME TO 'types';

Note: All these actions can be done easily through pgAdmin interface.
PostgreSQL Copy DB
• Sometimes, you want to copy a PostgreSQL database within the same database server for testing purposes.
• PostgreSQL makes it easy to do it via the CREATE DATABASE statement as follows:

CREATE DATABASE targetdb


WITH TEMPLATE sourcedb;

• Depending on the size of the source database, it may take a while to complete copying.
DBMS

• The source database must not have active connections during the copy process (active connections have to be terminated).

sourcedb targetdb
PostgreSQL Backup DB
• Backing up databases is one of the most critical tasks in database administration.
• Before backing up the databases, you should consider the following type of backups:
• All (full) / partial databases
• Both data and structures, or only structures

• PostgreSQL comes with pg_dump and pg_dumpall tools that help you backup databases easily.
DBMS

Also review: https://www.postgresql.org/docs/current/app-pgdump.html


PostgreSQL Backup DB
• To backup databases quickly, first switch over to the postgres account on your server by typing:
$ sudo -i -u postgres
• Then:
postgres@[hostname]:~ $ pg_dump -U username -W -F t database_name > database_backup_file.tar

• Let’s look into the options in more detail:


DBMS

• -U username: specifies the user to connect to the PostgreSQL database server. We can use the postgres
user in this example.
• -W: forces pg_dump to prompt for the password before connecting to the PostgreSQL database server
• -F: specifies the output file format that can be one of the following:
• c: custom-format archive file format
• d: directory-format archive
• t: tar
• p: plain-text SQL script file
• We use -F t to specify the output file as a tar file in this example.
• database_name: is the name of the database that you want to back up.
• database_backup_file.tar is the output backup file.

Also review: https://www.postgresql.org/docs/current/app-pgdump.html


PostgreSQL Backup All DB Objects
• To back up all databases, you can run the individual pg_dump command sequentially, or parallel (by using
multiple terminal windows) if you want to speed up the backup process.
• Besides the pg_dump, PostgreSQL also provides you with the pg_dumpall tool that allows you to backup all
databases at once. However, it is not recommended to use this tool because of the following reasons:
• The pg_dumpall program exports all databases, one after another, into a single script file, which prevents you from
performing the parallel restore. If you back up all databases this way, the restore process will take more time.
• The processing of dumping all databases takes longer than each individual one so you do not know which dump of
each database relates to a specific point in time.
DBMS

• If you have a good reason to use the pg_dumpall to backup all databases, the following is the command:
• Firstly, switch over to the postgres account on your server by typing:
$ sudo -i -u postgres
• Then to backup all databases with data:
postgres@[hostname]:~ $ pg_dumpall -U postgres > all_databases_backup_file.sql
• To backup only database object definitions, not the data:
postgres@[hostname]:~ $ pg_dumpall --schema-only > all_definitions_backup_file.sql
✓ For roles use --roles-only
✓ For tablespaces use --tablespaces-only
PostgreSQL Restore DB
• In PostgreSQL, you can restore a database in two ways:
• Using psql to restore plain SQL script file generated by pg_dump and pg_dumpall tools.
• Using pg_restore to restore tar file and directory format created by the pg_dump tool.

• The psql tool allows you to restore the SQL script file generated by the pg_dump, pg_dumpall or
any other tools that generate compatible backed up files. By using the psql tool, you can execute the
entire script in the dump file.
DBMS

• To restore a full backup and ignore any error occurred during the restoration process, you use the
following command:

postgres@[hostname]:~ $ psql -U username -f backupfile.sql


• If you want to stop restoring a database in case of errors, you add the
--set ON_ERROR_STOP=on option:
postgres@[hostname]:~ $ psql -U username --set ON_ERROR_STOP=on -f backupfile.sql
PostgreSQL Restore DB
• Besides psql tool, you can use pg_restore program to restore databases backed up by the pg_dump or
pg_dumpall tools.
• Create a new database named newdvdrental for practicing with the pg_restore tool:
CREATE DATABASE newdvdrental;
• Then:
pg_restore --dbname=newdvdrental --verbose dvdrental.tar
DBMS

You might also like