Postgresql Tutorial
Postgresql Tutorial
PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX,
SGI IRIX, Mac OS X, Solaris, Tru64), and Windows.
This tutorial will give you quick start with PostgreSQL and make you comfortable with
PostgreSQL programming.
Audience
This tutorial has been prepared for the beginners to help them understand the basic to
advanced concepts related to PostgreSQL Database.
Prerequisites
Before you start practicing with various types of examples given in this reference, I'm
making an assumption that you are already aware about what is database, especially
RDBMS and what is a computer programming language.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
PostgreSQL
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
ii
PostgreSQL
iii
PostgreSQL
iv
PostgreSQL
v
PostgreSQL
vi
1. PostgreSQL Overview PostgreSQL
PostgreSQL is a powerful, open source object-relational database system. It has more than
15 years of active development phase and a proven architecture that has earned it a strong
reputation for reliability, data integrity, and correctness.
This tutorial will give you a quick start with PostgreSQL and make you comfortable with
PostgreSQL programming.
What is PostgreSQL?
PostgreSQL (pronounced as post-gress-Q-L) is an open source relational database
management system (DBMS) developed by a worldwide team of volunteers. PostgreSQL
is not controlled by any corporation or other private entity and the source code is available
free of charge.
2. 1986-1994: POSTGRES
Development of the concepts in INGRES with a focus on object orientation and the
query language - Quel
The code base of INGRES was not used as a basis for POSTGRES
Commercialized as Illustra (bought by Informix, bought by IBM)
3. 1994-1995: Postgres95
1
PostgreSQL
PostgreSQL supports a large part of the SQL standard and offers many modern features
including the following:
Data types
Functions
Operators
Aggregate functions
Index methods
2
2. PostgreSQL Environment Setup PostgreSQL
To start understanding the PostgreSQL basics, first let us install the PostgreSQL. This
chapter explains about installing the PostgreSQL on Linux, Windows and Mac OS platforms.
Pick the version number of PostgreSQL you want and, as exactly as possible, the
platform you want from EnterpriseDB
Once you launch the installer, it asks you a few basic questions like location of the
installation, password of the user who will use database, port number, etc. So keep
all of them at their default values except password, which you can provide password
as per your choice. It will install PostgreSQL at your Linux machine and will display
the following message:
[root@host]# su - postgres
Password:
3
PostgreSQL
You can start/restart postgres server in case it is not running, using the following
command:
If your installation was correct, you will have PotsgreSQL prompt test=# as shown
above.
Pick the version number of PostgreSQL you want and, as exactly as possible, the
platform you want from EnterpriseDB
4
PostgreSQL
The next step of the installation process would be to select the directory where
your data would be stored. By default, it is stored under the "data" directory.
Next, the setup asks for password, so you can use your favorite password.
5
PostgreSQL
In the next step, when asked for "Locale", I selected "English, United States".
6
PostgreSQL
After the installation process is completed, you can access pgAdmin III, StackBuilder and
PostgreSQL shell from your Program Menu under PostgreSQL 9.2.
Pick the latest version number of PostgreSQL for Mac OS available at EnterpriseDB
7
PostgreSQL
Next, click the postgres-9.2.4-1-osx icon, which will give a warning message.
Accept the warning and proceed for further installation. It will ask for the
administrator password as seen in the following window:
Enter the password, proceed for the installation, and after this step, restart your
Mac machine. If you do not see the following window, start your installation once
again.
8
PostgreSQL
Once you launch the installer, it asks you a few basic questions like location of the
installation, password of the user who will use database, port number etc.
Therefore, keep all of them at their default values except the password, which you
can provide as per your choice. It will install PostgreSQL in your Mac machine in
the Application folder which you can check:
Now, you can launch any of the program to start with. Let us start with SQL Shell.
When you launch SQL Shell, just use all the default values it displays except, enter
your password, which you had selected at the time of installation. If everything
9
PostgreSQL
goes fine, then you will be inside postgres database and a postgress# prompt will
be displayed as shown below:
Congratulations!!! Now you have your environment ready to start with PostgreSQL
database programming.
10
3. PostgreSQL Syntax PostgreSQL
This chapter provides a list of the PostgreSQL SQL commands, followed by the precise
syntax rules for each of these commands. This set of commands is taken from the psql
command-line tool. Now that you have Postgres installed, open the psql as:
Using psql, you can generate a complete list of commands by using the \help command.
For the syntax of a specific command, use the following command:
ABORT
Abort the current transaction.
ALTER AGGREGATE
Change the definition of an aggregate function.
11
PostgreSQL
ALTER CONVERSION
Change the definition of a conversion.
ALTER DATABASE
Change a database specific parameter.
ALTER DOMAIN
Change the definition of a domain specific parameter.
ALTER FUNCTION
Change the definition of a function.
ALTER GROUP
Change a user group.
12
PostgreSQL
ALTER INDEX
Change the definition of an index.
ALTER LANGUAGE
Change the definition of a procedural language.
ALTER OPERATOR
Change the definition of an operator.
ALTER SCHEMA
Change the definition of a schema.
ALTER SEQUENCE
Change the definition of a sequence generator.
13
PostgreSQL
ALTER TABLE
Change the definition of a table.
ALTER TABLESPACE
Change the definition of a tablespace.
ALTER TRIGGER
Change the definition of a trigger.
14
PostgreSQL
ALTER TYPE
Change the definition of a type.
ALTER USER
Change a database user account.
ANALYZE
Collect statistics about a database.
BEGIN
Start a transaction block.
CHECKPOINT
Force a transaction log checkpoint.
CHECKPOINT
15
PostgreSQL
CLOSE
Close a cursor.
CLOSE name
CLUSTER
Cluster a table according to an index.
COMMENT
Define or change the comment of an object.
COMMENT ON
{
TABLE object_name |
COLUMN table_name.column_name |
AGGREGATE agg_name (agg_type) |
CAST (source_type AS target_type) |
CONSTRAINT constraint_name ON table_name |
CONVERSION object_name |
DATABASE object_name |
DOMAIN object_name |
FUNCTION func_name (arg1_type, arg2_type, ...) |
INDEX object_name |
LARGE OBJECT large_object_oid |
OPERATOR op (left_operand_type, right_operand_type) |
OPERATOR CLASS object_name USING index_method |
[ PROCEDURAL ] LANGUAGE object_name |
RULE rule_name ON table_name |
SCHEMA object_name |
SEQUENCE object_name |
TRIGGER trigger_name ON table_name |
TYPE object_name |
VIEW object_name
} IS 'text'
16
PostgreSQL
COMMIT
Commit the current transaction.
COPY
Copy data between a file and a table.
17
PostgreSQL
CREATE AGGREGATE
Define a new aggregate function.
CREATE CAST
Define a new cast.
CREATE CONVERSION
Define a new conversion.
CREATE DATABASE
18
PostgreSQL
CREATE DOMAIN
Define a new domain.
[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | CHECK (expression) }
CREATE FUNCTION
Define a new function.
CREATE GROUP
Define a new user group.
19
PostgreSQL
CREATE INDEX
Define a new index.
CREATE LANGUAGE
Define a new procedural language.
CREATE OPERATOR
Define a new operator.
20
PostgreSQL
CREATE RULE
Define a new rewrite rule.
CREATE SCHEMA
Define a new schema.
CREATE SEQUENCE
Define a new sequence generator.
CREATE TABLE
Define a new table.
21
PostgreSQL
)
[ INHERITS ( parent_table [, ... ] ) ]
[ WITH OIDS | WITHOUT OIDS ]
[ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
[ TABLESPACE tablespace ]
[ CONSTRAINT constraint_name ]
{ NOT NULL |
NULL |
UNIQUE [ USING INDEX TABLESPACE tablespace ] |
PRIMARY KEY [ USING INDEX TABLESPACE tablespace ] |
CHECK (expression) |
REFERENCES ref_table [ ( ref_column ) ]
[ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
[ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
[ CONSTRAINT constraint_name ]
{ UNIQUE ( column_name [, ... ] ) [ USING INDEX TABLESPACE tablespace ] |
PRIMARY KEY ( column_name [, ... ] ) [ USING INDEX TABLESPACE tablespace ] |
CHECK ( expression ) |
FOREIGN KEY ( column_name [, ... ] )
REFERENCES ref_table [ ( ref_column [, ... ] ) ]
[ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ]
[ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
CREATE TABLE AS
Define a new table from the results of a query.
22
PostgreSQL
CREATE TABLESPACE
Define a new tablespace.
CREATE TRIGGER
Define a new trigger.
CREATE TYPE
Define a new data type.
CREATE USER
Define a new database user account.
23
PostgreSQL
SYSID uid
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
| CREATEDB | NOCREATEDB
| CREATEUSER | NOCREATEUSER
| IN GROUP group_name [, ...]
| VALID UNTIL 'abs_time'
CREATE VIEW
Define a new view.
DEALLOCATE
Deallocate a prepared statement.
DECLARE
Define a cursor.
DELETE
Delete rows of a table.
DROP AGGREGATE
Remove an aggregate function.
DROP CAST
Remove a cast.
24
PostgreSQL
DROP CONVERSION
Remove a conversion.
DROP DATABASE
Remove a database.
DROP DOMAIN
Remove a domain.
DROP FUNCTION
Remove a function.
DROP GROUP
Remove a user group.
DROP INDEX
Remove an index.
DROP LANGUAGE
Remove a procedural language.
DROP OPERATOR
Remove an operator.
25
PostgreSQL
DROP RULE
Remove a rewrite rule.
DROP SCHEMA
Remove a schema.
DROP SEQUENCE
Remove a sequence.
DROP TABLE
Remove a table.
DROP TABLESPACE
Remove a tablespace.
DROP TRIGGER
Remove a trigger.
DROP TYPE
Remove a data type.
26
PostgreSQL
DROP USER
Remove a database user account.
DROP VIEW
Remove a view.
END
Commit the current transaction.
EXECUTE
Execute a prepared statement.
EXPLAIN
Show the execution plan of a statement.
FETCH
Retrieve rows from a query using a cursor.
NEXT
PRIOR
FIRST
LAST
ABSOLUTE count
RELATIVE count
count
ALL
FORWARD
FORWARD count
27
PostgreSQL
FORWARD ALL
BACKWARD
BACKWARD count
BACKWARD ALL
GRANT
Define access privileges.
INSERT
Create new rows in a table.
28
PostgreSQL
LISTEN
Listen for a notification.
LISTEN name
LOAD
Load or reload a shared library file.
LOAD 'filename'
LOCK
Lock a table.
MOVE
Position a cursor.
NOTIFY
Generate a notification.
NOTIFY name
PREPARE
Prepare a statement for execution.
REINDEX
Rebuild indexes.
29
PostgreSQL
RELEASE SAVEPOINT
Destroy a previously defined savepoint.
RESET
Restore the value of a runtime parameter to the default value.
RESET name
RESET ALL
REVOKE
Remove access privileges.
30
PostgreSQL
ROLLBACK
Abort the current transaction.
ROLLBACK TO SAVEPOINT
Roll back to a savepoint.
SAVEPOINT
Define a new savepoint within the current transaction.
SAVEPOINT savepoint_name
SELECT
Retrieve rows from a table or view.
31
PostgreSQL
SELECT INTO
Define a new table from the results of a query.
SET
Change a runtime parameter.
SET CONSTRAINTS
Set constraint checking modes for the current transaction.
32
PostgreSQL
Set the session user identifier and the current user identifier of the current session.
SET TRANSACTION
Set the characteristics of the current transaction.
SHOW
Show the value of a runtime parameter.
SHOW name
SHOW ALL
START TRANSACTION
Start a transaction block.
TRUNCATE
Empty a table.
UNLISTEN
33
PostgreSQL
UNLISTEN { name | * }
UPDATE
Update rows of a table.
VACUUM
Garbage-collect and optionally analyze a database.
34
4. PostgreSQL Data Type PostgreSQL
In this chapter, we will discuss about the data types used in PostgreSQL. While creating
table, for each column, you specify a data type, i.e., what kind of data you want to store
in the table fields.
Validation: Proper use of data types implies format validation of data and rejection
of data outside the scope of data type.
Performance: Proper use of data types gives the most efficient storage of data.
The values stored can be processed quickly, which enhances the performance.
PostgreSQL supports a wide set of Data Types. Besides, users can create their own custom
data type using CREATE TYPE SQL command. There are different categories of data types
in PostgreSQL. They are discussed below.
Numeric Types
Numeric types consist of two-byte, four-byte, and eight-byte integers, four-byte and eight-
byte floating-point numbers, and selectable-precision decimals. The following table lists
the available types.
Storage
Name Description Range
Size
-2147483648 to
integer 4 bytes typical choice for integer
+2147483647
-
9223372036854775808
bigint 8 bytes large-range integer
to
9223372036854775807
up to 131072 digits
before the decimal
decimal variable user-specified precision,exact point; up to 16383
digits after the decimal
point
35
PostgreSQL
up to 131072 digits
before the decimal
numeric variable user-specified precision,exact point; up to 16383
digits after the decimal
point
6 decimal digits
real 4 bytes variable-precision,inexact
precision
15 decimal digits
double precision 8 bytes variable-precision,inexact
precision
1 to
bigserial 8 bytes large autoincrementing integer
9223372036854775807
Monetary Types
The money data type stores a currency amount with a fixed fractional precision. Values of
the numeric, int, and bigint data types can be cast to money. Using Floating point numbers
is not recommended to handle money due to the potential for rounding errors.
Storage
Name Description Range
Size
-92233720368547758.08 to
money 8 bytes currency amount
+92233720368547758.07
Character Types
The table given below lists the general-purpose character types available in PostgreSQL.
Name Description
character varying(n), varchar(n) variable-length with limit
36
PostgreSQL
bytea 1 or 4 bytes plus the actual binary string variable-length binary string
Date/Time Types
PostgreSQL supports a full set of SQL date and time types, as shown in table below. Dates
are counted according to the Gregorian calendar. Here, all the types have resolution of 1
microsecond / 14 digits except date type, whose resolution is day.
time [ (p)] [
time of day (no
without time 8 bytes 00:00:00 24:00:00
date)
zone ]
interval -178000000
12 bytes time interval 178000000 years
[fields ] [(p) ] years
Boolean Type
PostgreSQL provides the standard SQL type Boolean. The Boolean data type can have the
states- true, false, and a third state, unknown, which is represented by the SQL null value.
37
PostgreSQL
Enumerated Type
Enumerated (enum) types are data types that comprise a static, ordered set of values.
They are equivalent to the enum types supported in a number of programming languages.
Unlike other types, Enumerated Types need to be created using CREATE TYPE command.
This type is used to store a static, ordered set of values. For example compass directions,
i.e., NORTH, SOUTH, EAST, and WEST or days of the week as shown below:
CREATE TYPE week AS ENUM ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
Geometric Type
Geometric data types represent two-dimensional spatial objects. The most fundamental
type, the point, forms the basis for all of the other types.
38
PostgreSQL
Name Description
This is a sorted list of distinct words that have been normalized to merge
tsvector
different variants of the same word, called as "lexemes".
This stores lexemes that are to be searched for, and combines them honoring
tsquery the Boolean operators & (AND), | (OR), and ! (NOT). Parentheses can be used
to enforce grouping of the operators.
UUID Type
A UUID (Universally Unique Identifiers) is written as a sequence of lower-case hexadecimal
digits, in several groups separated by hyphens, specifically a group of eight digits, followed
by three groups of four digits, followed by a group of 12 digits, for a total of 32 digits
representing the 128 bits.
XML Type
The XML data type can be used to store XML data. For storing XML data, first you have to
create XML values using the function xmlparse as follows:
39
PostgreSQL
JSON Type
The json data type can be used to store JSON (JavaScript Object Notation) data. Such
data can also be stored as text, but the json data type has the advantage of checking that
each stored value is a valid JSON value. There are also related support functions available,
which can be used directly to handle JSON data type as follows-
row_to_json(row(1,'foo')) {"f1":1,"f2":"foo"}
Array Type
PostgreSQL gives the opportunity to define a column of a table as a variable length
multidimensional array. Arrays of any built-in or user-defined base type, enum type, or
composite type can be created.
Declaration of Arrays
Array type can be declared as-
Inserting values
Array values can be inserted as a literal constant, enclosing the element values within
curly braces and separating them by commas. An example is shown below.
40
PostgreSQL
Accessing Arrays
An example for accessing Arrays is shown below. The command given below will select the
persons whose savings are more in second quarter than fourth quarter.
Modifying Arrays
An example of modifying arrays is as shown below.
Searching Arrays
An example of searching arrays is as shown below.
If the size of array is known, the search method given above can be used. Else, the
following example shows how to search when the size is not known.
Composite Types
This type represents a list of field names and their data types, i.e., structure of a row or
record of a table.
41
PostgreSQL
This is valid for the inventory_item defined above. The ROW keyword is actually optional
as long as you have more than one field in the expression.
You can even use the table name as well (for instance in a multitable query), like this-
Range Types
Range types represent data types that uses a range of data. Range type can be discrete
ranges (e.g., all integer values 1 to 10) or continuous ranges (e.g., any point in time
between 10:00am and 11:00am).
42
PostgreSQL
Custom range types can be created to make new types of ranges available, such as IP
address ranges using the inet type as a base, or float ranges using the float data type as
a base.
Range types support inclusive and exclusive range boundaries using the [ ] and ( )
characters, respectively. For example, '[4,9]' represents all the integers starting from and
including 4 up to but not including 9.
Pseudo Types
The PostgreSQL type system contains a number of special-purpose entries that are
collectively called pseudo-types. A pseudo-type cannot be used as a column data type,
but it can be used to declare a function's argument or result type.
43
PostgreSQL
Name Description
any Indicates that a function accepts any input data type.
44
5. PostgreSQL CREATE Database PostgreSQL
This chapter discusses about how to create a new database in your PostgreSQL.
PostgreSQL provides two ways of creating a new database:
Syntax
The basic syntax of CREATE DATABASE statement is as follows-
Example
Following is a simple example, which will create testdb in your PostgreSQL schema-
Syntax
The syntax for createdb is as shown below-
45
PostgreSQL
Parameters
The table given below lists the parameters with their descriptions-
Parameter Description
dbname The name of a database to create.
Options
The following table lists the command line arguments createdb accepts-
Option Description
-D tablespace Specifies the default tablespace for the database.
-e Echo the commands that createdb generates and sends to the server.
-T template Specifies the template database from which to build this database.
--help Show help about dropdb command line arguments, and exit.
-h host Specifies the host name of the machine on which the server is running.
Specifies the TCP port or the local Unix domain socket file extension on
-p port
which the server is listening for connections.
Open the command prompt and go to the directory where PostgreSQL is installed. Go to
the bin directory and execute the following command to create a database.
46
PostgreSQL
The above given command will prompt you for password of the PostgreSQL admin user,
which is postgres, by default. Hence, provide a password and proceed to create your new
database.
Once a database is created using either of the above-mentioned methods, you can check
it in the list of databases using \l, i.e., backslash el command as follows-
postgres-# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+---------+-------+-----------------------
postgres | postgres | UTF8 | C | C |
template0 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
testdb | postgres | UTF8 | C | C |
(4 rows)
postgres-#
47
6. PostgreSQL SELECT Database PostgreSQL
This chapter explains various methods of accessing the database. Assume that we have
already created a database in our previous chapter. You can select the database using
either of the following methods-
postgres=#
You can check the available database list using \l, i.e., backslash el command as follows-
postgres-# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+---------+-------+-----------------------
postgres | postgres | UTF8 | C | C |
template0 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
testdb | postgres | UTF8 | C | C |
(4 rows)
postgres-#
Now, type the following command to connect/select a desired database; here, we will
connect to the testdb database.
postgres=# \c testdb;
psql (9.2.4)
Type "help" for help.
You are now connected to database "testdb" as user "postgres".
testdb=#
48
PostgreSQL
OS Command Prompt
You can select your database from the command prompt itself at the time when you login
to your database. Following is a simple example-
You are now logged into PostgreSQL testdb and ready to execute your commands inside
testdb. To exit from the database, you can use the command \q.
49
7. PostgreSQL DROP Database PostgreSQL
In this chapter, we will discuss how to delete the database in PostgreSQL. There are two
options to delete a database-
Be careful before using this operation because deleting an existing database would result
in loss of complete information stored in the database.
Syntax
The syntax for DROP DATABASE is given below-
Parameters
The table lists the parameters with their descriptions.
Parameter Description
Do not throw an error if the database does not exist. A notice is issued in
IF EXISTS
this case.
We cannot drop a database that has any open connections, including our own connection
from psql or pgAdmin III. We must switch to another database or template1 if we want to
delete the database we are currently connected to. Thus, it might be more convenient to
use the program dropdb instead, which is a wrapper around this command.
Example
Following is a simple example, which will delete testdb from your PostgreSQL schema-
50
PostgreSQL
Syntax
The syntax for createdb is as shown below-
Parameters
The following table lists the parameters with their descriptions-
Parameter Description
dbname The name of a database to be deleted.
Options
The following table lists the command-line arguments dropdb accepts-
Option Description
-e Shows the commands being sent to the server.
Specifies the TCP port or the local UNIX domain socket file
-p port
extension on which the server is listening for connections.
51
PostgreSQL
Example
The following example demonstrates deleting a database from OS command prompt-
The above command drops the database testdb. Here, I have used the postgres (found
under the pg_roles of template1) username to drop the database.
52
8. PostgreSQL CREATE Table PostgreSQL
The PostgreSQL CREATE TABLE statement is used to create a new table in any of the given
database.
Syntax
Basic syntax of CREATE TABLE statement is as follows-
CREATE TABLE is a keyword, telling the database system to create a new table. The unique
name or identifier for the table follows the CREATE TABLE statement. Initially, the empty
table in the current database is owned by the user issuing the command.
Then, in brackets, comes the list, defining each column in the table and what sort of data
type it is. The syntax will become clear with an example given below.
Examples
Following is an example, which creates a COMPANY table with ID as primary key and NOT
NULL are the constraints showing that these fields cannot be NULL while creating records
in this table-
53
PostgreSQL
Let us create one more table, which we will use in our exercises in subsequent chapters.
You can verify if your table has been created successfully using \d command, which will
be used to list down all the tables in an attached database.
testdb-# \d
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | company | table | postgres
public | department | table | postgres
(2 rows)
testdb-# \d company
Table "public.company"
Column | Type | Modifiers
-----------+---------------+-----------
id | integer | not null
name | text | not null
age | integer | not null
address | character(50) |
salary | real |
join_date | date |
Indexes:
"company_pkey" PRIMARY KEY, btree (id)
54
9. PostgreSQL DROP Table PostgreSQL
The PostgreSQL DROP TABLE statement is used to remove a table definition and all
associated data, indexes, rules, triggers, and constraints for that table.
You have to be careful while using this command because once a table is deleted then all
the information available in the table would also be lost forever.
Syntax
Basic syntax of DROP TABLE statement is as follows-
Example
We had created the tables DEPARTMENT and COMPANY in the previous chapter. First,
verify these tables (use \d to list the tables):
testdb-# \d
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | company | table | postgres
public | department | table | postgres
(2 rows)
This means DEPARTMENT and COMPANY tables are present. So let us drop them as follows-
DROP TABLE
testdb=# \d
relations found.
testdb=#
The message returned DROP TABLE indicates that drop command is executed successfully.
55
10. PostgreSQL Schema PostgreSQL
A schema is a named collection of tables. A schema can also contain views, indexes,
sequences, data types, operators, and functions. Schemas are analogous to directories at
the operating system level, except that schemas cannot be nested. PostgreSQL statement
CREATE SCHEMA creates a schema.
Syntax
The basic syntax of CREATE SCHEMA is as follows-
Example
Let us see an example for creating a schema. Connect to the database testdb and create
a schema myschema as follows-
The message "CREATE SCHEMA" signifies that the schema is created successfully.
56
PostgreSQL
This will create an empty table. You can verify the table created with the command given
below-
It organizes database objects into logical groups to make them more manageable.
Third-party applications can be put into separate schemas so they do not collide
with the names of other objects.
57
11. PostgreSQL INSERT Query PostgreSQL
The PostgreSQL INSERT INTO statement allows one to insert new rows into a table. One
can insert a single row at a time or several rows as a result of a query.
Syntax
Basic syntax of INSERT INTO statement is as follows-
Here, column1, column2,...columnN are the names of the columns in the table into
which you want to insert data.
The target column names can be listed in any order. The values supplied by the
VALUES clause or query are associated with the explicit or implicit column list left-
to-right.
You may not need to specify the column(s) name in the SQL query if you are adding values
for all the columns of the table. However, make sure the order of the values is in the same
order as the columns in the table. The SQL INSERT INTO syntax would be as follows-
Output
The following table summarizes the output messages and their meaning-
Output
Description
Message
Message returned if only one row was inserted. oid is the numeric
INSERT oid 1 OID of the inserted row.
Examples
Let us create COMPANY table in testdb as follows-
58
PostgreSQL
ADDRESS CHAR(50),
SALARY REAL,
JOIN_DATE DATE
);
Following example is to insert a row; here salary column is omitted and therefore it will
have the default value-
Following example uses the DEFAULT clause for the ADDRESS columns rather than
specifying a value-
Following example inserts multiple rows using the multirow VALUES syntax-
All the above statements would create the following records in COMPANY table. The next
chapter will teach you how to display all these records from a table.
59
12. PostgreSQL SELECT Query PostgreSQL
PostgreSQL SELECT statement is used to fetch the data from a database table, which
returns data in the form of result table. These result tables are called result-sets.
Syntax
The basic syntax of SELECT statement is as follows-
Here, column1, column2...are the fields of a table, whose values you want to fetch. If you
want to fetch all the fields available in the field then you can use the following syntax-
Example
Consider the table COMPANY having records as follows-
Following is an example, which would fetch ID, Name and Salary fields of the customers
available in CUSTOMERS table-
id | name | salary
----+-------+--------
1 | Paul | 20000
2 | Allen | 15000
60
PostgreSQL
3 | Teddy | 20000
4 | Mark | 65000
5 | David | 85000
6 | Kim | 45000
7 | James | 10000
(7 rows)
If you want to fetch all the fields of CUSTOMERS table, then use the following query-
61
13. PostgreSQL Operators PostgreSQL
Arithmetic operators
Comparison operators
Logical operators
Bitwise operators
Example
Here are simple examples showing usage of PostgreSQL Arithmetic Operators:
62
PostgreSQL
testdb=# select 5 !;
?column?
----------
120
(1 row)
63
PostgreSQL
Example
Consider the table COMPANY having records as follows-
Here are simple examples showing the usage of PostgresSQL Comparison Operators.
Here, we have used the WHERE clause, which will be explained in a separate chapter, but
for now, you can understand that the WHERE clause is used to put a conditional statement
along with the SELECT statement.
The following SELECT statement lists down all the records having SALARY greater than
50,000.00-
The above given PostgreSQL statement will produce the following result-
Following SELECT statement lists down all the records having SALARY equal to 20,000.00-
64
PostgreSQL
Following SELECT statement lists down all the records having SALARY not equal to
20,000.00-
Following SELECT statement lists down all the records having SALARY not equal to
20,000.00-
Following SELECT statement lists down all the records having SALARY greater than or
equal to 65,000.00-
The above given PostgreSQL statement will produce the following result-
65
PostgreSQL
Checks if the value of left operand is greater than (a > b) is not true.
> the value of right operand, if yes then condition
becomes true.
Checks if the value of left operand is less than the (a < b) is true.
< value of right operand, if yes then condition
becomes true.
Checks if the value of left operand is greater than (a >= b) is not true.
>= or equal to the value of right operand, if yes then
condition becomes true.
Operator Description
The AND operator allows the existence of multiple conditions in a
AND
PostgresSQL statement's WHERE clause.
The NOT operator reverses the meaning of the logical operator with which
NOT it is used. Eg. NOT EXISTS, NOT BETWEEN, NOT IN etc. This is negate
operator.
66
PostgreSQL
Example
Consider the table COMPANY having records as follows-
Here are simple examples showing the usage of PostgreSQL LOGICAL Operators. The
following SELECT statement lists down all the records where AGE is greater than or equal
to 25 and salary is greater than or equal to 65000.00.
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 6500;
The above given PostgreSQL statement will produce the following result-
The following SELECT statement lists down all the records where AGE is greater than or
equal to 25 OR salary is greater than or equal to 65000.00-
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 6500;
67
PostgreSQL
The above given PostgreSQL statement will produce the following result-
Following SELECT statement lists down all the records where AGE is not NULL, which
means all the records because none of the record is having AGE equal to NULL-
The above given PostgreSQL statement will produce the following result-
68
PostgreSQL
p q p&q p|q
0 0 0 0
0 1 0 1
1 1 1 1
1 0 0 1
Assume A = 60; and B = 13; now in binary format they will be as follows-
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
Example
Here are simple examples showing the usage of PostgreSQL Bitwise Operators.
69
PostgreSQL
The Bitwise operators supported by PostgreSQL are listed in the following table-
Binary Ones Complement Operator (~A ) will give -61 which is 1100
~ is unary and has the effect of 0011 in 2's complement form due to
'flipping' bits. a signed binary number.
70
14. PostgreSQL Expressions PostgreSQL
PostgreSQL EXPRESSIONS are like formulas and they are written in query language. You
can also use to query the database for specific set of data.
Syntax
Consider the basic syntax of the SELECT statement as follows-
There are different types of PostgreSQL expressions, which are mentioned below.
71
PostgreSQL
The above given PostgreSQL statement will produce the following result-
The above given PostgreSQL statement will produce the following result-
addition
----------
21
(1 row)
There are several built-in functions like avg(), sum(), count() to perform what is known
as aggregate data calculations against a table or a specific table column.
The above given PostgreSQL statement will produce the following result-
RECORDS
---------
7
(1 row)
72
PostgreSQL
now
-------------------------------
2013-05-06 14:38:28.078+05:30
(1 row)
73
15. PostgreSQL WHERE Clause PostgreSQL
The PostgreSQL WHERE clause is used to specify a condition while fetching the data from
single table or joining with multiple tables.
If the given condition is satisfied, only then it returns specific value from the table. You
can filter out rows that you do not want included in the result-set by using the WHERE
clause.
The WHERE clause not only is used in SELECT statement, but it is also used in UPDATE,
DELETE statement, etc., which we would examine in subsequent chapters.
Syntax
The basic syntax of SELECT statement with WHERE clause is as follows-
You can specify a search_condition using comparison or logical operators.like >, <, =,
LIKE, NOT, etc. The following examples would make this concept clear.
Example
Consider the table COMPANY having records as follows-
74
PostgreSQL
Here are simple examples showing usage of PostgreSQL Logical Operators. Following
SELECT statement will list down all the records where AGE is greater than or equal to
25 AND salary is greater than or equal to 65000.00-
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
The above given PostgreSQL statement will produce the following result-
Following SELECT statement lists down all the records where AGE is greater than or equal
to 25 OR salary is greater than or equal to 65000.00-
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
The above given PostgreSQL statement will produce the following result-
Following SELECT statement lists down all the records where AGE is not NULL, which
means all the records, because none of the record has AGE equal to NULL-
The above given PostgreSQL statement will produce the following result-
75
PostgreSQL
Following SELECT statement lists down all the records where NAME starts with 'Pa', does
not matter what comes after 'Pa'.
The above given PostgreSQL statement will produce the following result-
Following SELECT statement lists down all the records where AGE value is either 25 or 27-
The above given PostgreSQL statement will produce the following result-
Following SELECT statement lists down all the records where AGE value is neither 25 nor
27-
The above given PostgreSQL statement will produce the following result-
76
PostgreSQL
Following SELECT statement lists down all the records where AGE value is in BETWEEN 25
AND 27-
Following SELECT statement makes use of SQL subquery where subquery finds all the
records with AGE field having SALARY > 65000 and later WHERE clause is being used
along with EXISTS operator to list down all the records where AGE from the outside query
exists in the result returned by sub-query:
The above given PostgreSQL statement will produce the following result-
age
-----
32
25
23
25
27
22
24
(7 rows)
Following SELECT statement makes use of SQL subquery where subquery finds all the
records with AGE field having SALARY > 65000 and later WHERE clause is being used
along with > operator to list down all the records where AGE from outside query is greater
than the age in the result returned by sub-query-
77
PostgreSQL
The above given PostgreSQL statement will produce the following result-
78
16. PostgreSQL AND & OR Conjunctive Operators PostgreSQL
The PostgreSQL AND and OR operators are used to combine multiple conditions to narrow
down selected data in a PostgreSQL statement. These two operators are called conjunctive
operators.
These operators provide a means to make multiple comparisons with different operators
in the same PostgreSQL statement.
Syntax
The basic syntax of AND operator with WHERE clause is as follows-
You can combine N number of conditions using AND operator. For an action to be taken
by the PostgreSQL statement, whether it be a transaction or query, all conditions
separated by the AND must be TRUE.
Example
Consider the table COMPANY, having records as follows-
79
PostgreSQL
Following SELECT statement lists down all the records where AGE is greater than or equal
to 25 AND salary is greater than or equal to 65000.00-
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
The above given PostgreSQL statement will produce the following result-
The OR Operator
The OR operator is also used to combine multiple conditions in a PostgreSQL statement's
WHERE clause. While using OR operator, complete condition will be assumed true when at
least any of the conditions is true. For example [condition1] OR [condition2] will be true if
either condition1 or condition2 is true.
Syntax
The basic syntax of OR operator with WHERE clause is as follows-
You can combine N number of conditions using OR operator. For an action to be taken by
the PostgreSQL statement, whether it be a transaction or query, only any ONE of the
conditions separated by the OR must be TRUE.
Example
Consider the COMPANY table, having the following records-
80
PostgreSQL
Following SELECT statement lists down all the records where AGE is greater than or equal
to 25 OR salary is greater than or equal to 65000.00-
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
The above given PostgreSQL statement will produce the following result-
81
17. PostgreSQL UPDATE Query PostgreSQL
The PostgreSQL UPDATE Query is used to modify the existing records in a table. You can
use WHERE clause with UPDATE query to update the selected rows. Otherwise, all the rows
would be updated.
Syntax
The basic syntax of UPDATE query with WHERE clause is as follows-
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example
Consider the table COMPANY, having records as follows-
82
PostgreSQL
If you want to modify all ADDRESS and SALARY column values in COMPANY table, you do
not need to use WHERE clause and UPDATE query would be as follows-
83
18. PostgreSQL DELETE Query PostgreSQL
The PostgreSQL DELETE Query is used to delete the existing records from a table. You
can use WHERE clause with DELETE query to delete the selected rows. Otherwise, all the
records would be deleted.
Syntax
The basic syntax of DELETE query with WHERE clause is as follows-
Example
Consider the table COMPANY, having records as follows-
84
PostgreSQL
If you want to DELETE all the records from COMPANY table, you do not need to use WHERE
clause with DELETE queries, which would be as follows-
Now, COMPANY table does not have any record because all the records have been deleted
by the DELETE statement.
85
19. PostgreSQL LIKE Clause PostgreSQL
The PostgreSQL LIKE operator is used to match text values against a pattern using
wildcards. If the search expression can be matched to the pattern expression, the LIKE
operator will return true, which is 1.
There are two wildcards used in conjunction with the LIKE operator-
The percent sign represents zero, one, or multiple numbers or characters. The underscore
represents a single number or character. These symbols can be used in combinations.
If either of these two signs is not used in conjunction with the LIKE clause, then the LIKE
acts like the equals operator.
Syntax
The basic syntax of % and _ is as follows-
or
or
or
or
You can combine N number of conditions using AND or OR operators. Here XXXX could be
any numeric or string value.
86
PostgreSQL
Example
Here are number of examples showing WHERE part having different LIKE clause with '%'
and '_' operators-
Statement Description
WHERE SALARY::text LIKE '200%' Finds any values that start with 200
WHERE SALARY::text LIKE '%200%' Finds any values that have 200 in any position
WHERE SALARY::text LIKE '%2' Finds any values that end with 2
Postgres LIKE is String compare only. Hence, we need to explicitly cast the integer column
to string as in the examples above.
Let us take a real example, consider the table COMPANY having records as follows-
87
PostgreSQL
Following is an example, which would display all the records from COMPANY table where
AGE starts with 2:
Following is an example, which would display all the records from COMPANY table where
ADDRESS will have a hyphen (-) inside the text-
88
20. PostgreSQL LIMIT Clause PostgreSQL
The PostgreSQL LIMIT clause is used to limit the data amount returned by the SELECT
statement.
Syntax
The basic syntax of SELECT statement with LIMIT clause is as follows-
Following is the syntax of LIMIT clause when it is used along with OFFSET clause-
LIMIT and OFFSET allow you to retrieve just a portion of the rows that are generated by
the rest of the query.
Example
Consider the table COMPANY having records as follows-
Following is an example, which limits the row in the table according to the number of rows
you want to fetch from table-
89
PostgreSQL
However, in certain situation, you may need to pick up a set of records from a particular
offset. Here is an example, which picks up three records starting from the third position-
90
21. PostgreSQL ORDER BY Clause PostgreSQL
The PostgreSQL ORDER BY clause is used to sort the data in ascending or descending
order, based on one or more columns.
Syntax-
The basic syntax of ORDER BY clause is as follows-
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column
you are using to sort, that column should be available in column-list.
Example
Consider the table COMPANY having records as follows-
Following is an example, which would sort the result in descending order by SALARY-
91
PostgreSQL
Following is an example, which would sort the result in descending order by NAME and
SALARY-
Following is an example, which would sort the result in descending order by NAME-
92
PostgreSQL
93
22. PostgreSQL GROUP BY PostgreSQL
The PostgreSQL GROUP BY clause is used in collaboration with the SELECT statement to
group together those rows in a table that have identical data. This is done to eliminate
redundancy in the output and/or compute aggregates that apply to these groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.
Syntax
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow
the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2....columnN
ORDER BY column1, column2....columnN
You can use more than one column in the GROUP BY clause. Make sure whatever column
you are using to group, that column should be available in column-list.
Example
Consider the table COMPANY having records as follows-
94
PostgreSQL
If you want to know the total amount of salary of each customer, then GROUP BY query
would be as follows-
name | sum
-------+-------
Teddy | 20000
Paul | 20000
Mark | 65000
David | 85000
Allen | 15000
Kim | 45000
James | 10000
(7 rows)
Now, let us create three more records in COMPANY table using the following INSERT
statements-
Now, our table has the following records with duplicate names-
95
PostgreSQL
Again, let us use the same statement to group-by all the records using NAME column as
follows-
testdb=# SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME ORDER BY NAME;
name | sum
-------+-------
Allen | 15000
David | 85000
James | 20000
Kim | 45000
Mark | 65000
Paul | 40000
Teddy | 20000
(7 rows)
name | sum
-------+-------
Teddy | 20000
Paul | 40000
Mark | 65000
Kim | 45000
James | 20000
David | 85000
Allen | 15000
(7 rows)
96
23. PostgreSQL WITH Clause PostgreSQL
In PostgreSQL, the WITH query provides a way to write auxiliary statements for use in a
larger query. It helps in breaking down complicated and large queries into simpler forms,
which are easily readable. These statements often referred to as Common Table
Expressions or CTEs, can be thought of as defining temporary tables that exist just for one
query.
The WITH query being CTE query, is particularly useful when subquery is executed multiple
times. It is equally helpful in place of temporary tables. It computes the aggregation once
and allows us to reference it by its name (may be multiple times) in the queries.
Syntax
The basic syntax of WITH query is as follows-
WITH
name_for_summary_data AS (
SELECT Statement)
SELECT columns
FROM name_for_summary_data
WHERE conditions <=> (
SELECT column
FROM name_for_summary_data)
[ORDER BY columns]
You can use data-modifying statements (INSERT, UPDATE or DELETE) in WITH. This allows
you to perform several different operations in the same query.
Recursive WITH
Recursive WITH or Hierarchical queries, is a form of CTE where a CTE can reference to
itself, i.e., a WITH query can refer to its own output, hence the name recursive.
97
PostgreSQL
Example
Consider the table COMPANY having records as follows-
Now, let us write a query using the WITH clause to select the records from the above table,
as follows-
With CTE AS
(Select
ID
, NAME
, AGE
, ADDRESS
, SALARY
FROM COMPANY )
Select * From CTE;
The above given PostgreSQL statement will produce the following result-
98
PostgreSQL
Now, let us write a query using the RECURSIVE keyword along with the WITH clause, to
find the sum of the salaries less than 20000, as follows-
The above given PostgreSQL statement will produce the following result-
sum
-------
25000
(1 row)
Let us write a query using data modifying statements along with the WITH clause, as
shown below.
First, create a table COMPANY1 similar to the table COMPANY. The query in the example
effectively moves rows from COMPANY to COMPANY1. The DELETE in WITH deletes the
specified rows from COMPANY, returning their contents by means of its RETURNING
clause; and then the primary query reads that output and inserts it into COMPANY1 TABLE.
WITH moved_rows AS (
DELETE FROM COMPANY
WHERE
SALARY >= 30000
RETURNING *
)
INSERT INTO COMPANY1 (SELECT * FROM moved_rows);
The above given PostgreSQL statement will produce the following result-
INSERT 0 3
99
PostgreSQL
Now, the records in the tables COMPANY and COMPANY1 are as follows-
100
24. PostgreSQL HAVING Clause PostgreSQL
The HAVING clause allows us to pick out particular rows where the function's result meets
some condition.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause
places conditions on groups created by the GROUP BY clause.
Syntax
The following is the position of the HAVING clause in a SELECT query-
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
The HAVING clause must follow the GROUP BY clause in a query and must also precede
the ORDER BY clause if used. The following is the syntax of the SELECT statement,
including the HAVING clause-
Example
Consider the table COMPANY having records as follows-
101
PostgreSQL
Following is an example, which would display record for which the name count is less than
2-
testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) < 2;
name
-------
Teddy
Paul
Mark
David
Allen
Kim
James
(7 rows)
Now, let us create three more records in COMPANY table using the following INSERT
statements-
Now, our table has the following records with duplicate names-
102
PostgreSQL
Following is the example, which would display record for which the name count is greater
than 1-
testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) > 1;
name
-------
Paul
James
(2 rows)
103
25. PostgreSQL DISTINCT Keyword PostgreSQL
There may be a situation when you have multiple duplicate records in a table. While
fetching such records, it makes more sense to fetch only unique records instead of fetching
duplicate records.
Syntax
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows-
Example
Consider the table COMPANY having records as follows-
104
PostgreSQL
First, let us see how the following SELECT query returns duplicate salary records-
name
-------
Paul
Allen
Teddy
Mark
David
Kim
James
Paul
Allen
(9 rows)
Now, let us use DISTINCT keyword with the above SELECT query and see the result-
105
PostgreSQL
This would produce the following result where we do not have any duplicate entry-
name
-------
Teddy
Paul
Mark
David
Allen
Kim
James
(7 rows)
106
PostgreSQL
Advanced PostgreSQL
107
26. PostgreSQL CONSTRAINTS PostgreSQL
Constraints are the rules enforced on data columns on table. These are used to prevent
invalid data from being entered into the database. This ensures the accuracy and reliability
of the data in the database.
Constraints could be column level or table level. Column level constraints are applied only
to one column whereas table level constraints are applied to the whole table. Defining a
data type for a column is a constraint in itself. For example, a column of type DATE
constrains the column to valid dates.
NOT NULL Constraint: Ensures that a column cannot have NULL value.
CHECK Constraint: The CHECK constraint ensures that all values in a column
satisfy certain conditions.
EXCLUSION Constraint: The EXCLUDE constraint ensures that if any two rows
are compared on the specified column(s) or expression(s) using the specified
operator(s), not all of these comparisons will return TRUE.
Example
For example, the following PostgreSQL statement creates a new table called COMPANY1
and adds five columns, three of which, ID and NAME and AGE, specify not to accept NULL
values-
108
PostgreSQL
SALARY REAL
);
UNIQUE Constraint
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the COMPANY table, for example, you might want to prevent two or more
people from having identical age.
Example
For example, the following PostgreSQL statement creates a new table called COMPANY3
and adds five columns. Here, AGE column is set to UNIQUE, so that you cannot have two
records with same age-
We use them to refer to table rows. Primary keys become foreign keys in other tables,
when creating relations among tables. Due to a 'longstanding coding oversight', primary
keys can be NULL in SQLite. This is not the case with other databases.
A primary key is a field in a table, which uniquely identifies each row/record in a database
table. Primary keys must contain unique values. A primary key column cannot have NULL
values.
A table can have only one primary key, which may consist of single or multiple fields.
When multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records
having the same value of that field(s).
109
PostgreSQL
Example
You already have seen various examples above where we have created COMAPNY4 table
with ID as primary key.
Example
For example, the following PostgreSQL statement creates a new table called COMPANY5
and adds five columns.
For example, the following PostgreSQL statement creates a new table called
DEPARTMENT1, which adds three columns. The column EMP_ID is the foreign key and
references the ID field of the table COMPANY6.
110
PostgreSQL
CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into a record.
If the condition evaluates to false, the record violates the constraint and is not entered
into the table.
Example
For example, the following PostgreSQL statement creates a new table called COMPANY5
and adds five columns. Here, we add a CHECK with SALARY column, so that you cannot
have any SALARY as Zero.
EXCLUSION Constraint
Exclusion constraints ensure that if any two rows are compared on the specified columns
or expressions using the specified operators, at least one of these operator comparisons
will return false or null.
Example
For example, the following PostgreSQL statement creates a new table called COMPANY7
and adds five columns. Here, we add an EXCLUDE constraint.
111
PostgreSQL
Here, USING gist is the type of index to build and use for enforcement.
You need to execute the command CREATE EXTENSION btree_gist, once per database.
This will install the btree_gist extension, which defines the exclusion constraints on plain
scalar data types.
As we have enforced the age has to be same, let us see this by inserting records to the
table-
For the first two INSERT statements, the records are added to the COMPANY7 table. For
the third INSERT statement, the following error is displayed-
Dropping Constraints
To remove a constraint you need to know its name. If the name is known, it is easy to
drop. Else, you need to find out the system-generated name. The psql command \d table
name can be helpful here. The general syntax is-
112
27. PostgreSQL JOINS PostgreSQL
The PostgreSQL Joins clause is used to combine records from two or more tables in a
database. A JOIN is a means for combining fields from two tables by using values common
to each.
Before we proceed, let us consider two tables, COMPANY and DEPARTMENT. We already
have seen INSERT statements to populate COMPANY table. So just let us assume the list
of records available in COMPANY table.
113
PostgreSQL
id | dept | emp_id
----+-------------+--------
1 | IT Billing | 1
2 | Engineering | 2
3 | Finance | 7
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT;
114
PostgreSQL
1 | Paul | IT Billing
1 | James | IT Billing
1 | James | IT Billing
2 | Paul | Engineering
2 | Teddy | Engineering
2 | Mark | Engineering
2 | David | Engineering
2 | Allen | Engineering
2 | Paul | Engineering
2 | James | Engineering
2 | James | Engineering
7 | Paul | Finance
7 | Teddy | Finance
7 | Mark | Finance
7 | David | Finance
7 | Allen | Finance
7 | Paul | Finance
7 | James | Finance
7 | James | Finance
An INNER JOIN is the most common type of join and is the default type of join. You can
use INNER keyword optionally.
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
115
PostgreSQL
In case of LEFT OUTER JOIN, an inner join is performed first. Then, for each row in table
T1 that does not satisfy the join condition with any row in table T2, a joined row is added
with null values in columns of T2. Thus, the joined table always has at least one row for
each row in T1.
SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ...
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
116
PostgreSQL
SELECT ... FROM table1 RIGHT OUTER JOIN table2 ON conditional_expression ...
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY RIGHT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
SELECT ... FROM table1 FULL OUTER JOIN table2 ON conditional_expression ...
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY FULL OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
117
PostgreSQL
118
28. PostgreSQL UNIONS Clause PostgreSQL
The PostgreSQL UNION clause/operator is used to combine the results of two or more
SELECT statements without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same
number of column expressions, the same data type, and have them in the same order but
they do not have to be the same length.
Syntax
The basic syntax of UNION is as follows-
UNION
Here, given condition could be any given expression based on your requirement.
Example
Consider the following two tables, (a) COMPANY table is as follows-
119
PostgreSQL
Now let us join these two tables using SELECT statement along with UNION clause as
follows-
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
120
PostgreSQL
Syntax:
The basic syntax of UNION ALL is as follows-
UNION ALL
Here, given condition could be any given expression based on your requirement.
Example
Now, let us join above-mentioned two tables in our SELECT statement as follows-
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION ALL
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
121
PostgreSQL
7 | James | Finance
3 | Teddy | Engineering
4 | Mark | Finance
5 | David | Engineering
6 | Kim | Finance
(14 rows)
122
29. PostgreSQL NULL Values PostgreSQL
The PostgreSQL NULL is the term used to represent a missing value. A NULL value in a
table is a value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that
a NULL value is different from a zero value or a field that contains spaces.
Syntax
The basic syntax of using NULL while creating a table is as follows-
Here, NOT NULL signifies that column should always accept an explicit value of the given
data type. There are two columns where we did not use NOT NULL. Hence, this means
these columns could be NULL.
A field with a NULL value is one that has been left blank during record creation.
Example
The NULL value can cause problems when selecting data because when comparing an
unknown value to any other value, the result is always unknown and not included in the
final results. Consider the following table, COMPANY having the following records-
123
PostgreSQL
Let us use the UPDATE statement to set few nullable values as NULL as follows-
testdb=# UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);
Next, let us see the usage of IS NOT NULL operator to list down all the records where
SALARY is not NULL-
The above given PostgreSQL statement will produce the following result-
Following is the usage of IS NULL operator, which will list down all the records where
SALARY is NULL-
124
PostgreSQL
The above given PostgreSQL statement will produce the following result-
125
30. PostgreSQL ALIAS Syntax PostgreSQL
You can rename a table or a column temporarily by giving another name, which is known
as ALIAS. The use of table aliases means to rename a table in a particular PostgreSQL
statement. Renaming is a temporary change and the actual table name does not change
in the database.
The column aliases are used to rename a table's columns for the purpose of a particular
PostgreSQL query.
Syntax
The basic syntax of table alias is as follows-
Example
Consider the following two tables, (a) COMPANY table is as follows-
126
PostgreSQL
id | dept | emp_id
----+--------------+--------
1 | IT Billing | 1
2 | Engineering | 2
3 | Finance | 7
4 | Engineering | 3
5 | Finance | 4
6 | Engineering | 5
7 | Finance | 6
(7 rows)
Now, following is the usage of TABLE ALIAS where we use C and D as aliases for
COMPANY and DEPARTMENT tables, respectively-
The above given PostgreSQL statement will produce the following result-
Let us see an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias
of ID column and COMPANY_NAME is an alias of name column.
127
PostgreSQL
The above given PostgreSQL statement will produce the following result-
128
31. PostgreSQL TRIGGERS PostgreSQL
o After the operation has completed (after constraints are checked and the
INSERT, UPDATE, or DELETE has completed)
A trigger that is marked FOR EACH ROW is called once for every row that the
operation modifies. In contrast, a trigger that is marked FOR EACH STATEMENT
only executes once for any given operation, regardless of how many rows it
modifies.
Both, the WHEN clause and the trigger actions, may access elements of the row
being inserted, deleted or updated using references of the form NEW.column-
name and OLD.column-name, where column-name is the name of a column
from the table that the trigger is associated with.
If multiple triggers of the same kind are defined for the same event, they will be
fired in alphabetical order by name.
The BEFORE, AFTER or INSTEAD OF keyword determines when the trigger actions
will be executed relative to the insertion, modification or removal of the associated
row.
Triggers are automatically dropped when the table that they are associated with is
dropped.
The table to be modified must exist in the same database as the table or view to
which the trigger is attached and one must use just tablename,
not database.tablename.
129
PostgreSQL
A CONSTRAINT option when specified creates a constraint trigger. This is the same
as a regular trigger except that the timing of the trigger firing can be adjusted
using SET CONSTRAINTS. Constraint triggers are expected to raise an exception
when the constraints they implement are violated.
Syntax
The basic syntax of creating a trigger is as follows-
Example
Let us consider a case where we want to keep audit trial for every record being inserted
in COMPANY table, which we will create newly as follows (Drop COMPANY table if you
already have it).
130
PostgreSQL
To keep audit trial, we will create a new table called AUDIT where log messages will be
inserted whenever there is an entry in COMPANY table for a new record:
Here, ID is the AUDIT record ID, and EMP_ID is the ID, which will come from COMPANY
table, and DATE will keep timestamp when the record will be created in COMPANY table.
So now, let us create a trigger on COMPANY table as follows-
Now, we will start the actual work. Let us start inserting record in COMPANY table, which
should result in creating an audit log record in AUDIT table. So let us create one record in
COMPANY table as follows-
Same time, one record will be created in AUDIT table. This record is the result of a trigger,
which we have created on INSERT operation on COMPANY table. Similarly, you can create
your triggers on UPDATE and DELETE operations based on your requirements.
emp_id | entry_date
--------+-------------------------------
1 | 2013-05-05 15:49:59.968+05:30
(1 row)
131
PostgreSQL
Listing TRIGGERS
You can list down all the triggers in the current database from pg_trigger table as follows-
The above given PostgreSQL statement will list down all triggers.
If you want to list the triggers on a particular table, then use AND clause with table name
as follows-
The above given PostgreSQL statement will also list down only one entry as follows-
tgname
-----------------
example_trigger
(1 row)
Dropping TRIGGERS
Following is the DROP command, which can be used to drop an existing trigger-
132
32. PostgreSQL INDEXES PostgreSQL
Indexes are special lookup tables that the database search engine can use to speed up
data retrieval. Simply put, an index is a pointer to data in a table. An index in a database
is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic,
you have to first refer to the index, which lists all topics alphabetically and then refer to
one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses; however, it slows down
data input, with UPDATE and INSERT statements. Indexes can be created or dropped with
no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the
index, to specify the table and which column or columns to index, and to indicate whether
the index is in ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there's an index.
Index Types
PostgreSQL provides several index types: B-tree, Hash, GiST, SP-GiST and GIN. Each
Index type uses a different algorithm that is best suited to different types of queries. By
default, the CREATE INDEX command creates B-tree indexes, which fit the most common
situations.
Single-Column Indexes
A single-column index is one that is created based on only one table column. The basic
syntax is as follows-
133
PostgreSQL
Multicolumn Indexes
A multicolumn index is defined on more than one column of a table. The basic syntax is
as follows-
Should there be only one column used, a single-column index should be the choice. Should
there be two or more columns that are frequently used in the WHERE clause as filters, the
multicolumn index would be the best choice.
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique
index does not allow any duplicate values to be inserted into the table. The basic syntax
is as follows-
Partial Indexes
A partial index is an index built over a subset of a table; the subset is defined by a
conditional expression (called the predicate of the partial index). The index contains entries
only for those table rows that satisfy the predicate. The basic syntax is as follows-
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when
an object is created. Indexes are automatically created for primary key constraints and
unique constraints.
Example
Following is an example where we will create an index on COMPANY table for salary
column-
134
PostgreSQL
Now, let us list down all the indices available on COMPANY table using \d
company command.
# \d company
This will produce the following result, where company_pkey is an implicit index, which got
created when the table was created.
Table "public.company"
Column | Type | Modifiers
---------+---------------+-----------
id | integer | not null
name | text | not null
age | integer | not null
address | character(50) |
salary | real |
Indexes:
"company_pkey" PRIMARY KEY, btree (id)
"salary_index" btree (salary)
You can list down the entire indexes database wide using the \di command.
135
33. PostgreSQL ALTER TABLE Command PostgreSQL
The PostgreSQL ALTER TABLE command is used to add, delete or modify columns in an
existing table.
You would also use ALTER TABLE command to add and drop various constraints on an
existing table.
Syntax-
The basic syntax of ALTER TABLE to add a new column in an existing table is as follows-
The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows-
The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as
follows-
The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is
as follows-
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows-
The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows-
The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as
follows-
136
PostgreSQL
The basic syntax of ALTER TABLE to DROP CONSTRAINT from a table is as follows-
The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as
follows-
Example
Consider our COMPANY table has the following records-
Now, COMPANY table is changed and the following would be the output from SELECT
statement-
137
PostgreSQL
Now, COMPANY table is changed and following would be output from SELECT statement-
138
34. PostgreSQL TRUNCATE TABLE Command PostgreSQL
The PostgreSQL TRUNCATE TABLE command is used to delete complete data from an
existing table. You can also use DROP TABLE command to delete complete table but it
would remove complete table structure from the database and you would need to re-create
this table once again if you wish to store some data.
It has the same effect as DELETE on each table, but since it does not actually scan the
tables, it is faster. Furthermore, it reclaims disk space immediately, rather than requiring
a subsequent VACUUM operation. This is most useful on large tables.
Syntax
The basic syntax of TRUNCATE TABLE is as follows-
Example
Consider the COMPANY table has the following records-
Now, COMPANY table is truncated and the following would be the output of SELECT
statement-
139
35. PostgreSQL VIEWS PostgreSQL
Views are pseudo-tables. That is, they are not real tables; nevertheless appear as ordinary
tables to SELECT. A view can represent a subset of a real table, selecting certain columns
or certain rows from an ordinary table. A view can even represent joined tables. Because
views are assigned separate permissions, you can use them to restrict table access so that
the users see only specific rows or columns of a table.
A view can contain all rows of a table or selected rows from one or more tables. A view
can be created from one or many tables, which depends on the written PostgreSQL query
to create a view.
Views, which are kind of virtual tables, allow users to do the following-
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data such that a user can only see limited data instead of
complete table.
Summarize data from various tables, which can be used to generate reports.
Since views are not ordinary tables, you may not be able to execute a DELETE, INSERT,
or UPDATE statement on a view. However, you can create a RULE to correct this problem
of using DELETE, INSERT or UPDATE on a view.
Creating Views
The PostgreSQL views are created using the CREATE VIEW statement. The PostgreSQL
views can be created from a single table, multiple tables, or another view.
You can include multiple tables in your SELECT statement in very similar way as you use
them in normal PostgreSQL SELECT query. If the optional TEMP or TEMPORARY keyword
is present, the view will be created in the temporary space. Temporary views are
automatically dropped at the end of the current session.
140
PostgreSQL
Example
Consider, the COMPANY table is having the following records-
Now, following is an example to create a view from COMPANY table. This view would be
used to have only few columns from COMPANY table.
Now, you can query COMPANY_VIEW in a similar way as you query an actual table.
Following is the example-
id | name | age
----+-------+-----
1 | Paul | 32
2 | Allen | 25
3 | Teddy | 23
4 | Mark | 25
5 | David | 27
6 | Kim | 22
7 | James | 24
(7 rows)
141
PostgreSQL
Dropping Views
To drop a view, simply use the DROP VIEW statement with the view_name. The basic
DROP VIEW syntax is as follows-
Following command will delete COMPANY_VIEW view, which we created in the last section-
142
36. PostgreSQL TRANSACTIONS PostgreSQL
A transaction is a unit of work that is performed against a database. Transactions are units
or sequences of work accomplished in a logical order, whether in a manual fashion by a
user or automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if
you are creating a record, updating a record, or deleting a record from the table, then you
are performing transaction on the table. It is important to control transactions to ensure
data integrity and to handle database errors.
Practically, you will club many PostgreSQL queries into a group and you will execute all of
them together as a part of a transaction.
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID-
Atomicity: Ensures that all operations within the work unit are completed
successfully; otherwise, the transaction is aborted at the point of failure and
previous operations are rolled back to their former state.
Transaction Control
The following commands are used to control transactions-
Transactional control commands are only used with the DML commands INSERT, UPDATE
and DELETE only. They cannot be used while creating tables or dropping them because
these operations are automatically committed in the database.
143
PostgreSQL
BEGIN;
or
BEGIN TRANSACTION;
The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.
COMMIT;
or
END TRANSACTION;
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
ROLLBACK;
Example
Consider the COMPANY table, having the following records-
144
PostgreSQL
Now, let us start a transaction and delete records from the table having age = 25 and
finally we use ROLLBACK command to undo all the changes.
testdb=# BEGIN;
DELETE FROM COMPANY WHERE AGE = 25;
ROLLBACK;
If you will check COMPANY table is still having the following records-
Now, let us start another transaction and delete records from the table having age = 25
and finally we use COMMIT command to commit all the changes.
testdb=# BEGIN;
DELETE FROM COMPANY WHERE AGE = 25;
COMMIT;
If you will check the COMPANY table, it still has the following records-
145
37. PostgreSQL LOCKS PostgreSQL
Locks or Exclusive Locks or Write Locks prevent users from modifying a row or an entire
table. Rows modified by UPDATE and DELETE are then exclusively locked automatically for
the duration of the transaction. This prevents other users from changing the row until the
transaction is either committed or rolled back.
The only time when users must wait for other users is when they are trying to modify the
same row. If they modify different rows, no waiting is necessary. SELECT queries never
have to wait.
The database performs locking automatically. In certain cases, however, locking must be
controlled manually. Manual locking can be done by using the LOCK command. It allows
specification of a transaction's lock type and scope.
LOCK [ TABLE ]
name
IN
lock_mode
lock_mode: The lock mode specifies which locks this lock conflicts with. If no lock
mode is specified, then ACCESS EXCLUSIVE, the most restrictive mode, is used.
Possible values are: ACCESS SHARE, ROW SHARE , ROW EXCLUSIVE, SHARE
UPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESS
EXCLUSIVE.
Once obtained, the lock is held for the remainder of the current transaction. There is no
UNLOCK TABLE command; locks are always released at the transaction end.
DeadLocks
Deadlocks can occur when two transactions are waiting for each other to finish their
operations. While PostgreSQL can detect them and end them with a ROLLBACK, deadlocks
can still be inconvenient. To prevent your applications from running into this problem,
make sure to design them in such a way that they will lock objects in the same order.
146
PostgreSQL
Advisory Locks
PostgreSQL provides means for creating locks that have application-defined meanings.
These are called advisory locks. As the system does not enforce their use, it is up to the
application to use them correctly. Advisory locks can be useful for locking strategies that
are an awkward fit for the MVCC model.
For example, a common use of advisory locks is to emulate pessimistic locking strategies
typical of the so-called "flat file" data management systems. While a flag stored in a table
could be used for the same purpose, advisory locks are faster, avoid table bloat, and are
automatically cleaned up by the server at the end of the session.
Example
Consider the table COMPANY having records as follows-
The following example locks the COMPANY table within the testdb database in ACCESS
EXCLUSIVE mode. The LOCK statement works only in a transaction mode.
testdb=#BEGIN;
LOCK TABLE company1 IN ACCESS EXCLUSIVE MODE;
The above given PostgreSQL statement will produce the following result-
LOCK TABLE
The above message indicates that the table is locked until the transaction ends and to
finish the transaction you will have to either rollback or commit the transaction.
147
38. PostgreSQL Sub Queries PostgreSQL
A subquery or Inner query or Nested query is a query within another PostgreSQL query
and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE statements along
with the operators like =, <, >, >=, <=, IN, etc.
A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the ORDER
BY in a subquery.
Subqueries that return more than one row can only be used with multiple value
operators, such as the IN, EXISTS, NOT IN, ANY/SOME, ALL operator.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN
can be used within the subquery.
148
PostgreSQL
Example
Consider the COMPANY table having the following records-
testdb=# SELECT *
FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY
WHERE SALARY > 45000) ;
149
PostgreSQL
Example
Consider a table COMPANY_BKP, with similar structure as COMPANY table and can be
created using the same CREATE TABLE using COMPANY_BKP as the table name. Now, to
copy complete COMPANY table into COMPANY_BKP, following is the syntax-
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have COMPANY_BKP table available, which is backup of the COMPANY table.
The following example updates SALARY by 0.50 times in the COMPANY table for all the
customers, whose AGE is greater than or equal to 27-
150
PostgreSQL
This would affect two rows and finally the COMPANY table would have the following
records-
Example
Assuming, we have COMPANY_BKP table available, which is a backup of the COMPANY
table.
The following example deletes records from the COMPANY table for all the customers,
whose AGE is greater than or equal to 27-
151
PostgreSQL
This would affect two rows and finally the COMPANY table would have the following
records-
152
39. PostgreSQL AUTO INCREMENT PostgreSQL
PostgreSQL has the data types smallserial, serial and bigserial; these are not true types,
but merely a notational convenience for creating unique identifier columns. These are
similar to AUTO_INCREMENT property supported by some other databases.
If you wish a serial column to have a unique constraint or be a primary key, it must now
be specified, just like any other data type.
The type name serial creates an integer columns. The type name bigserial creates a bigint
column. Bigserial should be used if you anticipate the use of more than 231 identifiers
over the lifetime of the table. The type name smallserial creates a smallint column.
Syntax
The basic usage of SERIAL dataype is as follows-
Example
Consider the COMPANY table to be created as follows-
153
PostgreSQL
This will insert seven tuples into the table COMPANY and COMPANY will have the following
records-
154
40. PostgreSQL PRIVILEGES PostgreSQL
SELECT,
INSERT,
UPDATE,
DELETE,
TRUNCATE,
REFERENCES,
TRIGGER,
CREATE,
CONNECT,
TEMPORARY,
EXECUTE, and
USAGE
Depending on the type of the object (table, function, etc.,), privileges are applied to the
object. To assign privileges to the users, the GRANT command is used.
privilege values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL.
object: The name of an object to which to grant access. The possible objects are:
table, view, sequence
155
PostgreSQL
privilege values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL.
object: The name of an object to which to grant access. The possible objects are:
table, view, sequence
Example
To understand the privileges, let us first create a USER as follows-
The message CREATE ROLE indicates that the USER "manisha" is created.
156
PostgreSQL
Next, let us grant all privileges on a table COMPANY to the user "manisha" as follows-
The message GRANT indicates that all privileges are assigned to the USER.
Next, let us revoke the privileges from the USER "manisha" as follows-
The message REVOKE indicates that all privileges are revoked from the USER.
The message DROP ROLE indicates USER Manisha is deleted from the database.
157
41. PostgreSQL DATE/TIME Functions and PostgreSQL
Operators
We had discussed about the Date/Time data types in the chapter Data Types. Now, let us
see the Date/Time operators and Functions.
The following table lists the behaviors of the basic arithmetic operators-
timestamp '2001-09-28
+ date '2001-09-28' + interval '1 hour'
01:00:00'
timestamp '2001-09-28
+ date '2001-09-28' + time '03:00'
03:00:00'
+ interval '1 day' + interval '1 hour' interval '1 day 01:00:00'
timestamp '2001-09-27
- date '2001-09-28' - interval '1 hour'
23:00:00'
- interval '1 day' - interval '1 hour' interval '1 day -01:00:00'
158
PostgreSQL
Following is the list of all important Date and Time related functions available-
Function Description
ISFINITE() Test for finite date, time and interval (not +/-infinity)
The above given PostgreSQL statement will produce the following result-
age
-------------------------
43 years 9 mons 27 days
159
PostgreSQL
The above given PostgreSQL statement will produce the following result-
age
--------------------------
55 years 10 mons 22 days
CURRENT DATE/TIME()
PostgreSQL provides a number of functions that return values related to the current date
and time. Following are some functions-
Function Description
160
PostgreSQL
date
------------
2013-05-05
(1 row)
PostgreSQL also provides functions that return the start time of the current statement, as
well as the actual current time at the instant the function is called. These functions are-
Function Description
161
PostgreSQL
162
PostgreSQL
The following are valid field names (similar to DATE_PART function field names):century,
day, decade, dow, doy, epoch, hour, isodow, isoyear, microseconds, millennium,
milliseconds, minute, month, quarter, second, timezone, timezone_hour,
timezone_minute, week, year.
Function Description
163
PostgreSQL
JUSTIFY_DAYS(interval), JUSTIFY_HOURS(interval),
JUSTIFY_INTERVAL(interval)
Function Description
164
PostgreSQL
165
42. PostgreSQL Functions PostgreSQL
PostgreSQL functions, also known as Stored Procedures, allow you to carry out
operations that would normally take several queries and round trips in a single function
within the database. Functions allow database reuse as other applications can interact
directly with your stored procedures instead of a middle-tier or duplicating code.
Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc.
Syntax
The basic syntax to create a function is as follows-
Where,
RETURN clause specifies that data type you are going to return from the function.
The return_datatype can be a base, composite, or domain type, or can reference
the type of a table column.
plpgsql is the name of the language that the function is implemented in. Here, we
use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-
defined procedural language. For backward compatibility, the name can be
enclosed by single quotes.
166
PostgreSQL
Example
The following example illustrates creating and calling a standalone function. This function
returns the total number of records in the COMPANY table. We will use the COMPANY table,
which has the following records-
Now, let us execute a call to this function and check the records in the COMPANY table.
totalrecords
--------------
7
(1 row)
167
43. PostgreSQL Useful Functions PostgreSQL
PostgreSQL built-in functions, also called as Aggregate functions, are used for performing
processing on string or numeric data.
PostgreSQL AVG Function - The PostgreSQL AVG aggregate function selects the
average value for certain table column.
168
PostgreSQL
(7 rows)
Now, based on the above table, suppose you want to count the total number of rows in
this table, then you can do it as follows-
The above given PostgreSQL statement will produce the following result-
count
-------
7
(1 row)
Similarly, you want to count the number of records for Paul then it can be done as follows-
To understand MAX function, consider the table COMPANY having records as follows-
Now, based on the above table, suppose you want to fetch maximum value of SALARY,
then you can do so by simply using the following command-
169
PostgreSQL
The above given PostgreSQL statement will produce the following result-
max
-------
85000
(1 row)
You can find all the records with maximum value for each name using the GROUP
BY clause as follows-
testdb=# SELECT id, name, MAX(salary) FROM COMPANY GROUP BY id, name;
The above given PostgreSQL statement will produce the following result-
id | name | max
----+-------+-------
4 | Mark | 65000
7 | James | 10000
6 | Kim | 45000
3 | Teddy | 20000
2 | Allen | 15000
5 | David | 85000
1 | Paul | 20000
You can use the MIN Function along with the MAX function to find out minimum value as
well. Try out the following example-
The above given PostgreSQL statement will produce the following result-
min | max
-------+-------
10000 | 85000
(1 row)
170
PostgreSQL
To understand the MIN function, consider the table COMPANY having records as follows-
Now, based on the above table, suppose you want to fetch the minimum value of salary,
then you can do so by simply using the following command-
The above given PostgreSQL statement will produce the following result-
min
-------
10000
(1 row)
You can find all the records with the minimum value for each name using the GROUP
BY clause as follows-
testdb=# SELECT id, name, MIN(salary) FROM company GROUP BY id, name;
The above given PostgreSQL statement will produce the following result-
id | name | min
----+-------+-------
4 | Mark | 65000
7 | James | 10000
6 | Kim | 45000
3 | Teddy | 20000
171
PostgreSQL
2 | Allen | 15000
5 | David | 85000
1 | Paul | 20000
(7 rows)
You can use the MIN Function along with the MAX function to find out the minimum value
as well. Try out the following example-
The above given PostgreSQL statement will produce the following result-
min | max
-------+-------
10000 | 85000
(1 row)
To understand the AVG function, consider the table COMPANY having records as follows-
Now, based on the above table, suppose you want to calculate the average of all the
SALARY, then you can do so by using the following command-
172
PostgreSQL
The above given PostgreSQL statement will produce the following result-
avg
------------------
37142.8571428571
(1 row)
You can take athe verage of various records set using the GROUP BY clause. The following
example will take the average of all the records related to a single person and you will
have the average salary of each person.
To understand the SUM function, consider the table COMPANY having records as follows-
173
PostgreSQL
Now, based on the above table, suppose you want to calculate the total of all the salary,
then you can do so by using the following command-
The above given PostgreSQL statement will produce the following result-
sum
--------
260000
(1 row)
You can take the sum of various records set using the GROUP BY clause. The following
example will sum up all the records related to a single person and you will have salary for
each person.
The above given PostgreSQL statement will produce the following result-
name | sum
-------+-------
Teddy | 20000
Paul | 20000
Mark | 65000
David | 85000
Allen | 15000
Kim | 45000
James | 10000
(7 rows)
To understand the ARRAY_AGG function, consider the table COMPANY having records as
follows-
174
PostgreSQL
Now, based on the above table, suppose you want to use the ARRAY_AGG, you can do so
by using the following command-
The above given PostgreSQL statement will produce the following result-
array_agg
---------------------------------------------
{20000,15000,20000,65000,85000,45000,10000}
Name Description
175
PostgreSQL
ABS(X)
The ABS() function returns the absolute value of X. Consider the following example-
176
PostgreSQL
ACOS(X)
This function returns the arccosine of X. The value of X must range between -1 and 1 or
NULL will be returned. Consider the following example-
ASIN(X)
The ASIN() function returns the arcsine of X. The value of X must be in the range of -1 to
1 or NULL is returned.
ATAN(X)
177
PostgreSQL
ATAN2(Y,X)
This function returns the arctangent of the two arguments: X and Y. It is similar to the
arctangent of Y/X, except that the signs of both are used to find the quadrant of the result.
CEIL(X) / CEILING(X)
These functions return the smallest integer value that is not smaller than X. Consider the
following example-
178
PostgreSQL
+---------------------------------------------------------+
1 row in set (0.00 sec)
COS(X)
This function returns the cosine of X. The value of X is given in radians.
testdb=#SELECT COS(90);
+---------------------------------------------------------+
| COS(90) |
+---------------------------------------------------------+
| -0.44807361612917 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
COT(X)
This function returns the cotangent of X. Consider the following example-
testdb=#SELECT COT(1);
+---------------------------------------------------------+
| COT(1) |
+---------------------------------------------------------+
| 0.64209261593433 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
DEGREES(X)
This function returns the value of X converted from radians to degrees.
testdb=#SELECT DEGREES(PI());
+---------------------------------------------------------+
| DEGREES(PI()) |
+---------------------------------------------------------+
| 180.000000 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
EXP(X)
179
PostgreSQL
This function returns the value of e (the base of the natural logarithm) raised to the power
of X.
testdb=#SELECT EXP(3);
+---------------------------------------------------------+
| EXP(3) |
+---------------------------------------------------------+
| 20.085537 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
FLOOR(X)
This function returns the largest integer value that is not greater than X.
testdb=#SELECT FLOOR(7.55);
+---------------------------------------------------------+
| FLOOR(7.55) |
+---------------------------------------------------------+
| 7 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
GREATEST(n1,n2,n3,..........)
The GREATEST() function returns the greatest value in the set of input parameters (n1,
n2, n3, and so on). The following example uses the GREATEST() function to return the
largest number from a set of numeric values-
testdb=#SELECT GREATEST(3,5,1,8,33,99,34,55,67,43);
+---------------------------------------------------------+
| GREATEST(3,5,1,8,33,99,34,55,67,43) |
+---------------------------------------------------------+
| 99 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
LEAST(N1,N2,N3,N4,......)
180
PostgreSQL
The LEAST() function is the opposite of the GREATEST() function. Its purpose is to return
the least-valued item from the value list (N1, N2, N3, and so on). The following example
shows the proper usage and output for the LEAST() function-
testdb=#SELECT LEAST(3,5,1,8,33,99,34,55,67,43);
+---------------------------------------------------------+
| LEAST(3,5,1,8,33,99,34,55,67,43) |
+---------------------------------------------------------+
| 1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
LOG(X) / LOG(B,X)
The single argument version of the function will return the natural logarithm of X. If it is
called with two arguments, it returns the logarithm of X for an arbitrary base B. Consider
the following example-
testdb=#SELECT LOG(45);
+---------------------------------------------------------+
| LOG(45) |
+---------------------------------------------------------+
| 1.65321251377534 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
testdb=#SELECT LOG(2,65536);
+---------------------------------------------------------+
| LOG(2,65536) |
+---------------------------------------------------------+
| 16.000000 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
MOD(N,M)
This function returns the remainder of N divided by M. Consider the following example-
181
PostgreSQL
testdb=#SELECT MOD(29,3);
+---------------------------------------------------------+
| MOD(29,3) |
+---------------------------------------------------------+
| 2 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
PI()
This function simply returns the value of pi. SQL internally stores the full double-precision
value of pi.
testdb=#SELECT PI();
+---------------------------------------------------------+
| PI() |
+---------------------------------------------------------+
| 3.141593 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
POW(X,Y) / POWER(X,Y)
These two functions return the value of X raised to the power of Y.
RADIANS(X)
This function returns the value of X, converted from degrees to radians.
182
PostgreSQL
testdb=#SELECT RADIANS(90);
+---------------------------------------------------------+
| RADIANS(90) |
+---------------------------------------------------------+
|1.570796 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
ROUND(X) / ROUND(X,D)
This function returns X rounded to the nearest integer. If a second argument, D, is
supplied, then the function returns X rounded to D decimal places. D must be positive or
all digits to the right of the decimal point will be removed. Consider the following example-
testdb=#SELECT ROUND(5.693893);
+---------------------------------------------------------+
| ROUND(5.693893) |
+---------------------------------------------------------+
| 6 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
testdb=#SELECT ROUND(5.693893,2);
+---------------------------------------------------------+
| ROUND(5.693893,2) |
+---------------------------------------------------------+
| 5.69 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SIGN(X)
This function returns the sign of X (negative, zero, or positive) as -1, 0, or 1.
183
PostgreSQL
testdb=#SELECT SIGN(-4.65);
+---------------------------------------------------------+
| SIGN(-4.65) |
+---------------------------------------------------------+
| -1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
testdb=#SELECT SIGN(0);
+---------------------------------------------------------+
| SIGN(0) |
+---------------------------------------------------------+
| 0 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
testdb=#SELECT SIGN(4.65);
+---------------------------------------------------------+
| SIGN(4.65) |
+---------------------------------------------------------+
| 1 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SIN(X)
This function returns the sine of X. Consider the following example-
testdb=#SELECT SIN(90);
+---------------------------------------------------------+
| SIN(90) |
+---------------------------------------------------------+
| 0.893997 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQRT(X)
This function returns the non-negative square root of X. Consider the following example-
184
PostgreSQL
testdb=#SELECT SQRT(49);
+---------------------------------------------------------+
| SQRT(49) |
+---------------------------------------------------------+
| 7 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TAN(X)
This function returns the tangent of the argument X, which is expressed in radians-
testdb=#SELECT TAN(45);
+---------------------------------------------------------+
| TAN(45) |
+---------------------------------------------------------+
| 1.619775 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
Name Description
185
PostgreSQL
ASCII(str)
Returns the numeric value of the leftmost character of the string str. Returns 0 if str is an
empty string. Returns NULL if str is NULL. ASCII() works for characters with numeric values
from 0 to 255.
186
PostgreSQL
+---------------------------------------------------------+
| 50 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
BIT_LENGTH(str)
Returns the length of the string str in bits.
CHAR_LENGTH(str)
Returns the length of the string str, measured in characters. A multi-byte character counts
as a single character. This means that for a string containing five two-byte characters,
LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
187
PostgreSQL
CHARACTER_LENGTH(str)
CHARACTER_LENGTH() is a synonym for CHAR_LENGTH().
CONCAT(str1,str2,...)
Returns the string that results from concatenating the arguments. It may have one or
more arguments. If all arguments are non-binary strings, the result is a non-binary string.
If the arguments include any binary strings, the result is a binary string. A numeric
argument is converted to its equivalent binary string form; if you want to avoid that, you
can use an explicit type cast, as in this example.
CONCAT_WS(separator,str1,str2,...)
CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT().
The first argument is the separator for the rest of the arguments. The separator is added
between the strings to be concatenated. The separator can be a string, as can the rest of
the arguments. If the separator is NULL, the result is NULL.
188
PostgreSQL
LCASE(str)
LCASE() is a synonym for LOWER().
LEFT(str,len)
Returns the leftmost len characters from the string str, or NULL if any argument is NULL.
LENGTH(str)
Returns the length of the string str, measured in bytes. A multi-byte character counts as
multiple bytes. This means that for a string containing five two-byte characters, LENGTH()
returns 10, whereas CHAR_LENGTH() returns 5.
LOWER(str)
Returns the string str with all characters changed to lowercase according to the current
character set mapping.
189
PostgreSQL
+---------------------------------------------------------+
| LOWER('QUADRATICALLY') |
+---------------------------------------------------------+
| quadratically |
+---------------------------------------------------------+
1 row in set (0.00 sec)
LPAD(str,len,padstr)
Returns the string str, left-padded with the string padstr to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
LTRIM(str)
Returns the string str with leading space characters removed.
MID(str,pos,len)
MID(str,pos,len) is a synonym for SUBSTRING(str,pos,len).
POSITION(substr IN str)
190
PostgreSQL
191
PostgreSQL
(1 row)
REGEXP_SPLIT_TO_ARRAY(string text, pattern text [, flags text ]), Split string using a
POSIX regular expression as the delimiter.
192
PostgreSQL
(2 rows)
REPEAT(str,count)
Returns a string consisting of the string str repeated count times. If count is less than 1,
returns an empty string. Returns NULL if str or count are NULL.
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string
to_str. REPLACE() performs a case-sensitive match when searching for from_str.
REVERSE(str)
Returns the string str with the order of the characters reversed.
RIGHT(str,len)
Returns the rightmost len characters from the string str, or NULL if any argument is NULL.
193
PostgreSQL
rbar
(1 row)
RPAD(str,len,padstr)
Returns the string str, right-padded with the string padstr to a length of len characters. If
str is longer than len, the return value is shortened to len characters.
RTRIM(str)
Returns the string str with trailing space characters removed.
SUBSTRING(str,pos)
SUBSTRING(str,pos,len)
194
PostgreSQL
(1 row)
195
PostgreSQL
UCASE(str)
UCASE() is a synonym for UPPER().
UPPER(str)
Returns the string str with all characters changed to uppercase according to the current
character set mapping.
196
PostgreSQL
PostgreSQL Interfaces
197
44. PostgreSQL C/C++ Interface PostgreSQL
This tutorial is going to use libpqxx library, which is the official C++ client API for
PostgreSQL. The source code for libpqxx is available under the BSD license, so you're free
to download it, pass it on to others, change it, sell it, include it in your own code, and
share your changes with anyone you choose.
Installation
The the latest version of libpqxx is available to be downloaded from the link Download
Libpqxx. So download the latest version and follow the following steps-
wget http://pqxx.org/download/software/libpqxx/libpqxx-4.0.tar.gz
tar xvfz libpqxx-4.0.tar.gz
cd libpqxx-4.0
./configure
make
make install
Before you start using C/C++ PostgreSQL interface, find the pg_hba.conf file in your
PostgreSQL installation directory and add the following line-
You can start/restart postgres server in case it is not running using the following
command-
198
PostgreSQL
C.is_open()
The method is_open() is a public method of connection object and returns
2
boolean value. If connection is active, then this method returns true otherwise
it returns false.
C.disconnect()
3
This method is used to disconnect an opened database connection.
pqxx::work W( C )
This is a typedef which will be used to create a transactional object using
connection C, which ultimately will be used to execute SQL statements in
4 transactional mode.
If transaction object gets created successfully, then it is assigned to variable
W which will be used to access public methods related to transactional object.
W.commit()
6 This public method from transactional object will be used to commit the
transaction.
W.abort()
7 This public method from transactional object will be used to rollback the
transaction.
pqxx::nontransaction N( C )
This is a typedef which will be used to create a non-transactional object using
connection C, which ultimately will be used to execute SQL statements in non-
8 transactional mode.
If transaction object gets created successfully, then it is assigned to variable N
which will be used to access public methods related to non-transactional
object.
199
PostgreSQL
Connecting To Database
The following C code segment shows how to connect to an existing database running on
local machine at port 5432. Here, I used backslash \ for line continuation.
#include <iostream>
#include <pqxx/pqxx>
using namespace std;
using namespace pqxx;
Now, let us compile and run the above program to connect to our database testdb, which
is already available in your schema and can be accessed using user postgres and
password pass123.
You can use the user ID and password based on your database setting. Remember to keep
the -lpqxx and -lpq in the given order! Otherwise, the linker will complain bitterly about
the missing functions with names starting with "PQ."
200
PostgreSQL
Create a Table
The following C code segment will be used to create a table in previously created database-
#include <iostream>
#include <pqxx/pqxx>
try{
connection C("dbname=testdb user=postgres password=cohondob \
hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
} else {
cout << "Can't open database" << endl;
return 1;
}
/* Create SQL statement */
sql = "CREATE TABLE COMPANY(" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL );";
201
PostgreSQL
When the above given program is compiled and executed, it will create COMPANY table in
your testdb database and will display the following statements-
INSERT Operation
The following C code segment shows how we can create records in our COMPANY table
created in above example-
#include <iostream>
#include <pqxx/pqxx>
using namespace std;
using namespace pqxx;
202
PostgreSQL
return 1;
}
/* Create SQL statement */
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";
return 0;
}
When the above given program is compiled and executed, it will create given records in
COMPANY table and will display the following two lines-
203
PostgreSQL
SELECT Operation
The following C code segment shows how we can fetch and display records from our
COMPANY table created in above example-
#include <iostream>
#include <pqxx/pqxx>
try{
connection C("dbname=testdb user=postgres password=cohondob \
hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
} else {
cout << "Can't open database" << endl;
return 1;
}
/* Create SQL statement */
sql = "SELECT * from COMPANY";
204
PostgreSQL
When the above given program is compiled and executed, it will produce the following
result-
205
PostgreSQL
UPDATE Operation
The following C code segment shows how we can use the UPDATE statement to update
any record and then fetch and display updated records from our COMPANY table-
#include <iostream>
#include <pqxx/pqxx>
try{
connection C("dbname=testdb user=postgres password=cohondob \
hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
} else {
cout << "Can't open database" << endl;
return 1;
}
206
PostgreSQL
return 0;
}
When the above given program is compiled and executed, it will produce the following
result-
207
PostgreSQL
Age = 25
Address = Rich-Mond
Salary = 65000
ID = 1
Name = Paul
Age = 32
Address = California
Salary = 25000
Operation done successfully
DELETE Operation
The following C code segment shows how we can use the DELETE statement to delete any
record and then fetch and display remaining records from our COMPANY table-
#include <iostream>
#include <pqxx/pqxx>
try{
connection C("dbname=testdb user=postgres password=cohondob \
hostaddr=127.0.0.1 port=5432");
if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
} else {
cout << "Can't open database" << endl;
return 1;
}
208
PostgreSQL
When the above given program is compiled and executed, it will produce the following
result-
209
PostgreSQL
210
45. PostgreSQL JAVA Interface PostgreSQL
Installation
Before we start using PostgreSQL in our Java programs, we need to make sure that we
have PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial for
Java installation on your machine. Now let us check how to set up PostgreSQL JDBC driver.
The following section assumes you have little knowledge about Java JDBC concepts. If you
do not have, then it is suggested to spent half and hour with JDBC Tutorial to become
comfortable with concepts explained below.
Connecting To Database
The following Java code shows how to connect to an existing database. If the database
does not exist, then it will be created and finally a database object will be returned.
import java.sql.Connection;
import java.sql.DriverManager;
public class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"postgres", "123");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}}
211
PostgreSQL
Before you compile and run above program, find pg_hba.conf file in your PostgreSQL
installation directory and add the following line-
You can start/restart the postgres server, in case it is not running, using the following
command-
Now, let us compile and run the above program to connect with testdb. Here, we are
using postgres as user ID and 123 as password to access the database. You can change
this as per your database configuration and setup. We are also assuming current version
of JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path.
C:\JavaPostgresIntegration>javac PostgreSQLJDBC.java
C:\JavaPostgresIntegration>java -cp c:\tools\postgresql-9.2-
1002.jdbc3.jar;C:\JavaPostgresIntegration PostgreSQLJDBC
Open database successfully
Create a Table
The following Java program will be used to create a table in previously opened database.
Make sure you do not have this table already in your target database.
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
212
PostgreSQL
When a program is compiled and executed, it will create the COMPANY table
in testdb database and will display the following two lines-
INSERT Operation
The following Java program shows how we can create records in our COMPANY table
created in above example-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
213
PostgreSQL
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"manisha", "123");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
+ "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
}
When the above program is compiled and executed, it will create given records in
COMPANY table and will display the following two lines-
214
PostgreSQL
SELECT Operation
The following Java program shows how we can fetch and display records from our
COMPANY table created in above example-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class PostgreSQLJDBC {
public static void main( String args[] )
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"manisha", "123");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
215
PostgreSQL
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
When the program is compiled and executed, it will produce the following result-
ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
216
PostgreSQL
UPDATE Operation
The following Java code shows how we can use the UPDATE statement to update any
record and then fetch and display updated records from our COMPANY table-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class PostgreSQLJDBC {
public static void main( String args[] )
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"manisha", "123");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
stmt.executeUpdate(sql);
c.commit();
217
PostgreSQL
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
When the program is compiled and executed, it will produce the following result-
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
218
PostgreSQL
DELETE Operation
The following Java code shows how we can use the DELETE statement to delete any record
and then fetch and display remaining records from our COMPANY table-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class PostgreSQLJDBC6 {
public static void main( String args[] )
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"manisha", "123");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "DELETE from COMPANY where ID=2;";
stmt.executeUpdate(sql);
c.commit();
219
PostgreSQL
When the program is compiled and executed, it will produce the following result-
220
PostgreSQL
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
Operation done successfully
221
46. PostgreSQL PHP Interface PostgreSQL
Installation
The PostgreSQL extension is enabled by default in the latest releases of PHP 5.3.x. It is
possible to disable it by using --without-pgsql at compile time. Still you can use yum
command to install PHP -PostgreSQL interface-
Before you start using the PHP PostgreSQL interface, find the pg_hba.conf file in your
PostgreSQL installation directory and add the following line-
You can the start/restart postgres server, in case it is not running, using the following
command-
Windows users must enable php_pgsql.dll in order to use this extension. This DLL is
included with Windows distributions in the latest releases of PHP 5.3.x
For detailed installation instructions, kindly check our PHP tutorial and its official website.
222
PostgreSQL
2
This routine resets the connection. It is useful for error recovery. Returns
TRUE on success or FALSE on failure.
3
This routine returns the status of the specified connection. Returns
PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.
4
This routine returns the name of the database that the given PostgreSQL
connection resource.
8
This routine fetches one row of data from the result associated with the
specified result resource.
9
This routine returns an array that contains all rows (records) in the result
resource.
10
This routine returns the number of rows affected by INSERT, UPDATE, and
DELETE queries.
223
PostgreSQL
This routine returns the number of rows in a PostgreSQL result resource for
example number of rows returned by SELECT statement.
12
This routine closes the non-persistent connection to a PostgreSQL database
associated with the given connection resource.
Connecting to Database
The following PHP code shows how to connect to an existing database on a local machine
and finally a database connection object will be returned.
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=testdb";
$credentials = "user=postgres password=pass123";
Now, let us run the above given program to open our database testdb; if the database is
successfully opened, then it will give the following message-
224
PostgreSQL
Create a Table
The following PHP program will be used to create a table in a previously created database-
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=testdb";
$credentials = "user=postgres password=pass123";
When the above given program is executed, it will create COMPANY table in
your testdb and it will display the following messages-
225
PostgreSQL
INSERT Operation
The following PHP program shows how we can create records in our COMPANY table
created in above example-
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=testdb";
$credentials = "user=postgres password=pass123";
226
PostgreSQL
When the above given program is executed, it will create the given records in COMPANY
table and will display the following two lines-
SELECT Operation
The following PHP program shows how we can fetch and display records from our
COMPANY table created in above example-
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=testdb";
$credentials = "user=postgres password=pass123";
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
227
PostgreSQL
pg_close($db);
?>
When the above given program is executed, it will produce the following result. Keep a
note that fields are returned in the sequence they were used while creating table.
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
UPDATE Operation
The following PHP code shows how we can use the UPDATE statement to update any record
and then fetch and display updated records from our COMPANY table-
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=testdb";
$credentials = "user=postgres password=pass123";
228
PostgreSQL
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
When the above given program is executed, it will produce the following result-
229
PostgreSQL
DELETE Operation
The following PHP code shows how we can use the DELETE statement to delete any record
and then fetch and display the remaining records from our COMPANY table-
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=testdb";
$credentials = "user=postgres password=pass123";
230
PostgreSQL
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
When the above given program is executed, it will produce the following result-
231
PostgreSQL
232
47. PostgreSQL Perl Interface PostgreSQL
Installation
The PostgreSQL can be integrated with Perl using Perl DBI module, which is a database
access module for the Perl programming language. It defines a set of methods, variables
and conventions that provide a standard database interface.
Here are simple steps to install DBI module on your Linux/Unix machine-
$ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz
$ tar xvfz DBI-1.625.tar.gz
$ cd DBI-1.625
$ perl Makefile.PL
$ make
$ make install
If you need to install SQLite driver for DBI, then it can be installed as follows-
$ wget http://search.cpan.org/CPAN/authors/id/T/TU/TURNSTEP/DBD-Pg-
2.19.3.tar.gz
$ tar xvfz DBD-Pg-2.19.3.tar.gz
$ cd DBD-Pg-2.19.3
$ perl Makefile.PL
$ make
$ make install
Before you start using Perl PostgreSQL interface, find the pg_hba.conf file in your
PostgreSQL installation directory and add the following line-
You can start/restart the postgres server, in case it is not running, using the following
command-
233
PostgreSQL
$dbh->do($sql)
2 This routine prepares and executes a single SQL statement. Returns the
number of rows affected or undef on error. A return value of -1 means the
number of rows is not known, not applicable, or not available. Here $dbh is a
handle returned by DBI->connect() call.
$dbh->prepare($sql)
3
This routine prepares a statement for later execution by the database engine
and returns a reference to a statement handle object.
$sth->execute()
$sth->fetchrow_array()
5
This routine fetches the next row of data and returns it as a list containing the
field values. Null fields are returned as undef values in the list.
$DBI::err
6 This is equivalent to $h->err, where $h is any of the handle types like $dbh,
$sth, or $drh. This returns native database engine error code from the last
driver method called.
234
PostgreSQL
$DBI::errstr
$dbh->disconnect()
8
This routine closes a database connection previously opened by a call to DBI-
>connect().
Connecting to Database
The following Perl code shows how to connect to an existing database. If the database
does not exist, then it will be created and finally a database object will be returned.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "Pg";
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
Now, let us run the above given program to open our database testdb; if the database is
successfully opened then it will give the following message-
Create a Table
The following Perl program will be used to create a table in previously created database-
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "Pg";
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
235
PostgreSQL
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL););
my $rv = $dbh->do($stmt);
if($rv < 0){
print $DBI::errstr;
} else {
print "Table created successfully\n";
}
$dbh->disconnect();
When the above given program is executed, it will create COMPANY table in
your testdb and it will display the following messages-
INSERT Operation
The following Perl program shows how we can create records in our COMPANY table
created in above example-
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "Pg";
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
236
PostgreSQL
When the above given program is executed, it will create given records in COMPANY table
and will display the following two lines-
SELECT Operation
The following Perl program shows how we can fetch and display records from our COMPANY
table created in above example-
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "Pg";
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
237
PostgreSQL
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
When the above given program is executed, it will produce the following result-
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
238
PostgreSQL
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
UPDATE Operation
The following Perl code shows how we can use the UPDATE statement to update any record
and then fetch and display updated records from our COMPANY table-
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "Pg";
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
239
PostgreSQL
When the above given program is executed, it will produce the following result-
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
DELETE Operation
The following Perl code shows how we can use the DELETE statement to delete any record
and then fetch and display the remaining records from our COMPANY table-
#!/usr/bin/perl
240
PostgreSQL
use DBI;
use strict;
my $driver = "Pg";
my $database = "testdb";
my $dsn = "DBI:$driver:dbname=$database;host=127.0.0.1;port=5432";
my $userid = "postgres";
my $password = "pass123";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
When the above given program is executed, it will produce the following result-
241
PostgreSQL
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
242
48. PostgreSQL Python Interface PostgreSQL
Installation
The PostgreSQL can be integrated with Python using psycopg2 module. sycopg2 is a
PostgreSQL database adapter for the Python programming language. psycopg2 was
written with the aim of being very small and fast, and stable as a rock. You do not need
to install this module separately because it is shipped, by default, along with Python
version 2.5.x onwards.
If you do not have it installed on your machine then you can use yum command to install
it as follows-
To use psycopg2 module, you must first create a Connection object that represents the
database and then optionally you can create cursor object which will help you in executing
all the SQL statements.
psycopg2.connect(database="testdb", user="postgres",
password="cohondob", host="127.0.0.1", port="5432")
1
connection.cursor()
2
This routine creates a cursor which will be used throughout of your database
programming with Python.
243
PostgreSQL
curosr.executemany(sql, seq_of_parameters)
4
This routine executes an SQL command against all parameter sequences or
mappings found in the sequence sql.
curosr.callproc(procname[, parameters])
5 This routine executes a stored database procedure with the given name. The
sequence of parameters must contain one entry for each argument that the
procedure expects.
cursor.rowcount
6
This read-only attribute which returns the total number of database rows that
have been modified, inserted, or deleted by the last last execute*().
connection.commit()
7 This method commits the current transaction. If you don't call this method,
anything you did since the last call to commit() is not visible from other
database connections.
connection.rollback()
8
This method rolls back any changes to the database since the last call to
commit().
connection.close()
9 This method closes the database connection. Note that this does not
automatically call commit(). If you just close your database connection
without calling commit() first, your changes will be lost!
cursor.fetchone()
10
This method fetches the next row of a query result set, returning a single
sequence, or None when no more data is available.
cursor.fetchmany([size=cursor.arraysize])
11 This routine fetches the next set of rows of a query result, returning a list. An
empty list is returned when no more rows are available. The method tries to
fetch as many rows as indicated by the size parameter.
cursor.fetchall()
12
This routine fetches all (remaining) rows of a query result, returning a list. An
empty list is returned when no rows are available.
244
PostgreSQL
Connecting to Database
The following Python code shows how to connect to an existing database. If the database
does not exist, then it will be created and finally a database object will be returned.
#!/usr/bin/python
import psycopg2
conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",
host="127.0.0.1", port="5432")
print "Opened database successfully"
Here, you can also supply database testdb as name and if database is successfully
opened, then it will give the following message-
Create a Table
The following Python program will be used to create a table in previously created database-
#!/usr/bin/python
import psycopg2
conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",
host="127.0.0.1", port="5432")
print "Opened database successfully"
cur = conn.cursor()
cur.execute('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully"
conn.commit()
conn.close()
When above program is executed, it will create COMPANY table in your test.db and it will
display the following messages:
245
PostgreSQL
INSERT Operation
The following Python program shows how we can create records in our COMPANY table
created in the above example-
#!/usr/bin/python
import psycopg2
conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",
host="127.0.0.1", port="5432")
print "Opened database successfully"
cur = conn.cursor()
cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )");
When the above given program is executed, it will create given records in COMPANY table
and will display the following two lines-
246
PostgreSQL
SELECT Operation
The following Python program shows how we can fetch and display records from our
COMPANY table created in the above example-
#!/usr/bin/python
import psycopg2
conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",
host="127.0.0.1", port="5432")
print "Opened database successfully"
cur = conn.cursor()
cur.execute("SELECT id, name, address, salary from COMPANY")
rows = cur.fetchall()
for row in rows:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above given program is executed, it will produce the following result-
247
PostgreSQL
SALARY = 65000.0
Operation done successfully
UPDATE Operation
The following Python code shows how we can use the UPDATE statement to update any
record and then fetch and display updated records from our COMPANY table-
#!/usr/bin/python
import psycopg2
conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",
host="127.0.0.1", port="5432")
print "Opened database successfully"
cur = conn.cursor()
cur.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")
conn.commit
print "Total number of rows updated :", cur.rowcount
cur.execute("SELECT id, name, address, salary from COMPANY")
rows = cur.fetchall()
for row in rows:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
print "Operation done successfully";
conn.close()
When the above given program is executed, it will produce the following result-
ID = 2
NAME = Allen
248
PostgreSQL
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
DELETE Operation
The following Python code shows how we can use the DELETE statement to delete any
record and then fetch and display the remaining records from our COMPANY table-
#!/usr/bin/python
import psycopg2
cur = conn.cursor()
249
PostgreSQL
When the above given program is executed, it will produce the following result-
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully
250