Ceng301 Dbms Session 10
Ceng301 Dbms Session 10
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
• 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
CONNECTION LIMIT=-1
TEMPLATE=template1;
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.
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';
• Rename a column
• Set a default value for the column.
• Add a constraint to a column.
• Rename a table
DROP TABLE IF EXISTS distros;
• 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.):
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:
• 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
• -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.
• 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: