PostgreSQL Database SQL fundamantals
PostgreSQL Database SQL fundamantals
htm
This tutorial will give you a quick start with PostgreSQL and make you
comfortable with PostgreSQL programming.
1986-1994 − POSTGRES
1994-1995 − Postgres95
PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX,
BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. It supports text,
images, sounds, and video, and includes programming interfaces for C / C++,
Java, Perl, Python, Ruby, Tcl and Open Database Connectivity (ODBC).
PostgreSQL supports a large part of the SQL standard and offers many modern
features including the following −
SQL Sub-selects
Foreign keys
Trigger
Views
Transactions
Data types
Functions
Operators
Aggregate functions
Index methods
PostgreSQL supports four standard procedural languages, which allows the users
to write their own code in any of the languages and it can be executed by
PostgreSQL database server. These procedural languages are - PL/pgSQL, PL/Tcl,
PL/Perl and PL/Python. Besides, other non-standard procedural languages like PL/
PHP, PL/V8, PL/Ruby, PL/Java, etc., are also supported.
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.
Follow the given steps to install PostgreSQL on your Linux machine. Make sure
you are logged in as root before you proceed for the installation.
------------------------------------------------------------------------
Please specify the directory where PostgreSQL will be installed.
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 −
Installing
0% ______________ 50% ______________ 100%
#########################################
-----------------------------------------------------------------------
Setup has finished installing PostgreSQL on your computer.
[root@host]# su - postgres
Password:
bash-4.1$ createdb testdb
bash-4.1$ psql testdb
psql (8.4.13, server 9.2.4)
test=#
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.
Follow the given steps to install PostgreSQL on your Windows machine. Make sure
you have turned Third Party Antivirus off while installing.
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.
In the next step, when asked for "Locale", I selected "English, United
States".
After the installation process is completed, you can access pgAdmin III,
StackBuilder and PostgreSQL shell from your Program Menu under PostgreSQL
9.2.
Follow the given steps to install PostgreSQL on your Mac machine. Make sure you
are logged in as administrator before you proceed for the installation.
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.
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 goes fine, then you will be inside postgres
database and a postgress# prompt will be displayed as shown below −
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 −
An SQL statement is comprised of tokens where each token can represent either
a keyword, identifier, quoted identifier, constant, or special character symbol. The
table given below uses a simple SELECT statement to illustrate a basic, but
complete, SQL statement and its components.
ISOLATION LEVEL {
SERIALIZABLE | REPEATABLE READ | READ COMMITTED
| READ UNCOMMITTED
}
READ WRITE | READ ONLY
CHECKPOINT
Close a cursor.
CLOSE name
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'
[ ESCAPE [ AS ] 'escape' ]
[ FORCE NOT NULL column [, ...] ]
COPY table_name [ ( column [, ...] ) ]
TO { 'filename' | STDOUT }
[ [ WITH ]
[ BINARY ]
[ OIDS ]
[ DELIMITER [ AS ] 'delimiter' ]
[ NULL [ AS ] 'null string' ]
[ CSV [ QUOTE [ AS ] 'quote' ]
[ ESCAPE [ AS ] 'escape' ]
[ FORCE QUOTE column [, ...] ]
Where constraint is −
[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | CHECK (expression) }
Where column_constraint is −
[ 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
And table_constraint is −
[ 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
SYSID uid
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
| CREATEDB | NOCREATEDB
| CREATEUSER | NOCREATEUSER
| IN GROUP group_name [, ...]
| VALID UNTIL 'abs_time'
Define a cursor.
Remove a cast.
Remove a conversion.
Remove a database.
Remove a domain.
Remove a function.
Remove an index.
Remove an operator.
Remove a schema.
Remove a sequence.
Remove a table.
Remove a tablespace.
Remove a trigger.
Remove a view.
NEXT
PRIOR
FIRST
LAST
ABSOLUTE count
RELATIVE count
count
ALL
FORWARD
FORWARD count
FORWARD ALL
BACKWARD
BACKWARD count
BACKWARD ALL
LISTEN name
LOAD 'filename'
Lock a table.
Position a cursor.
Generate a notification.
NOTIFY name
Rebuild indexes.
RESET name
RESET ALL
SAVEPOINT savepoint_name
Set the session user identifier and the current user identifier of the current
session.
SHOW name
SHOW ALL
Empty a table.
UNLISTEN { name | * }
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.
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.
small-range
smallint 2 bytes -32768 to +32767
integer
large-range -9223372036854775808 to
bigint 8 bytes
integer 9223372036854775807
variable-
real 4 bytes 6 decimal digits precision
precision,inexact
double variable-
8 bytes 15 decimal digits precision
precision precision,inexact
small
smallserial 2 bytes autoincrementing 1 to 32767
integer
autoincrementing
serial 4 bytes 1 to 2147483647
integer
large
bigserial 8 bytes autoincrementing 1 to 9223372036854775807
integer
The money 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.
currency -92233720368547758.08 to
money 8 bytes
amount +92233720368547758.07
The table given below lists the general-purpose character types available in
PostgreSQL.
character(n), char(n)
2
fixed-length, blank padded
text
3
variable unlimited length
The bytea data type allows storage of binary strings as in the table given below.
bytea 1 or 4 bytes plus the actual binary string variable-length binary string
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.
Storage
Name Description Low Value High Value
Size
both date
timestamp
and time
[(p)] [without 8 bytes 4713 BC 294276 AD
(no time
time zone ]
zone)
both date
and time,
TIMESTAMPTZ 8 bytes 4713 BC 294276 AD
with time
zone
date (no
date 4 bytes 4713 BC 5874897 AD
time of day)
time [ (p)] [
time of day
without time 8 bytes 00:00:00 24:00:00
(no date)
zone ]
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.
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');
PostgreSQL offers data types to store IPv4, IPv6, and MAC addresses. It is better
to use these types instead of plain text types to store network addresses,
because these types offer input error checking and specialized operators and
functions.
Bit String Types are used to store bit masks. They are either 0 or 1. There are
two SQL bit types: bit(n) and bit varying(n), where n is a positive integer.
This type supports full text search, which is the activity of searching through a
collection of natural-language documents to locate those that best match a query.
There are two Data Types for this −
tsvector
1 This is a sorted list of distinct words that have been normalized to
merge different variants of the same word, called as "lexemes".
tsquery
This stores lexemes that are to be searched for, and combines them
2
honoring the Boolean operators & (AND), | (OR), and ! (NOT).
Parentheses can be used to enforce grouping of the operators.
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 −
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.
array_to_json('{{1,5},{99,100}}'::int[]) [[1,5],[99,100]]
row_to_json(row(1,'foo')) {"f1":1,"f2":"foo"}
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
−
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.
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.
This type represents a list of field names and their data types, i.e., structure of a
row or record of a table.
Composite values can be inserted as a literal constant, enclosing the field values
within parentheses and separating them by commas. An example is shown below
−
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.
To access a field of a composite column, use a dot followed by the field name,
much like selecting a field from a table name. For example, to select some
subfields from our on_hand example table, the query would be as shown below −
You can even use the table name as well (for instance in a multitable query), like
this −
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).
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.
Object identifiers (OIDs) are used internally by PostgreSQL as primary keys for
various system tables. If WITH OIDS is specified or default_with_oids
configuration variable is enabled, only then, in such cases OIDs are added to
user-created tables. The following table lists several alias types. The OID alias
types have no operations of their own except for specialized input and output
routines.
numeric object
oid any 564182
identifier
function with
regprocedure pg_proc sum(int4)
argument types
text search
regconfig pg_ts_config English
configuration
text search
regdictionary pg_ts_dict simple
dictionary
any
1
Indicates that a function accepts any input data type.
anyelement
2
Indicates that a function accepts any data type.
anyarray
3
Indicates that a function accepts any array data type.
anynonarray
4
Indicates that a function accepts any non-array data type.
anyenum
5
Indicates that a function accepts any enum data type.
anyrange
6
Indicates that a function accepts any range data type.
cstring
7
Indicates that a function accepts or returns a null-terminated C string.
internal
8 Indicates that a function accepts or returns a server-internal data
type.
language_handler
9 A procedural language call handler is declared to return
language_handler.
fdw_handler
10
A foreign-data wrapper handler is declared to return fdw_handler.
record
11
Identifies a function returning an unspecified row type.
trigger
12
A trigger function is declared to return trigger.
void
13
Indicates that a function returns no value.
This chapter discusses about how to create a new database in your PostgreSQL.
PostgreSQL provides two ways of creating a new database −
This command will create a database from PostgreSQL shell prompt, but you
should have appropriate privilege to create a database. By default, the new
database will be created by cloning the standard system database template1.
The following is a simple example, which will create testdb in your PostgreSQL
schema
The table given below lists the parameters with their descriptions.
dbname
1
The name of a database to create.
description
2
Specifies a comment to be associated with the newly created
database.
options
3
command-line arguments, which createdb accepts.
The following table lists the command line arguments createdb accepts −
-D tablespace
1
Specifies the default tablespace for the database.
-e
2
Echo the commands that createdb generates and sends to the server.
-E encoding
3
Specifies the character encoding scheme to be used in this database.
-l locale
4
Specifies the locale to be used in this database.
-T template
5
Specifies the template database from which to build this database.
--help
6
Show help about createdb command line arguments, and exit.
-h host
7 Specifies the host name of the machine on which the server is
running.
-p port
8 Specifies the TCP port or the local Unix domain socket file extension
on which the server is listening for connections.
-U username
9
User name to connect as.
-w
10
Never issue a password prompt.
-W
11
Force createdb to prompt for a password before connecting to a
database.
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.
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
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-#
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 −
OS Command Prompt
Assume you have already launched your PostgreSQL client and you have landed
at the following SQL prompt −
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-#
postgres=# \c testdb;
psql (9.2.4)
Type "help" for help.
You are now connected to database "testdb" as user "postgres".
testdb=#
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.
In this chapter, we will discuss how to delete the database in PostgreSQL. There
are two options to delete a database −
This command drops a database. It removes the catalog entries for the database
and deletes the directory containing the data. It can only be executed by the
database owner. This command cannot be executed while you or anyone else is
connected to the target database (connect to postgres or any other database to
issue this command).
IF EXISTS
1 Do not throw an error if the database does not exist. A notice is issued
in this case.
name
2
The name of the database to remove.
The following is a simple example, which will delete testdb from your PostgreSQL
schema −
dbname
1
The name of a database to be deleted.
option
2
command-line arguments, which dropdb accepts.
-e
1
Shows the commands being sent to the server.
-i
2
Issues a verification prompt before doing anything destructive.
-V
3
Print the dropdb version and exit.
--if-exists
4 Do not throw an error if the database does not exist. A notice is issued
in this case.
--help
5
Show help about dropdb command-line arguments, and exit.
-h host
6 Specifies the host name of the machine on which the server is
running.
-p port
7 Specifies the TCP port or the local UNIX domain socket file extension
on which the server is listening for connections.
-U username
8
User name to connect as.
-w
9
Never issue a password prompt.
-W
10 Force dropdb to prompt for a password before connecting to a
database.
--maintenance-db=dbname
11 Specifies the name of the database to connect to in order to drop the
target database.
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.
The PostgreSQL CREATE TABLE statement is used to create a new table in any of
the given database.
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
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.
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
The above given PostgreSQL statement will produce the following result −
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | company | table | postgres
public | department | table | postgres
(2 rows)
testdb-# \d company
The above given PostgreSQL statement will produce the following result −
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)
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.
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.
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.
This will create an empty table. You can verify the table created with the
command given below −
To drop a schema if it is empty (all objects in it have been dropped), use the
command −
It allows many users to use one database without interfering with each
other.
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.
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.
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 −
The following table summarizes the output messages and their meaning −
INSERT oid 1
1 Message returned if only one row was inserted. oid is the numeric OID
of the inserted row.
INSERT 0 #
2 Message returned if more than one rows were inserted. # is the
number of rows inserted.
The following example is to insert a row; here salary column is omitted and
therefore it will have the default value −
The following example uses the DEFAULT clause for the JOIN_DATE column rather
than specifying a value −
The 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.
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.
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 −
The 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
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 −
Arithmetic operators
Comparison operators
Logical operators
Bitwise operators
Example
Show Examples
Show Examples
AND
1 The AND operator allows the existence of multiple conditions in a
PostgresSQL statement's WHERE clause.
NOT
The NOT operator reverses the meaning of the logical operator with
2
which it is used. Eg. NOT EXISTS, NOT BETWEEN, NOT IN etc. This is
negate operator.
OR
3 The OR operator is used to combine multiple conditions in a
PostgresSQL statement's WHERE clause.
Bitwise operator works on bits and performs bit-by-bit operation. The truth table
for & and | is as follows −
p q p&q p|q
0 0 0 0
0 1 0 1
1 1 1 1
1 0 0 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
Show Examples
The Bitwise operators supported by PostgreSQL are listed in the following table −
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.
There are different types of PostgreSQL expressions, which are mentioned below
−
PostgreSQL Boolean Expressions fetch the data on the basis of matching single
value. Following is the syntax −
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
The above given PostgreSQL statement will produce the following result −
These expressions are used to perform any mathematical operation in any query.
Following is the syntax −
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)
Date Expressions return the current system date and time values and these
expressions are used in various data manipulations.
The above given PostgreSQL statement will produce the following result −
now
-------------------------------
2013-05-06 14:38:28.078+05:30
(1 row)
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.
You can specify a search_condition using comparison or logical operators. like >,
<, =, LIKE, NOT, etc. The following examples would make this concept clear.
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
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 >= 65000;
The above given PostgreSQL statement will produce the following result −
The 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 −
The 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 −
The 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 −
The 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 −
The following SELECT statement lists down all the records where AGE value is in
BETWEEN 25 AND 27 −
The above given PostgreSQL statement will produce the following result −
The 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)
The 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 −
The above given PostgreSQL statement will produce the following result −
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.
You can combine N number of conditions using AND operator. For an action to be
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 >= 65000;
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 >= 65000;
The above given PostgreSQL statement will produce the following result −
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.
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
The following is an example, which would update ADDRESS for a customer, whose
ID is 6 −
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 −
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.
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.
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.
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.
Here are number of examples showing WHERE part having different LIKE clause
with '%' and '_' operators −
Let us take a real example, consider the table COMPANY, having records as
follows −
The following is an example, which would display all the records from COMPANY
table where AGE starts with 2 −
The following is an example, which would display all the records from COMPANY
table where ADDRESS will have a hyphen (-) inside the text −
The PostgreSQL LIMIT clause is used to limit the data amount returned by the
SELECT statement.
The 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.
The following is an example, which limits the row in the table according to the
number of rows you want to fetch from table −
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 −
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.
The following is an example, which would sort the result in ascending order by
SALARY −
The following is an example, which would sort the result in ascending order by
NAME and SALARY −
The following is an example, which would sort the result in descending order by
NAME −
The GROUP BY clause follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
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.
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 −
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)
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.
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]
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 −
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 −
UNION ALL
SELECT SALARY FROM COMPANY WHERE SALARY < 20000
)
SELECT sum(n) FROM t;
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
Now, the records in the tables COMPANY and COMPANY1 are as follows −
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.
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 −
The 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 −
The 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)
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.
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 −
This would produce the following result where we do not have any duplicate entry
−
name
-------
Teddy
Paul
Mark
David
Allen
Kim
James
(7 rows)
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.
UNIQUE Constraint − Ensures that all values in a column are different.
By default, a column can hold NULL values. If you do not want a column to have
a NULL value, then you need to define such constraint on this column specifying
that NULL is now not allowed for that column. A NOT NULL constraint is always
written as a column constraint.
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 −
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.
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 −
The PRIMARY KEY constraint uniquely identifies each record in a database table.
There can be more UNIQUE columns, but only one primary key in a table.
Primary keys are important when designing the database tables. Primary keys are
unique ids.
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 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).
You already have seen various examples above where we have created
COMAPNY4 table with ID as primary key −
SALARY REAL
);
A foreign key constraint specifies that the values in a column (or a group of
columns) must match the values appearing in some row of another table. We say
this maintains the referential integrity between two related tables. They are
called foreign keys because the constraints are foreign; that is, outside the table.
Foreign keys are sometimes called a referencing key.
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.
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.
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 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.
For example, the following PostgreSQL statement creates a new table called
COMPANY7 and adds five columns. Here, we add an EXCLUDE constraint −
Here, USING gist is the type of index to build and use for enforcement.
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 −
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 −
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.
id | dept | emp_id
----+-------------+--------
1 | IT Billing | 1
2 | Engineering | 2
3 | Finance | 7
A CROSS JOIN matches every row of the first table with every row of the second
table. If the input tables have x and y columns, respectively, the resulting table
will have x+y columns. Because CROSS JOINs have the potential to generate
extremely large tables, care must be taken to use them only when appropriate.
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT;
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
A INNER JOIN creates a new result table by combining column values of two
tables (table1 and table2) based upon the join-predicate. The query compares
each row of table1 with each row of table2 to find all pairs of rows, which satisfy
the join-predicate. When the join-predicate is satisfied, column values for each
matched pair of rows of table1 and table2 are combined into a result row.
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;
2 | Allen | Engineering
The OUTER JOIN is an extension of the INNER JOIN. SQL standard defines three
types of OUTER JOINs: LEFT, RIGHT, and FULL and PostgreSQL supports all of
these.
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;
First, an inner join is performed. Then, for each row in table T2 that does not
satisfy the join condition with any row in table T1, a joined row is added with null
values in columns of T1. This is the converse of a left join; the result table will
always have a row for each row in T2.
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;
First, an inner join is performed. 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. In addition, for each row of T2 that does not satisfy the
join condition with any row in T1, a joined row with null values in the columns of
T1 is added.
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;
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.
UNION
Here, given condition could be any given expression based on your requirement.
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;
The UNION ALL operator is used to combine the results of two SELECT
statements including duplicate rows. The same rules that apply to UNION apply
to the UNION ALL operator as well.
UNION ALL
Here, given condition could be any given expression based on your requirement.
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;
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.
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.
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 −
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 −
The following is the usage of IS NULL operator which will list down all the
records where SALARY is NULL −
The above given PostgreSQL statement will produce the following result −
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.
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 −
7 | James | 24 | Finance
3 | Teddy | 23 | Engineering
4 | Mark | 25 | Finance
5 | David | 27 | Engineering
6 | Kim | 22 | Finance
(7 rows)
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 −
The above given PostgreSQL statement will produce the following result −
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.
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.
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.
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).
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
emp_id | entry_date
--------+-------------------------------
1 | 2013-05-05 15:49:59.968+05:30
(1 row)
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 −
testdb=# SELECT tgname FROM pg_trigger, pg_class WHERE tgrelid=pg_class.oid AND relname
The above given PostgreSQL statement will also list down only one entry as
follows −
tgname
-----------------
example_trigger
(1 row)
The following is the DROP command, which can be used to drop an existing
trigger −
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.
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.
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.
A single-column index is one that is created based on only one table column. The
basic syntax is as follows −
ON table_name (column_name);
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 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 −
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 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.
The following is an example where we will create an index on COMPANY table for
salary column −
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 −
You would also use ALTER TABLE command to add and drop various constraints
on an existing table.
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 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 PRIMARY KEY constraint to a table is
as follows −
The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a
table is as follows −
Now, COMPANY table is changed and the following would be the output from
SELECT statement −
The following is the example to DROP gender column from existing table −
Now, COMPANY table is changed and the following would be the output from
SELECT statement −
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.
Now, COMPANY table is truncated and the following would be the output of
SELECT statement −
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 −
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.
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.
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)
To drop a view, simply use the DROP VIEW statement with the view_name. The
basic DROP VIEW syntax is as follows −
The following command will delete COMPANY_VIEW view, which we created in the
last section −
Practically, you will club many PostgreSQL queries into a group and you will
execute all of them together as a part of a transaction.
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.
Consistency − Ensures that the database properly changes states upon a
successfully committed transaction.
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.
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;
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;
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 −
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.
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 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
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.
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.
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.
Subqueries are most frequently used with the SELECT statement. The basic
syntax is as follows −
testdb=# SELECT *
FROM COMPANY
WHERE ID IN (SELECT ID
FROM COMPANY
WHERE SALARY > 45000) ;
Subqueries also can be used with INSERT statements. The INSERT statement
uses the data returned from the subquery to insert into another table. The
selected data in the subquery can be modified with any of the character, date, or
number functions.
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 −
The subquery can be used in conjunction with the UPDATE statement. Either
single or multiple columns in a table can be updated when using a subquery with
the UPDATE statement.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
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 −
This would affect two rows and finally the COMPANY table would have the
following records −
The subquery can be used in conjunction with the DELETE statement like with
any other statements mentioned above.
The following example deletes records from the COMPANY table for all the
customers, whose AGE is greater than or equal to 27 −
This would affect two rows and finally the COMPANY table would have the
following records −
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.
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.
This will insert seven tuples into the table COMPANY and COMPANY will have the
following records −
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.
The message CREATE ROLE indicates that the USER "manisha" is created.
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.
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'
The following is the list of all important Date and Time related functions available.
AGE()
1
Subtract arguments
CURRENT DATE/TIME()
2
Current date and time
DATE_PART()
3
Get subfield (equivalent to extract)
EXTRACT()
4
Get subfield
ISFINITE()
5
Test for finite date, time and interval (not +/-infinity)
JUSTIFY
6
Adjust interval
AGE(timestamp, timestamp)
When invoked with the TIMESTAMP form of the second argument,
1
AGE() subtract arguments, producing a "symbolic" result that uses
years and months and is of type INTERVAL.
AGE(timestamp)
2 When invoked with only the TIMESTAMP as argument, AGE() subtracts
from the current_date (at midnight).
The above given PostgreSQL statement will produce the following result −
age
-------------------------
43 years 9 mons 27 days
The above given PostgreSQL statement will produce the following result −
age
--------------------------
55 years 10 mons 22 days
CURRENT_DATE
1
Delivers current date.
CURRENT_TIME
2
Delivers values with time zone.
CURRENT_TIMESTAMP
3
Delivers values with time zone.
CURRENT_TIME(precision)
4 Optionally takes a precision parameter, which causes the result to be
rounded to that many fractional digits in the seconds field.
CURRENT_TIMESTAMP(precision)
5 Optionally takes a precision parameter, which causes the result to be
rounded to that many fractional digits in the seconds field.
LOCALTIME
6
Delivers values without time zone.
LOCALTIMESTAMP
7
Delivers values without time zone.
LOCALTIME(precision)
8 Optionally takes a precision parameter, which causes the result to be
rounded to that many fractional digits in the seconds field.
LOCALTIMESTAMP(precision)
9 Optionally takes a precision parameter, which causes the result to be
rounded to that many fractional digits in the seconds field.
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 −
transaction_timestamp()
1 It is equivalent to CURRENT_TIMESTAMP, but is named to clearly
reflect what it returns.
statement_timestamp()
2
It returns the start time of the current statement.
clock_timestamp()
3 It returns the actual current time, and therefore its value changes
even within a single SQL command.
timeofday()
4 It returns the actual current time, but as a formatted text string rather
than a timestamp with time zone value.
now()
5
It is a traditional PostgreSQL equivalent to transaction_timestamp().
DATE_PART('field', source)
These functions get the subfields. The field parameter needs to be a
string value, not a name.
1 The valid field names are: century, day, decade, dow, doy, epoch,
hour, isodow, isoyear, microseconds, millennium, milliseconds, minute,
month, quarter, second, timezone, timezone_hour, timezone_minute,
week, year.
DATE_TRUNC('field', source)
This function is conceptually similar to the trunc function for numbers.
source is a value expression of type timestamp or interval. field
selects to which precision to truncate the input value. The return value
2
is of type timestamp or interval.
The valid values for field are : microseconds, milliseconds, second,
minute, hour, day, week, month, quarter, year, decade, century,
millennium
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.
(1 row)
ISFINITE(date)
1
Tests for finite date.
ISFINITE(timestamp)
2
Tests for finite time stamp.
ISFINITE(interval)
3
Tests for finite interval.
t
(1 row)
JUSTIFY_DAYS(interval)
1 Adjusts interval so 30-day time periods are represented as months.
Return the interval type
JUSTIFY_HOURS(interval)
2 Adjusts interval so 24-hour time periods are represented as days.
Return the interval type
JUSTIFY_INTERVAL(interval)
3 Adjusts interval using JUSTIFY_DAYS and JUSTIFY_HOURS, with
additional sign adjustments. Return the interval type
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.
[...]
BEGIN
< function_body >
[...]
RETURN { variable_name | value }
END; LANGUAGE plpgsql;
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.
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 −
(7 rows)
Now, let us execute a call to this function and check the records in the COMPANY
table
totalrecords
--------------
7
(1 row)
PostgreSQL built-in functions, also called as Aggregate functions, are used for
performing processing on string or numeric data.
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 are 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.
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 −
The following are important interface routines which can sufice your requirement
to work with PostgreSQL database from your C/C++ program. If you are looking
for a more sophisticated application then you can look into the libpqxx official
documentation, or you can use commercially available APIs.
C.is_open()
The method is_open() is a public method of connection object and
2
returns 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 )
4 This is a typedef which will be used to create a 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
8 SQL statements in non-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.
#include <iostream>
#include <pqxx/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."
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;
}
return 0;
}
When the above given program is compiled and executed, it will create COMPANY
table in your testdb database and will display the following statements −
The following C code segment shows how we can create records in 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;
}
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 −
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 {
return 0;
}
When the above given program is compiled and executed, it will produce the
following result −
Name = Allen
Age = 25
Address = Texas
Salary = 15000
ID = 3
Name = Teddy
Age = 23
Address = Norway
Salary = 20000
ID = 4
Name = Mark
Age = 25
Address = Rich-Mond
Salary = 65000
Operation done successfully
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;
}
return 0;
}
When the above given program is compiled and executed, it will produce the
following result −
ID = 2
Name = Allen
Age = 25
Address = Texas
Salary = 15000
ID = 3
Name = Teddy
Age = 23
Address = Norway
Salary = 20000
ID = 4
Name = Mark
Age = 25
Address = Rich-Mond
Salary = 65000
ID = 1
Name = Paul
Age = 32
Address = California
Salary = 25000
Operation done successfully
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;
}
return 0;
}
When the above given program is compiled and executed, it will produce the
following result −
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.
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;
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
Open database successfully
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;
stmt = c.createStatement();
String sql = "CREATE TABLE COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
When a program is compiled and executed, it will create the COMPANY table in
testdb database and will display the following two lines −
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;
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 −
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;
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();
}
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
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;
stmt = c.createStatement();
String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
stmt.executeUpdate(sql);
c.commit();
When the program is compiled and executed, it will produce the following result −
ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0
ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0
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;
stmt = c.createStatement();
String sql = "DELETE from COMPANY where ID = 2;";
stmt.executeUpdate(sql);
c.commit();
}
}
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
Operation done successfully
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 start/restart the 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.
The following are important PHP routines, which can suffice your requirement to
work with PostgreSQL database from your PHP program. If you are looking for a
more sophisticated application, then you can look into the PHP official
documentation.
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 −
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";
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);
EOF;
When the above given program is executed, it will create COMPANY table in your
testdb and it will display the following messages −
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";
if(!$db) {
echo "Error : Unable to open database\n";
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
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 the given records in
COMPANY table and will display the following two lines −
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;
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.
SALARY = 20000
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
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";
if(!$ret) {
echo pg_last_error($db);
exit;
} else {
echo "Record updated successfully\n";
}
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
When the above given program is executed, it will produce the following result −
ID = 3
NAME = Teddy
ADDRESS = 23
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = 25
SALARY = 65000
ID = 1
NAME = Paul
ADDRESS = 32
SALARY = 25000
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";
$sql =<<<EOF
When the above given program is executed, it will produce the following result −
ID = 4
NAME = Mark
ADDRESS = 25
SALARY = 65000
ID = 1
NAME = Paul
ADDRESS = 32
SALARY = 25000
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 −
Following are the important DBI routines, which can suffice your requirement to
work with SQLite database from your Perl program. If you are looking for a more
sophisticated application, then you can look into Perl DBI official documentation.
$dbh→do($sql)
This routine prepares and executes a single SQL statement. Returns
2 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()
This routine performs whatever processing is necessary to execute the
prepared statement. An undef is returned if an error occurs. A
4
successful execute always returns true regardless of the number of
rows affected. Here $sth is a statement handle returned by
$dbh→prepare($sql) call.
$sth→fetchrow_array()
This routine fetches the next row of data and returns it as a list
5
containing the field values. Null fields are returned as undef values in
the list.
$DBI::err
This is equivalent to $h→err, where $h is any of the handle types like
6
$dbh, $sth, or $drh. This returns native database engine error code
from the last driver method called.
$DBI::errstr
This is equivalent to $h→errstr, where $h is any of the handle types
7
like $dbh, $sth, or $drh. This returns the native database engine error
message from the last DBI method called.
$dbh->disconnect()
8 This routine closes a database connection previously opened by a call
to DBI→connect().
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;
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 −
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";
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 create COMPANY table in your
testdb and it will display the following messages −
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";
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 create given records in
COMPANY table and will display the following two lines −
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";
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 −
SALARY = 20000
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
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";
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
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
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 −
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
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.
The following are important psycopg2 module routines, which can suffice your
requirement to work with PostgreSQL database from your Python program. If you
are looking for a more sophisticated application, then you can look into Python
psycopg2 module's official documentation.
psycopg2.connect(database="testdb", user="postgres",
password="cohondob", host="127.0.0.1", port="5432")
1
This API opens a connection to the PostgreSQL database. If database
is opened successfully, it returns a connection object.
connection.cursor()
2 This routine creates a cursor which will be used throughout of your
database programming with Python.
cursor.executemany(sql, seq_of_parameters)
4 This routine executes an SQL command against all parameter
sequences or mappings found in the sequence sql.
cursor.callproc(procname[, parameters])
This routine executes a stored database procedure with the given
5
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()
This method commits the current transaction. If you do not call this
7
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()
This method closes the database connection. Note that this does not
9
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])
This routine fetches the next set of rows of a query result, returning a
11 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.
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
Here, you can also supply database testdb as name and if database is
successfully opened, then it will give the following message −
The following Python program will be used to create a table in previously created
database −
#!/usr/bin/python
import psycopg2
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 the above given program is executed, it will create COMPANY table in your
test.db and it will display the following messages −
The following Python program shows how we can create records in our COMPANY
table created in the above example −
#!/usr/bin/python
import psycopg2
cur = conn.cursor()
conn.commit()
print "Records created successfully";
conn.close()
When the above given program is executed, it will create given records in
COMPANY table and will display the following two lines −
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
cur = conn.cursor()
When the above given program is executed, it will produce the following result −
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
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
cur = conn.cursor()
When the above given program is executed, it will produce the following result −
NAME = Paul
ADDRESS = California
SALARY = 25000.0
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
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()
rows = cur.fetchall()
for row in rows:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"
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