Embed presentation
Downloaded 42 times









![PostgreSQL3To start understanding the PostgreSQL basics, first let us install the PostgreSQL. Thischapter explains about installing the PostgreSQL on Linux, Windows and Mac OS platforms.InstallingPostgreSQLonLinux/UnixFollow the given steps to install PostgreSQL on your Linux machine. Make sure you arelogged in as root before you proceed for the installation. Pick the version number of PostgreSQL you want and, as exactly as possible, theplatform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-linux-x64.run for my 64-bit CentOS-6machine. Now, let us execute it as follows:[root@host]# chmod +x postgresql-9.2.4-1-linux-x64.run[root@host]# ./postgresql-9.2.4-1-linux-x64.run------------------------------------------------------------------------Welcome to the PostgreSQL Setup Wizard.------------------------------------------------------------------------Please specify the directory where PostgreSQL will be installed.Installation Directory [/opt/PostgreSQL/9.2]: Once you launch the installer, it asks you a few basic questions like location of theinstallation, password of the user who will use database, port number, etc. So keepall of them at their default values except password, which you can provide passwordas per your choice. It will install PostgreSQL at your Linux machine and will displaythe following message:Please wait while Setup installs PostgreSQL on your computer.Installing0% ______________ 50% ______________ 100%#########################################-----------------------------------------------------------------------Setup has finished installing PostgreSQL on your computer. Follow the following post-installation steps to create your database:[root@host]# su - postgresPassword:2. PostgreSQL – Environment Setup](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-10-2048.jpg&f=jpg&w=240)
![PostgreSQL4bash-4.1$ createdb testdbbash-4.1$ psql testdbpsql (8.4.13, server 9.2.4)test=# You can start/restart postgres server in case it is not running, using the followingcommand:[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ] If your installation was correct, you will have PotsgreSQL prompt test=# as shownabove.InstallingPostgreSQLonWindowsFollow the given steps to install PostgreSQL on your Windows machine. Make sure youhave turned Third Party Antivirus off while installing. Pick the version number of PostgreSQL you want and, as exactly as possible, theplatform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-windows.exe for my Windows PC running in 32-bit mode, so let us run postgresql-9.2.4-1-windows.exe as administrator toinstall PostgreSQL. Select the location where you want to install it. By default, it isinstalled within Program Files folder.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-11-2048.jpg&f=jpg&w=240)






![PostgreSQL11This chapter provides a list of the PostgreSQL SQL commands, followed by the precisesyntax rules for each of these commands. This set of commands is taken from the psqlcommand-line tool. Now that you have Postgres installed, open the psql as:Program Files > PostgreSQL 9.2 > SQL Shell(psql).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:postgres-# help <command_name>TheSQLStatementAn SQL statement is comprised of tokens where each token can represent either akeyword, identifier, quoted identifier, constant, or special character symbol. The tablegiven below uses a simple SELECT statement to illustrate a basic, but complete, SQLstatement and its components.SELECT id, name FROM statesToken Type Keyword Identifiers Keyword IdentifierDescription Command Id and name columns Clause Table namePostgreSQLSQLcommandsABORTAbort the current transaction.ABORT [ WORK | TRANSACTION ]ALTER AGGREGATEChange the definition of an aggregate function.ALTER AGGREGATE name ( type ) RENAME TO new_nameALTER AGGREGATE name ( type ) OWNER TO new_owner3. PostgreSQL – Syntax](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-18-2048.jpg&f=jpg&w=240)
![PostgreSQL12ALTER CONVERSIONChange the definition of a conversion.ALTER CONVERSION name RENAME TO new_nameALTER CONVERSION name OWNER TO new_ownerALTER DATABASEChange a database specific parameter.ALTER DATABASE name SET parameter { TO | = } { value | DEFAULT }ALTER DATABASE name RESET parameterALTER DATABASE name RENAME TO new_nameALTER DATABASE name OWNER TO new_ownerALTER DOMAINChange the definition of a domain specific parameter.ALTER DOMAIN name { SET DEFAULT expression | DROP DEFAULT }ALTER DOMAIN name { SET | DROP } NOT NULLALTER DOMAIN name ADD domain_constraintALTER DOMAIN name DROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ]ALTER DOMAIN name OWNER TO new_ownerALTER FUNCTIONChange the definition of a function.ALTER FUNCTION name ( [ type [, ...] ] ) RENAME TO new_nameALTER FUNCTION name ( [ type [, ...] ] ) OWNER TO new_ownerALTER GROUPChange a user group.ALTER GROUP groupname ADD USER username [, ... ]ALTER GROUP groupname DROP USER username [, ... ]ALTER GROUP groupname RENAME TO new_name](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-19-2048.jpg&f=jpg&w=240)
![PostgreSQL13ALTER INDEXChange the definition of an index.ALTER INDEX name OWNER TO new_ownerALTER INDEX name SET TABLESPACE indexspace_nameALTER INDEX name RENAME TO new_nameALTER LANGUAGEChange the definition of a procedural language.ALTER LANGUAGE name RENAME TO new_nameALTER OPERATORChange the definition of an operator.ALTER OPERATOR name ( { lefttype | NONE } , { righttype | NONE } )OWNER TO new_ownerALTER OPERATOR CLASSChange the definition of an operator class.ALTER OPERATOR CLASS name USING index_method RENAME TO new_nameALTER OPERATOR CLASS name USING index_method OWNER TO new_ownerALTER SCHEMAChange the definition of a schema.ALTER SCHEMA name RENAME TO new_nameALTER SCHEMA name OWNER TO new_ownerALTER SEQUENCEChange the definition of a sequence generator.ALTER SEQUENCE name [ INCREMENT [ BY ] increment ][ MINVALUE minvalue | NO MINVALUE ][ MAXVALUE maxvalue | NO MAXVALUE ][ RESTART [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-20-2048.jpg&f=jpg&w=240)
![PostgreSQL14ALTER TABLEChange the definition of a table.ALTER TABLE [ ONLY ] name [ * ]action [, ... ]ALTER TABLE [ ONLY ] name [ * ]RENAME [ COLUMN ] column TO new_columnALTER TABLE nameRENAME TO new_nameWhere action is one of the following lines:ADD [ COLUMN ] column_type [ column_constraint [ ... ] ]DROP [ COLUMN ] column [ RESTRICT | CASCADE ]ALTER [ COLUMN ] column TYPE type [ USING expression ]ALTER [ COLUMN ] column SET DEFAULT expressionALTER [ COLUMN ] column DROP DEFAULTALTER [ COLUMN ] column { SET | DROP } NOT NULLALTER [ COLUMN ] column SET STATISTICS integerALTER [ COLUMN ] column SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }ADD table_constraintDROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ]CLUSTER ON index_nameSET WITHOUT CLUSTERSET WITHOUT OIDSOWNER TO new_ownerSET TABLESPACE tablespace_nameALTER TABLESPACEChange the definition of a tablespace.ALTER TABLESPACE name RENAME TO new_nameALTER TABLESPACE name OWNER TO new_ownerALTER TRIGGERChange the definition of a trigger.ALTER TRIGGER name ON table RENAME TO new_name](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-21-2048.jpg&f=jpg&w=240)
![PostgreSQL15ALTER TYPEChange the definition of a type.ALTER TYPE name OWNER TO new_ownerALTER USERChange a database user account.ALTER USER name [ [ WITH ] option [ ... ] ]ALTER USER name RENAME TO new_nameALTER USER name SET parameter { TO | = } { value | DEFAULT }ALTER USER name RESET parameterWhere option can be:[ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'| CREATEDB | NOCREATEDB| CREATEUSER | NOCREATEUSER| VALID UNTIL 'abstime'ANALYZECollect statistics about a database.ANALYZE [ VERBOSE ] [ table [ (column [, ...] ) ] ]BEGINStart a transaction block.BEGIN [ WORK | TRANSACTION ] [ transaction_mode [, ...] ]Where transaction_mode is one of:ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED| READ UNCOMMITTED }READ WRITE | READ ONLYCHECKPOINTForce a transaction log checkpoint.CHECKPOINT](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-22-2048.jpg&f=jpg&w=240)
![PostgreSQL16CLOSEClose a cursor.CLOSE nameCLUSTERCluster a table according to an index.CLUSTER index_name ON table_nameCLUSTER table_nameCLUSTERCOMMENTDefine or change the comment of an object.COMMENT ON{TABLE object_name |COLUMN table_name.column_name |AGGREGATE agg_name (agg_type) |CAST (source_type AS target_type) |CONSTRAINT constraint_name ON table_name |CONVERSION object_name |DATABASE object_name |DOMAIN object_name |FUNCTION func_name (arg1_type, arg2_type, ...) |INDEX object_name |LARGE OBJECT large_object_oid |OPERATOR op (left_operand_type, right_operand_type) |OPERATOR CLASS object_name USING index_method |[ PROCEDURAL ] LANGUAGE object_name |RULE rule_name ON table_name |SCHEMA object_name |SEQUENCE object_name |TRIGGER trigger_name ON table_name |TYPE object_name |VIEW object_name} IS 'text'](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-23-2048.jpg&f=jpg&w=240)
![PostgreSQL17COMMITCommit the current transaction.COMMIT [ WORK | TRANSACTION ]COPYCopy data between a file and a table.COPY table_name [ ( column [, ...] ) ]FROM { 'filename' | STDIN }[ [ WITH ][ BINARY ][ OIDS ][ DELIMITER [ AS ] 'delimiter' ][ NULL [ AS ] 'null string' ][ CSV [ QUOTE [ AS ] 'quote' ][ 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 [, ...] ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-24-2048.jpg&f=jpg&w=240)
![PostgreSQL18CREATE AGGREGATEDefine a new aggregate function.CREATE AGGREGATE name (BASETYPE = input_data_type,SFUNC = sfunc,STYPE = state_data_type[ , FINALFUNC = ffunc ][ , INITCOND = initial_condition ])CREATE CASTDefine a new cast.CREATE CAST (source_type AS target_type)WITH FUNCTION func_name (arg_types)[ AS ASSIGNMENT | AS IMPLICIT ]CREATE CAST (source_type AS target_type)WITHOUT FUNCTION[ AS ASSIGNMENT | AS IMPLICIT ]CREATE CONSTRAINT TRIGGERDefine a new constraint trigger.CREATE CONSTRAINT TRIGGER nameAFTER events ONtable_name constraint attributesFOR EACH ROW EXECUTE PROCEDURE func_name ( args )CREATE CONVERSIONDefine a new conversion.CREATE [DEFAULT] CONVERSION nameFOR source_encoding TO dest_encoding FROM func_nameCREATE DATABASE](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-25-2048.jpg&f=jpg&w=240)
![PostgreSQL19Create a new database.CREATE DATABASE name[ [ WITH ] [ OWNER [=] db_owner ][ TEMPLATE [=] template ][ ENCODING [=] encoding ][ TABLESPACE [=] tablespace ] ]CREATE DOMAINDefine a new domain.CREATE DOMAIN name [AS] data_type[ DEFAULT expression ][ constraint [ ... ] ]Where constraint is:[ CONSTRAINT constraint_name ]{ NOT NULL | NULL | CHECK (expression) }CREATE FUNCTIONDefine a new function.CREATE [ OR REPLACE ] FUNCTION name ( [ [ arg_name ] arg_type [, ...] ] )RETURNS ret_type{ LANGUAGE lang_name| IMMUTABLE | STABLE | VOLATILE| CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT| [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER| AS 'definition'| AS 'obj_file', 'link_symbol'} ...[ WITH ( attribute [, ...] ) ]CREATE GROUPDefine a new user group.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-26-2048.jpg&f=jpg&w=240)
![PostgreSQL20CREATE GROUP name [ [ WITH ] option [ ... ] ]Where option can be:SYSID gid| USER username [, ...]CREATE INDEXDefine a new index.CREATE [ UNIQUE ] INDEX name ON table [ USING method ]( { column | ( expression ) } [ opclass ] [, ...] )[ TABLESPACE tablespace ][ WHERE predicate ]CREATE LANGUAGEDefine a new procedural language.CREATE [ TRUSTED ] [ PROCEDURAL ] LANGUAGE nameHANDLER call_handler [ VALIDATOR val_function ]CREATE OPERATORDefine a new operator.CREATE OPERATOR name (PROCEDURE = func_name[, LEFTARG = left_type ] [, RIGHTARG = right_type ][, COMMUTATOR = com_op ] [, NEGATOR = neg_op ][, RESTRICT = res_proc ] [, JOIN = join_proc ][, HASHES ] [, MERGES ][, SORT1 = left_sort_op ] [, SORT2 = right_sort_op ][, LTCMP = less_than_op ] [, GTCMP = greater_than_op ])CREATE OPERATOR CLASSDefine a new operator class.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-27-2048.jpg&f=jpg&w=240)
![PostgreSQL21CREATE OPERATOR CLASS name [ DEFAULT ] FOR TYPE data_typeUSING index_method AS{ OPERATOR strategy_number operator_name [ ( op_type, op_type ) ] [ RECHECK ]| FUNCTION support_number func_name ( argument_type [, ...] )| STORAGE storage_type} [, ... ]CREATE RULEDefine a new rewrite rule.CREATE [ OR REPLACE ] RULE name AS ON eventTO table [ WHERE condition ]DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }CREATE SCHEMADefine a new schema.CREATE SCHEMA schema_name[ AUTHORIZATION username ] [ schema_element [ ... ] ]CREATE SCHEMA AUTHORIZATION username[ schema_element [ ... ] ]CREATE SEQUENCEDefine a new sequence generator.CREATE [ TEMPORARY | TEMP ] SEQUENCE name[ INCREMENT [ BY ] increment ][ MINVALUE minvalue | NO MINVALUE ][ MAXVALUE maxvalue | NO MAXVALUE ][ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]CREATE TABLEDefine a new table.CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name ({ column_name data_type [ DEFAULT default_expr ] [ column_constraint [ ... ] ]| table_constraint| LIKE parent_table [ { INCLUDING | EXCLUDING } DEFAULTS ] } [, ... ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-28-2048.jpg&f=jpg&w=240)
![PostgreSQL22)[ INHERITS ( parent_table [, ... ] ) ][ WITH OIDS | WITHOUT OIDS ][ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ][ TABLESPACE tablespace ]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 ]CREATE TABLE ASDefine a new table from the results of a query.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-29-2048.jpg&f=jpg&w=240)
![PostgreSQL23CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name[ (column_name [, ...] ) ] [ [ WITH | WITHOUT ] OIDS ]AS queryCREATE TABLESPACEDefine a new tablespace.CREATE TABLESPACE tablespace_name [ OWNER username ] LOCATION 'directory'CREATE TRIGGERDefine a new trigger.CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }ON table [ FOR [ EACH ] { ROW | STATEMENT } ]EXECUTE PROCEDURE func_name ( arguments )CREATE TYPEDefine a new data type.CREATE TYPE name AS( attribute_name data_type [, ... ] )CREATE TYPE name (INPUT = input_function,OUTPUT = output_function[ , RECEIVE = receive_function ][ , SEND = send_function ][ , ANALYZE = analyze_function ][ , INTERNALLENGTH = { internal_length | VARIABLE } ][ , PASSEDBYVALUE ][ , ALIGNMENT = alignment ][ , STORAGE = storage ][ , DEFAULT = default ][ , ELEMENT = element ][ , DELIMITER = delimiter ])CREATE USERDefine a new database user account.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-30-2048.jpg&f=jpg&w=240)
![PostgreSQL24CREATE USER name [ [ WITH ] option [ ... ] ]Where option can be:SYSID uid| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'| CREATEDB | NOCREATEDB| CREATEUSER | NOCREATEUSER| IN GROUP group_name [, ...]| VALID UNTIL 'abs_time'CREATE VIEWDefine a new view.CREATE [ OR REPLACE ] VIEW name [ ( column_name [, ...] ) ] AS queryDEALLOCATEDeallocate a prepared statement.DEALLOCATE [ PREPARE ] plan_nameDECLAREDefine a cursor.DECLARE name [ BINARY ] [ INSENSITIVE ] [ [ NO ] SCROLL ]CURSOR [ { WITH | WITHOUT } HOLD ] FOR query[ FOR { READ ONLY | UPDATE [ OF column [, ...] ] } ]DELETEDelete rows of a table.DELETE FROM [ ONLY ] table [ WHERE condition ]DROP AGGREGATERemove an aggregate function.DROP AGGREGATE name ( type ) [ CASCADE | RESTRICT ]DROP CASTRemove a cast.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-31-2048.jpg&f=jpg&w=240)
![PostgreSQL25DROP CAST (source_type AS target_type) [ CASCADE | RESTRICT ]DROP CONVERSIONRemove a conversion.DROP CONVERSION name [ CASCADE | RESTRICT ]DROP DATABASERemove a database.DROP DATABASE nameDROP DOMAINRemove a domain.DROP DOMAIN name [, ...] [ CASCADE | RESTRICT ]DROP FUNCTIONRemove a function.DROP FUNCTION name ( [ type [, ...] ] ) [ CASCADE | RESTRICT ]DROP GROUPRemove a user group.DROP GROUP nameDROP INDEXRemove an index.DROP INDEX name [, ...] [ CASCADE | RESTRICT ]DROP LANGUAGERemove a procedural language.DROP [ PROCEDURAL ] LANGUAGE name [ CASCADE | RESTRICT ]DROP OPERATORRemove an operator.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-32-2048.jpg&f=jpg&w=240)
![PostgreSQL26DROP OPERATOR name ( { left_type | NONE } , { right_type | NONE } )[ CASCADE | RESTRICT ]DROP OPERATOR CLASSRemove an operator class.DROP OPERATOR CLASS name USING index_method [ CASCADE | RESTRICT ]DROP RULERemove a rewrite rule.DROP RULE name ON relation [ CASCADE | RESTRICT ]DROP SCHEMARemove a schema.DROP SCHEMA name [, ...] [ CASCADE | RESTRICT ]DROP SEQUENCERemove a sequence.DROP SEQUENCE name [, ...] [ CASCADE | RESTRICT ]DROP TABLERemove a table.DROP TABLE name [, ...] [ CASCADE | RESTRICT ]DROP TABLESPACERemove a tablespace.DROP TABLESPACE tablespace_nameDROP TRIGGERRemove a trigger.DROP TRIGGER name ON table [ CASCADE | RESTRICT ]DROP TYPERemove a data type.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-33-2048.jpg&f=jpg&w=240)
![PostgreSQL27DROP TYPE name [, ...] [ CASCADE | RESTRICT ]DROP USERRemove a database user account.DROP USER nameDROP VIEWRemove a view.DROP VIEW name [, ...] [ CASCADE | RESTRICT ]ENDCommit the current transaction.END [ WORK | TRANSACTION ]EXECUTEExecute a prepared statement.EXECUTE plan_name [ (parameter [, ...] ) ]EXPLAINShow the execution plan of a statement.EXPLAIN [ ANALYZE ] [ VERBOSE ] statementFETCHRetrieve rows from a query using a cursor.FETCH [ direction { FROM | IN } ] cursor_nameWhere direction can be empty or one of:NEXTPRIORFIRSTLASTABSOLUTE countRELATIVE countcountALLFORWARDFORWARD count](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-34-2048.jpg&f=jpg&w=240)
![PostgreSQL28FORWARD ALLBACKWARDBACKWARD countBACKWARD ALLGRANTDefine access privileges.GRANT { { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }[,...] | ALL [ PRIVILEGES ] }ON [ TABLE ] table_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { { CREATE | TEMPORARY | TEMP } [,...] | ALL [ PRIVILEGES ] }ON DATABASE db_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { CREATE | ALL [ PRIVILEGES ] }ON TABLESPACE tablespace_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { EXECUTE | ALL [ PRIVILEGES ] }ON FUNCTION func_name ([type, ...]) [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { USAGE | ALL [ PRIVILEGES ] }ON LANGUAGE lang_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { { CREATE | USAGE } [,...] | ALL [ PRIVILEGES ] }ON SCHEMA schema_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]INSERTCreate new rows in a table.INSERT INTO table [ ( column [, ...] ) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-35-2048.jpg&f=jpg&w=240)
![PostgreSQL29{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) | query }LISTENListen for a notification.LISTEN nameLOADLoad or reload a shared library file.LOAD 'filename'LOCKLock a table.LOCK [ TABLE ] name [, ...] [ IN lock_mode MODE ] [ NOWAIT ]Where lock_mode is one of:ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE| SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVEMOVEPosition a cursor.MOVE [ direction { FROM | IN } ] cursor_nameNOTIFYGenerate a notification.NOTIFY namePREPAREPrepare a statement for execution.PREPARE plan_name [ (data_type [, ...] ) ] AS statementREINDEXRebuild indexes.REINDEX { DATABASE | TABLE | INDEX } name [ FORCE ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-36-2048.jpg&f=jpg&w=240)
![PostgreSQL30RELEASE SAVEPOINTDestroy a previously defined savepoint.RELEASE [ SAVEPOINT ] savepoint_nameRESETRestore the value of a runtime parameter to the default value.RESET nameRESET ALLREVOKERemove access privileges.REVOKE [ GRANT OPTION FOR ]{ { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }[,...] | ALL [ PRIVILEGES ] }ON [ TABLE ] table_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ { CREATE | TEMPORARY | TEMP } [,...] | ALL [ PRIVILEGES ] }ON DATABASE db_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ CREATE | ALL [ PRIVILEGES ] }ON TABLESPACE tablespace_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ EXECUTE | ALL [ PRIVILEGES ] }ON FUNCTION func_name ([type, ...]) [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ USAGE | ALL [ PRIVILEGES ] }ON LANGUAGE lang_name [, ...]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-37-2048.jpg&f=jpg&w=240)
![PostgreSQL31FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ { CREATE | USAGE } [,...] | ALL [ PRIVILEGES ] }ON SCHEMA schema_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]ROLLBACKAbort the current transaction.ROLLBACK [ WORK | TRANSACTION ]ROLLBACK TO SAVEPOINTRoll back to a savepoint.ROLLBACK [ WORK | TRANSACTION ] TO [ SAVEPOINT ] savepoint_nameSAVEPOINTDefine a new savepoint within the current transaction.SAVEPOINT savepoint_nameSELECTRetrieve rows from a table or view.SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]* | expression [ AS output_name ] [, ...][ FROM from_item [, ...] ][ WHERE condition ][ GROUP BY expression [, ...] ][ HAVING condition [, ...] ][ { UNION | INTERSECT | EXCEPT } [ ALL ] select ][ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ][ LIMIT { count | ALL } ][ OFFSET start ][ FOR UPDATE [ OF table_name [, ...] ] ]Where from_item can be one of:[ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]( select ) [ AS ] alias [ ( column_alias [, ...] ) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-38-2048.jpg&f=jpg&w=240)
![PostgreSQL32function_name ( [ argument [, ...] ] )[ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ]function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )from_item [ NATURAL ] join_type from_item[ ON join_condition | USING ( join_column [, ...] ) ]SELECT INTODefine a new table from the results of a query.SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]* | expression [ AS output_name ] [, ...]INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table[ FROM from_item [, ...] ][ WHERE condition ][ GROUP BY expression [, ...] ][ HAVING condition [, ...] ][ { UNION | INTERSECT | EXCEPT } [ ALL ] select ][ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ][ LIMIT { count | ALL } ][ OFFSET start ][ FOR UPDATE [ OF table_name [, ...] ] ]SETChange a runtime parameter.SET [ SESSION | LOCAL ] name { TO | = } { value | 'value' | DEFAULT }SET [ SESSION | LOCAL ] TIME ZONE { time_zone | LOCAL | DEFAULT }SET CONSTRAINTSSet constraint checking modes for the current transaction.SET CONSTRAINTS { ALL | name [, ...] } { DEFERRED | IMMEDIATE }SET SESSION AUTHORIZATION](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-39-2048.jpg&f=jpg&w=240)
![PostgreSQL33Set the session user identifier and the current user identifier of the current session.SET [ SESSION | LOCAL ] SESSION AUTHORIZATION usernameSET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULTRESET SESSION AUTHORIZATIONSET TRANSACTIONSet the characteristics of the current transaction.SET TRANSACTION transaction_mode [, ...]SET SESSION CHARACTERISTICS AS TRANSACTION transaction_mode [, ...]Where transaction_mode is one of:ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED| READ UNCOMMITTED }READ WRITE | READ ONLYSHOWShow the value of a runtime parameter.SHOW nameSHOW ALLSTART TRANSACTIONStart a transaction block.START TRANSACTION [ transaction_mode [, ...] ]Where transaction_mode is one of:ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED| READ UNCOMMITTED }READ WRITE | READ ONLYTRUNCATEEmpty a table.TRUNCATE [ TABLE ] nameUNLISTEN](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-40-2048.jpg&f=jpg&w=240)
![PostgreSQL34Stop listening for a notification.UNLISTEN { name | * }UPDATEUpdate rows of a table.UPDATE [ ONLY ] table SET column = { expression | DEFAULT } [, ...][ FROM from_list ][ WHERE condition ]VACUUMGarbage-collect and optionally analyze a database.VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ table ]VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-41-2048.jpg&f=jpg&w=240)


![PostgreSQL37BinaryDataTypesThe bytea data type allows storage of binary strings as in the table given below.Name Storage Size Descriptionbytea 1 or 4 bytes plus the actual binary string variable-length binary stringDate/TimeTypesPostgreSQL supports a full set of SQL date and time types, as shown in table below. Datesare counted according to the Gregorian calendar. Here, all the types have resolution of 1microsecond / 14 digits except date type, whose resolution is day.Name Storage Size Description Low Value High Valuetimestamp[(p)] [withouttime zone ]8 bytesboth date andtime (no timezone)4713 BC 294276 ADtimestamp[(p) ] withtime zone8 bytesboth date andtime, with timezone4713 BC 294276 ADdate 4 bytesdate (no timeof day)4713 BC 5874897 ADtime [ (p)] [without timezone ]8 bytestime of day (nodate)00:00:00 24:00:00time [ (p)]with timezone12 bytestimes of dayonly, with timezone00:00:00+1459 24:00:00-1459interval[fields ] [(p) ]12 bytes time interval-178000000years178000000 yearsBooleanTypePostgreSQL provides the standard SQL type Boolean. The Boolean data type can have thestates- true, false, and a third state, unknown, which is represented by the SQL null value.Name Storage Size Descriptionboolean 1 byte state of true or false](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-44-2048.jpg&f=jpg&w=240)
![PostgreSQL38EnumeratedTypeEnumerated (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');Enumerated, once created, can be used like any other types.GeometricTypeGeometric data types represent two-dimensional spatial objects. The most fundamentaltype, the point, forms the basis for all of the other types.Name Storage Size Representation Descriptionpoint 16 bytes Point on a plane (x,y)line 32 bytesInfinite line (not fullyimplemented)((x1,y1),(x2,y2))lseg 32 bytes Finite line segment ((x1,y1),(x2,y2))box 32 bytes Rectangular box ((x1,y1),(x2,y2))path 16+16n bytes Closed path (similar to polygon) ((x1,y1),...)path 16+16n bytes Open path [(x1,y1),...]polygon 40+16n Polygon (similar to closed path) ((x1,y1),...)circle 24 bytes Circle<(x,y),r> (center pointand radius)NetworkAddressTypePostgreSQL offers data types to store IPv4, IPv6, and MAC addresses. It is better to usethese types instead of plain text types to store network addresses because these typesoffer input error checking and specialized operators and functions.Name Storage Size Descriptioncidr 7 or 19 bytes IPv4 and IPv6 networksinet 7 or 19 bytes IPv4 and IPv6 hosts and networks](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-45-2048.jpg&f=jpg&w=240)

![PostgreSQL40JSONTypeThe json data type can be used to store JSON (JavaScript Object Notation) data. Suchdata can also be stored as text, but the json data type has the advantage of checking thateach 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-Example Example Resultarray_to_json('{{1,5},{99,100}}'::int[]) [[1,5],[99,100]]row_to_json(row(1,'foo')) {"f1":1,"f2":"foo"}ArrayTypePostgreSQL gives the opportunity to define a column of a table as a variable lengthmultidimensional array. Arrays of any built-in or user-defined base type, enum type, orcomposite type can be created.Declaration of ArraysArray type can be declared as-CREATE TABLE monthly_savings (name text,saving_per_quarter integer[],scheme text[][]);or by using the keyword "ARRAY" as-CREATE TABLE monthly_savings (name text,saving_per_quarter integer ARRAY[4],scheme text[][]);Inserting valuesArray values can be inserted as a literal constant, enclosing the element values withincurly braces and separating them by commas. An example is shown below.INSERT INTO monthly_savingsVALUES (‘Manisha’,‘{20000, 14600, 23500, 13250}’,‘{{“FD”, “MF”}, {“FD”, “Property”}}’);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-47-2048.jpg&f=jpg&w=240)
![PostgreSQL41Accessing ArraysAn example for accessing Arrays is shown below. The command given below will select thepersons whose savings are more in second quarter than fourth quarter.SELECT name FROM monhly_savings WHERE saving_per_quarter[2] >saving_per_quarter[4];Modifying ArraysAn example of modifying arrays is as shown below.UPDATE monthly_savings SET saving_per_quarter = '{25000,25000,27000,27000}'WHERE name = 'Manisha';or using the ARRAY expression syntax:UPDATE monthly_savings SET saving_per_quarter = ARRAY[25000,25000,27000,27000]WHERE name = 'Manisha';Searching ArraysAn example of searching arrays is as shown below.SELECT * FROM monthly_savings WHERE saving_per_quarter[1] = 10000 ORsaving_per_quarter[2] = 10000 ORsaving_per_quarter[3] = 10000 ORsaving_per_quarter[4] = 10000;If the size of array is known, the search method given above can be used. Else, thefollowing example shows how to search when the size is not known.SELECT * FROM monthly_savings WHERE 10000 = ANY (saving_per_quarter);CompositeTypesThis type represents a list of field names and their data types, i.e., structure of a row orrecord of a table.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-48-2048.jpg&f=jpg&w=240)

![PostgreSQL43 int8range - Range of bigint numrange - Range of numeric tsrange - Range of timestamp without time zone tstzrange - Range of timestamp with time zone daterange - Range of dateCustom range types can be created to make new types of ranges available, such as IPaddress ranges using the inet type as a base, or float ranges using the float data type asa base.Range types support inclusive and exclusive range boundaries using the [ ] and ( )characters, respectively. For example, '[4,9]' represents all the integers starting from andincluding 4 up to but not including 9.ObjectIdentifierTypesObject identifiers (OIDs) are used internally by PostgreSQL as primary keys for varioussystem tables. If WITH OIDS is specified or default_with_oids configuration variable isenabled, only then, in such cases OIDs are added to user-created tables. The followingtable lists several alias types. The OID alias types have no operations of their own exceptfor specialized input and output routines.Name References Description Value Exampleoid any numeric object identifier 564182regproc pg_proc function name sumregprocedure pg_proc function with argument types sum(int4)regoper pg_operator operator name +regoperator pg_operator operator with argument types *(integer,integer) or -(NONE,integer)regclass pg_class relation name pg_typeregtype pg_type data type name integerregconfig pg_ts_config text search configuration Englishregdictionary pg_ts_dict text search dictionary simplePseudoTypesThe PostgreSQL type system contains a number of special-purpose entries that arecollectively called pseudo-types. A pseudo-type cannot be used as a column data type,but it can be used to declare a function's argument or result type.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-50-2048.jpg&f=jpg&w=240)

![PostgreSQL45This chapter discusses about how to create a new database in your PostgreSQL.PostgreSQL provides two ways of creating a new database: Using CREATE DATABASE, an SQL command. Using createdb a command-line executable.Using CREATE DATABASEThis command will create a database from PostgreSQL shell prompt, but you should haveappropriate privilege to create a database. By default, the new database will be createdby cloning the standard system database template1.SyntaxThe basic syntax of CREATE DATABASE statement is as follows-CREATE DATABASE dbname;where dbname is the name of a database to create.ExampleFollowing is a simple example, which will create testdb in your PostgreSQL schema-postgres=# CREATE DATABASE testdb;postgres-#UsingcreatedbCommandPostgreSQL command line executable createdb is a wrapper around the SQLcommand CREATE DATABASE. The only difference between this command and SQLcommand CREATE DATABASE is that the former can be directly run from the commandline and it allows a comment to be added into the database, all in one command.SyntaxThe syntax for createdb is as shown below-createdb [option...] [dbname [description]]5. PostgreSQL – CREATE Database](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-52-2048.jpg&f=jpg&w=240)




![PostgreSQL50In this chapter, we will discuss how to delete the database in PostgreSQL. There are twooptions to delete a database- Using DROP DATABASE, an SQL command. Using dropdb a command-line executable.Be careful before using this operation because deleting an existing database would resultin loss of complete information stored in the database.Using DROP DATABASEThis command drops a database. It removes the catalog entries for the database anddeletes 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 targetdatabase (connect to postgres or any other database to issue this command).SyntaxThe syntax for DROP DATABASE is given below-DROP DATABASE [ IF EXISTS ] nameParametersThe table lists the parameters with their descriptions.Parameter DescriptionIF EXISTSDo not throw an error if the database does not exist. A notice is issued inthis case.name The name of the database to remove.We cannot drop a database that has any open connections, including our own connectionfrom psql or pgAdmin III. We must switch to another database or template1 if we want todelete the database we are currently connected to. Thus, it might be more convenient touse the program dropdb instead, which is a wrapper around this command.ExampleFollowing is a simple example, which will delete testdb from your PostgreSQL schema-postgres=# DROP DATABASE testdb;postgres-#7. PostgreSQL – DROP Database](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-57-2048.jpg&f=jpg&w=240)
![PostgreSQL51UsingdropdbCommandPostgresSQL command line executable dropdb is a command-line wrapper around theSQL command DROP DATABASE. There is no effective difference between droppingdatabases via this utility and via other methods for accessing the server. dropdb destroysan existing PostgreSQL database. The user, who executes this command must be adatabase super user or the owner of the database.SyntaxThe syntax for createdb is as shown below-dropdb [option...] dbnameParametersThe following table lists the parameters with their descriptions-Parameter Descriptiondbname The name of a database to be deleted.option command-line arguments, which dropdb accepts.OptionsThe following table lists the command-line arguments dropdb accepts-Option Description-e Shows the commands being sent to the server.-iIssues a verification prompt before doing anythingdestructive.-V Print the dropdb version and exit.--if-existsDo not throw an error if the database does not exist. Anotice is issued in this case.--helpShow help about dropdb command-line arguments, andexit.-h hostSpecifies the host name of the machine on which the serveris running.-p portSpecifies the TCP port or the local UNIX domain socket fileextension on which the server is listening for connections.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-58-2048.jpg&f=jpg&w=240)



















![PostgreSQL71An expression is a combination of one or more values, operators, and PostgresSQLfunctions that evaluate to a value.PostgreSQL EXPRESSIONS are like formulas and they are written in query language. Youcan also use to query the database for specific set of data.SyntaxConsider the basic syntax of the SELECT statement as follows-SELECT column1, column2, columnNFROM table_nameWHERE [CONTION | EXPRESSION];There are different types of PostgreSQL expressions, which are mentioned below.PostgreSQL–BooleanExpressionsPostgreSQL Boolean Expressions fetch the data on the basis of matching single value.Following is the syntax-SELECT column1, column2, columnNFROM table_nameWHERE SINGLE VALUE MATCHTING EXPRESSION;Consider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)14. PostgreSQL – Expressions](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-78-2048.jpg&f=jpg&w=240)
![PostgreSQL72Here is the simple example showing usage of PostgreSQL Boolean Expressions-testdb=# SELECT * FROM COMPANY WHERE SALARY = 10000;The above given PostgreSQL statement will produce the following result-id | name | age | address | salary----+-------+-----+----------+--------7 | James | 24 | Houston | 10000(1 row)PostgreSQL–NumericExpressionThese expressions are used to perform any mathematical operation in any query. Followingis the syntax-SELECT numerical_expression as OPERATION_NAME[FROM table_name WHERE CONDITION] ;Here numerical_expression is used for mathematical expression or any formula. Followingis a simple example showing usage of SQL Numeric Expressions-testdb=# SELECT (15 + 6) AS ADDITION ;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 knownas aggregate data calculations against a table or a specific table column.testdb=# SELECT COUNT(*) AS "RECORDS" FROM COMPANY;The above given PostgreSQL statement will produce the following result-RECORDS---------7(1 row)](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-79-2048.jpg&f=jpg&w=240)

![PostgreSQL74The PostgreSQL WHERE clause is used to specify a condition while fetching the data fromsingle table or joining with multiple tables.If the given condition is satisfied, only then it returns specific value from the table. Youcan filter out rows that you do not want included in the result-set by using the WHEREclause.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.SyntaxThe basic syntax of SELECT statement with WHERE clause is as follows-SELECT column1, column2, columnNFROM table_nameWHERE [search_condition]You can specify a search_condition using comparison or logical operators.like >, <, =,LIKE, NOT, etc. The following examples would make this concept clear.ExampleConsider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)15. PostgreSQL – WHERE Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-81-2048.jpg&f=jpg&w=240)




![PostgreSQL79The PostgreSQL AND and OR operators are used to combine multiple conditions to narrowdown selected data in a PostgreSQL statement. These two operators are called conjunctiveoperators.These operators provide a means to make multiple comparisons with different operatorsin the same PostgreSQL statement.TheANDOperatorThe AND operator allows the existence of multiple conditions in a PostgreSQL statement'sWHERE clause. While using AND operator, complete condition will be assumed true whenall the conditions are true. For example [condition1] AND [condition2] will be true onlywhen both condition1 and condition2 are true.SyntaxThe basic syntax of AND operator with WHERE clause is as follows-SELECT column1, column2, columnNFROM table_nameWHERE [condition1] AND [condition2]...AND [conditionN];You can combine N number of conditions using AND operator. For an action to be takenby the PostgreSQL statement, whether it be a transaction or query, all conditionsseparated by the AND must be TRUE.ExampleConsider the table COMPANY, having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)16. PostgreSQL – AND & OR Conjunctive Operators](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-86-2048.jpg&f=jpg&w=240)
![PostgreSQL80Following SELECT statement lists down all the records where AGE is greater than or equalto 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-id | name | age | address | salary----+-------+-----+------------+--------4 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 85000(2 rows)TheOROperatorThe OR operator is also used to combine multiple conditions in a PostgreSQL statement'sWHERE clause. While using OR operator, complete condition will be assumed true when atleast any of the conditions is true. For example [condition1] OR [condition2] will be true ifeither condition1 or condition2 is true.SyntaxThe basic syntax of OR operator with WHERE clause is as follows-SELECT column1, column2, columnNFROM table_nameWHERE [condition1] OR [condition2]...OR [conditionN]You can combine N number of conditions using OR operator. For an action to be taken bythe PostgreSQL statement, whether it be a transaction or query, only any ONE of theconditions separated by the OR must be TRUE.ExampleConsider the COMPANY table, having the following records-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 45000](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-87-2048.jpg&f=jpg&w=240)

![PostgreSQL82The PostgreSQL UPDATE Query is used to modify the existing records in a table. You canuse WHERE clause with UPDATE query to update the selected rows. Otherwise, all the rowswould be updated.SyntaxThe basic syntax of UPDATE query with WHERE clause is as follows-UPDATE table_nameSET column1 = value1, column2 = value2...., columnN = valueNWHERE [condition];You can combine N number of conditions using AND or OR operators.ExampleConsider the table COMPANY, having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which would update ADDRESS for a customer, whose ID is 6-testdb=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3;Now, COMPANY table would have the following records-id | name | age | address | salary----+-------+-----+------------+--------1 | Paul | 32 | California | 200002 | Allen | 25 | Texas | 1500017. PostgreSQL – UPDATE Query](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-89-2048.jpg&f=jpg&w=240)

![PostgreSQL84The PostgreSQL DELETE Query is used to delete the existing records from a table. Youcan use WHERE clause with DELETE query to delete the selected rows. Otherwise, all therecords would be deleted.SyntaxThe basic syntax of DELETE query with WHERE clause is as follows-DELETE FROM table_nameWHERE [condition];You can combine N number of conditions using AND or OR operators.ExampleConsider the table COMPANY, having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which would DELETE a customer whose ID is 7-testdb=# DELETE FROM COMPANY WHERE ID = 2;Now, COMPANY table will have the following records-id | name | age | address | salary----+-------+-----+-------------+--------1 | Paul | 32 | California | 200003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 6500018. PostgreSQL – DELETE Query](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-91-2048.jpg&f=jpg&w=240)




![PostgreSQL89The PostgreSQL LIMIT clause is used to limit the data amount returned by the SELECTstatement.SyntaxThe basic syntax of SELECT statement with LIMIT clause is as follows-SELECT column1, column2, columnNFROM table_nameLIMIT [no of rows]Following is the syntax of LIMIT clause when it is used along with OFFSET clause-SELECT column1, column2, columnNFROM table_nameLIMIT [no of rows] OFFSET [row num]LIMIT and OFFSET allow you to retrieve just a portion of the rows that are generated bythe rest of the query.ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which limits the row in the table according to the number of rowsyou want to fetch from table-testdb=# SELECT * FROM COMPANY LIMIT 4;20. PostgreSQL – LIMIT Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-96-2048.jpg&f=jpg&w=240)

![PostgreSQL91The PostgreSQL ORDER BY clause is used to sort the data in ascending or descendingorder, based on one or more columns.Syntax-The basic syntax of ORDER BY clause is as follows-SELECT column-listFROM 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 columnyou are using to sort, that column should be available in column-list.ExampleConsider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which would sort the result in descending order by SALARY-testdb=# SELECT * FROM COMPANY ORDER BY AGE ASC;21. PostgreSQL – ORDER BY Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-98-2048.jpg&f=jpg&w=240)


![PostgreSQL94The PostgreSQL GROUP BY clause is used in collaboration with the SELECT statement togroup together those rows in a table that have identical data. This is done to eliminateredundancy in the output and/or compute aggregates that apply to these groups.The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes theORDER BY clause.SyntaxThe basic syntax of GROUP BY clause is given below. The GROUP BY clause must followthe conditions in the WHERE clause and must precede the ORDER BY clause if one is used.SELECT column-listFROM table_nameWHERE [ conditions ]GROUP BY column1, column2....columnNORDER BY column1, column2....columnNYou can use more than one column in the GROUP BY clause. Make sure whatever columnyou are using to group, that column should be available in column-list.ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)22. PostgreSQL – GROUP BY](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-101-2048.jpg&f=jpg&w=240)


![PostgreSQL97In PostgreSQL, the WITH query provides a way to write auxiliary statements for use in alarger query. It helps in breaking down complicated and large queries into simpler forms,which are easily readable. These statements often referred to as Common TableExpressions or CTEs, can be thought of as defining temporary tables that exist just for onequery.The WITH query being CTE query, is particularly useful when subquery is executed multipletimes. It is equally helpful in place of temporary tables. It computes the aggregation onceand allows us to reference it by its name (may be multiple times) in the queries.The WITH clause must be defined before it is used in the query.SyntaxThe basic syntax of WITH query is as follows-WITHname_for_summary_data AS (SELECT Statement)SELECT columnsFROM name_for_summary_dataWHERE conditions <=> (SELECT columnFROM name_for_summary_data)[ORDER BY columns]Where name_for_summary_data is the name given to the WITH clause. Thename_for_summary_data can be the same as an existing table name and will takeprecedence.You can use data-modifying statements (INSERT, UPDATE or DELETE) in WITH. This allowsyou to perform several different operations in the same query.RecursiveWITHRecursive WITH or Hierarchical queries, is a form of CTE where a CTE can reference toitself, i.e., a WITH query can refer to its own output, hence the name recursive.23. PostgreSQL – WITH Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-104-2048.jpg&f=jpg&w=240)



![PostgreSQL101The HAVING clause allows us to pick out particular rows where the function's result meetssome condition.The WHERE clause places conditions on the selected columns, whereas the HAVING clauseplaces conditions on groups created by the GROUP BY clause.SyntaxThe following is the position of the HAVING clause in a SELECT query-SELECTFROMWHEREGROUP BYHAVINGORDER BYThe HAVING clause must follow the GROUP BY clause in a query and must also precedethe ORDER BY clause if used. The following is the syntax of the SELECT statement,including the HAVING clause-SELECT column1, column2FROM table1, table2WHERE [ conditions ]GROUP BY column1, column2HAVING [ conditions ]ORDER BY column1, column2ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 6500024. PostgreSQL – HAVING Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-108-2048.jpg&f=jpg&w=240)


![PostgreSQL104The PostgreSQL DISTINCT keyword is used in conjunction with SELECT statement toeliminate all the duplicate records and fetching only unique records.There may be a situation when you have multiple duplicate records in a table. Whilefetching such records, it makes more sense to fetch only unique records instead of fetchingduplicate records.SyntaxThe basic syntax of DISTINCT keyword to eliminate duplicate records is as follows-SELECT DISTINCT column1, column2,.....columnNFROM table_nameWHERE [condition]ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Let us add two more records to this table as follows-INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)VALUES (8, 'Paul', 32, 'California', 20000.00 );INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)VALUES (9, 'Allen', 25, 'Texas', 15000.00 );25. PostgreSQL – DISTINCT Keyword](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-111-2048.jpg&f=jpg&w=240)














![PostgreSQL119The PostgreSQL UNION clause/operator is used to combine the results of two or moreSELECT statements without returning any duplicate rows.To use UNION, each SELECT must have the same number of columns selected, the samenumber of column expressions, the same data type, and have them in the same order butthey do not have to be the same length.SyntaxThe basic syntax of UNION is as follows-SELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]UNIONSELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]Here, given condition could be any given expression based on your requirement.ExampleConsider the following two tables, (a) COMPANY table is as follows-testdb=# SELECT * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)28. PostgreSQL – UNIONS Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-126-2048.jpg&f=jpg&w=240)

![PostgreSQL121TheUNIONALLClauseThe UNION ALL operator is used to combine the results of two SELECT statementsincluding duplicate rows. The same rules that apply to UNION apply to the UNION ALLoperator as well.Syntax:The basic syntax of UNION ALL is as follows-SELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]UNION ALLSELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]Here, given condition could be any given expression based on your requirement.ExampleNow, let us join above-mentioned two tables in our SELECT statement as follows-testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENTON COMPANY.ID = DEPARTMENT.EMP_IDUNION ALLSELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENTON COMPANY.ID = DEPARTMENT.EMP_ID;This would produce the following result-emp_id | name | dept--------+-------+--------------1 | Paul | IT Billing2 | Allen | Engineering7 | James | Finance3 | Teddy | Engineering4 | Mark | Finance5 | David | Engineering6 | Kim | Finance1 | Paul | IT Billing2 | Allen | Engineering](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-128-2048.jpg&f=jpg&w=240)




![PostgreSQL126You can rename a table or a column temporarily by giving another name, which is knownas ALIAS. The use of table aliases means to rename a table in a particular PostgreSQLstatement. Renaming is a temporary change and the actual table name does not changein the database.The column aliases are used to rename a table's columns for the purpose of a particularPostgreSQL query.SyntaxThe basic syntax of table alias is as follows-SELECT column1, column2....FROM table_name AS alias_nameWHERE [condition];The basic syntax of column alias is as follows-SELECT column_name AS alias_nameFROM table_nameWHERE [condition];ExampleConsider the following two tables, (a) COMPANY table is as follows-testdb=# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)30. PostgreSQL – ALIAS Syntax](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-133-2048.jpg&f=jpg&w=240)



![PostgreSQL130 A CONSTRAINT option when specified creates a constraint trigger. This is the sameas a regular trigger except that the timing of the trigger firing can be adjustedusing SET CONSTRAINTS. Constraint triggers are expected to raise an exceptionwhen the constraints they implement are violated.SyntaxThe basic syntax of creating a trigger is as follows-CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_nameON table_name[-- Trigger logic goes here....];Here, event_name could be INSERT, DELETE, UPDATE, and TRUNCATE databaseoperation on the mentioned table table_name. You can optionally specify FOR EACH ROWafter table name.Following is the syntax of creating a trigger on an UPDATE operation on one or morespecified columns of a table as follows-CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_nameON table_name[-- Trigger logic goes here....];ExampleLet us consider a case where we want to keep audit trial for every record being insertedin COMPANY table, which we will create newly as follows (Drop COMPANY table if youalready have it).testdb=# CREATE TABLE COMPANY(ID INT PRIMARY KEY NOT NULL,NAME TEXT NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(50),SALARY REAL);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-137-2048.jpg&f=jpg&w=240)









![PostgreSQL140Views are pseudo-tables. That is, they are not real tables; nevertheless appear as ordinarytables to SELECT. A view can represent a subset of a real table, selecting certain columnsor certain rows from an ordinary table. A view can even represent joined tables. Becauseviews are assigned separate permissions, you can use them to restrict table access so thatthe 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 viewcan be created from one or many tables, which depends on the written PostgreSQL queryto create a view.Views, which are kind of virtual tables, allow users to do the following- Structure data in a way that users or classes of users find natural or intuitive. Restrict access to the data such that a user can only see limited data instead ofcomplete table. Summarize data from various tables, which can be used to generate reports.Since views are not ordinary tables, you may not be able to execute a DELETE, INSERT,or UPDATE statement on a view. However, you can create a RULE to correct this problemof using DELETE, INSERT or UPDATE on a view.CreatingViewsThe PostgreSQL views are created using the CREATE VIEW statement. The PostgreSQLviews can be created from a single table, multiple tables, or another view.The basic CREATE VIEW syntax is as follows-CREATE [TEMP | TEMPORARY] VIEW view_name ASSELECT column1, column2.....FROM table_nameWHERE [condition];You can include multiple tables in your SELECT statement in very similar way as you usethem in normal PostgreSQL SELECT query. If the optional TEMP or TEMPORARY keywordis present, the view will be created in the temporary space. Temporary views areautomatically dropped at the end of the current session.35. PostgreSQL – VIEWS](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-147-2048.jpg&f=jpg&w=240)





![PostgreSQL146Locks or Exclusive Locks or Write Locks prevent users from modifying a row or an entiretable. Rows modified by UPDATE and DELETE are then exclusively locked automatically forthe duration of the transaction. This prevents other users from changing the row until thetransaction is either committed or rolled back.The only time when users must wait for other users is when they are trying to modify thesame row. If they modify different rows, no waiting is necessary. SELECT queries neverhave to wait.The database performs locking automatically. In certain cases, however, locking must becontrolled manually. Manual locking can be done by using the LOCK command. It allowsspecification of a transaction's lock type and scope.Syntax for LOCK commandThe basic syntax for LOCK command is as follows-LOCK [ TABLE ]nameINlock_mode name: The name (optionally schema-qualified) of an existing table to lock. If ONLYis specified before the table name, only that table is locked. If ONLY is not specified,the table and all its descendant tables (if any) are locked. lock_mode: The lock mode specifies which locks this lock conflicts with. If no lockmode is specified, then ACCESS EXCLUSIVE, the most restrictive mode, is used.Possible values are: ACCESS SHARE, ROW SHARE , ROW EXCLUSIVE, SHAREUPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESSEXCLUSIVE.Once obtained, the lock is held for the remainder of the current transaction. There is noUNLOCK TABLE command; locks are always released at the transaction end.DeadLocksDeadlocks can occur when two transactions are waiting for each other to finish theiroperations. While PostgreSQL can detect them and end them with a ROLLBACK, deadlockscan still be inconvenient. To prevent your applications from running into this problem,make sure to design them in such a way that they will lock objects in the same order.37. PostgreSQL – LOCKS](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-153-2048.jpg&f=jpg&w=240)

![PostgreSQL148A subquery or Inner query or Nested query is a query within another PostgreSQL queryand embedded within the WHERE clause.A subquery is used to return data that will be used in the main query as a condition tofurther restrict the data to be retrieved.Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE statements alongwith the operators like =, <, >, >=, <=, IN, etc.There are a few rules that subqueries must follow. Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiplecolumns are in the main query for the subquery to compare its selected columns. An ORDER BY cannot be used in a subquery, although the main query can use anORDER BY. The GROUP BY can be used to perform the same function as the ORDERBY in a subquery. Subqueries that return more than one row can only be used with multiple valueoperators, such as the IN, EXISTS, NOT IN, ANY/SOME, ALL operator. The BETWEEN operator cannot be used with a subquery; however, the BETWEENcan be used within the subquery.SubquerieswiththeSELECTStatementSubqueries are most frequently used with the SELECT statement. The basic syntax is asfollows-SELECT column_name [, column_name ]FROM table1 [, table2 ]WHERE column_name OPERATOR(SELECT column_name [, column_name ]FROM table1 [, table2 ][WHERE])38. PostgreSQL – Sub Queries](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-155-2048.jpg&f=jpg&w=240)
![PostgreSQL149ExampleConsider the COMPANY table having the following records-id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Now, let us check the following sub-query with SELECT statement-testdb=# SELECT *FROM COMPANYWHERE ID IN (SELECT IDFROM COMPANYWHERE SALARY > 45000) ;This would produce the following result-id | name | age | address | salary----+-------+-----+-------------+--------4 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 85000(2 rows)SubquerieswiththeINSERTStatementSubqueries also can be used with INSERT statements. The INSERT statement uses thedata returned from the subquery to insert into another table. The selected data in thesubquery can be modified with any of the character, date, or number functions.The basic syntax is as follows-INSERT INTO table_name [ (column1 [, column2 ]) ]SELECT [ *|column1 [, column2 ]FROM table1 [, table2 ][ WHERE VALUE OPERATOR ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-156-2048.jpg&f=jpg&w=240)
[ WHERE) ]ExampleAssuming, we have COMPANY_BKP table available, which is backup of the COMPANY table.The following example updates SALARY by 0.50 times in the COMPANY table for all thecustomers, whose AGE is greater than or equal to 27-testdb=# UPDATE COMPANYSET SALARY = SALARY * 0.50WHERE AGE IN (SELECT AGE FROM COMPANY_BKPWHERE AGE >= 27 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-157-2048.jpg&f=jpg&w=240)
[ WHERE) ]ExampleAssuming, we have COMPANY_BKP table available, which is a backup of the COMPANYtable.The following example deletes records from the COMPANY table for all the customers,whose AGE is greater than or equal to 27-testdb=# DELETE FROM COMPANYWHERE AGE IN (SELECT AGE FROM COMPANY_BKPWHERE AGE > 27 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-158-2048.jpg&f=jpg&w=240)



![PostgreSQL155Whenever an object is created in a database, an owner is assigned to it. The owner isusually the one who executed the creation statement. For most kinds of objects, the initialstate is that only the owner (or a superuser) can modify or delete the object. To allowother roles or users to use it, privileges or permission must be granted.Different kinds of privileges in PostgreSQL are- SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, CREATE, CONNECT, TEMPORARY, EXECUTE, and USAGEDepending on the type of the object (table, function, etc.,), privileges are applied to theobject. To assign privileges to the users, the GRANT command is used.Syntax for GRANTBasic syntax for GRANT command is as follows-GRANT privilege [, ...]ON object [, ...]TO { PUBLIC | GROUP group | username } privilege values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. object: The name of an object to which to grant access. The possible objects are:table, view, sequence PUBLIC: A short form representing all users. GROUP group: A group to whom to grant privileges.40. PostgreSQL – PRIVILEGES](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-162-2048.jpg&f=jpg&w=240)
![PostgreSQL156 username: The name of a user to whom to grant privileges. PUBLIC is a shortform representing all users.The privileges can be revoked using the REVOKE command.Syntax for REVOKEBasic syntax for REVOKE command is as follows-REVOKE privilege [, ...]ON object [, ...]FROM { PUBLIC | GROUP groupname | username } privilege values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. object: The name of an object to which to grant access. The possible objects are:table, view, sequence PUBLIC: A short form representing all users. GROUP group: A group to whom to grant privileges. username: The name of a user to whom to grant privileges. PUBLIC is a shortform representing all users.ExampleTo understand the privileges, let us first create a USER as follows-testdb=# CREATE USER manisha WITH PASSWORD 'password';CREATE ROLEThe message CREATE ROLE indicates that the USER "manisha" is created.Consider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-163-2048.jpg&f=jpg&w=240)









![PostgreSQL166PostgreSQL functions, also known as Stored Procedures, allow you to carry outoperations that would normally take several queries and round trips in a single functionwithin the database. Functions allow database reuse as other applications can interactdirectly with your stored procedures instead of a middle-tier or duplicating code.Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc.SyntaxThe basic syntax to create a function is as follows-CREATE [OR REPLACE] FUNCTION function_name (arguments)RETURNS return_datatype AS $variable_name$DECLAREdeclaration;[...]BEGIN< function_body >[...]RETURN { variable_name | value }END; LANGUAGE plpgsql;Where, function-name specifies the name of the function. [OR REPLACE] option allows modifying an existing function. The function must contain a return statement. 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 referencethe type of a table column. function-body contains the executable part. The AS keyword is used for creating a standalone function. plpgsql is the name of the language that the function is implemented in. Here, weuse 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 beenclosed by single quotes.42. PostgreSQL – Functions](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-173-2048.jpg&f=jpg&w=240)

























![PostgreSQL192(1 row)expr REGEXP patternREGEXP_MATCHES(string text, pattern text [, flags text]) function performs a patternmatch of expr against pattern. Returns 1 if expr matches pat; otherwise it returns 0. Ifeither expr or pat is NULL, the result is NULL. REGEXP_MATCHES is not case sensitive,except when used with binary strings.REGEXP_REPLACE(string text, pattern text, replacement text [, flags text]) functionreplaces substring(s) matching a POSIX regular expression.REGEXP_SPLIT_TO_ARRAY(string text, pattern text [, flags text ]), Split string using aPOSIX regular expression as the delimiter.REGEXP_SPLIT_TO_TABLE(string text, pattern text [, flags text]), splits string using aPOSIX regular expression as the delimiter.Following are the examples for all these functions-testdb=# SELECT REGEXP_MATCHES('ABCDEF' ,'A%C%%');regexp_matches----------------(0 rows)testdb=# SELECT REGEXP_REPLACE('Thomas', '.[mN]a.', 'M');regexp_replace----------------ThM(1 row)testdb=# SELECT REGEXP_SPLIT_TO_ARRAY('hello world', E's+');regexp_split_to_array-----------------------{hello,world}(1 row)testdb=# SELECT REGEXP_SPLIT_TO_TABLE('hello world', E's+');regexp_split_to_table-----------------------helloworld](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-199-2048.jpg&f=jpg&w=240)


![PostgreSQL195(1 row)testdb=# SELECT SUBSTRING('foobarbar' FROM 4);substring-----------barbar(1 row)testdb=# SELECT SUBSTRING('Quadratically',5,6);substring-----------ratica(1 row)TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)TRIM([remstr FROM] str)Returns the string str with all remstr prefixes or suffixes removed. If none of the specifiersBOTH, LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if notspecified, spaces are removed.testdb=# SELECT TRIM(' bar ');btrim-------bar(1 row)testdb=# SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx');ltrim--------barxxx(1 row)testdb=# SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx');btrim-------bar(1 row)](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-202-2048.jpg&f=jpg&w=240)


![PostgreSQL198This tutorial is going to use libpqxx library, which is the official C++ client API forPostgreSQL. The source code for libpqxx is available under the BSD license, so you're freeto download it, pass it on to others, change it, sell it, include it in your own code, andshare your changes with anyone you choose.InstallationThe the latest version of libpqxx is available to be downloaded from the link DownloadLibpqxx. So download the latest version and follow the following steps-wget http://pqxx.org/download/software/libpqxx/libpqxx-4.0.tar.gztar xvfz libpqxx-4.0.tar.gzcd libpqxx-4.0./configuremakemake installBefore you start using C/C++ PostgreSQL interface, find the pg_hba.conf file in yourPostgreSQL installation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can start/restart postgres server in case it is not running using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]44. PostgreSQL – C/C++ Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-205-2048.jpg&f=jpg&w=240)

![PostgreSQL2009N.exec(const std::string & sql)This public method from non-transactional object will be used to execute SQLstatement and returns a result object which is actually an interator holding allthe returned records.ConnectingToDatabaseThe following C code segment shows how to connect to an existing database running onlocal machine at port 5432. Here, I used backslash for line continuation.#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){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;}C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}}Now, let us compile and run the above program to connect to our database testdb, whichis already available in your schema and can be accessed using user postgres andpassword pass123.You can use the user ID and password based on your database setting. Remember to keepthe -lpqxx and -lpq in the given order! Otherwise, the linker will complain bitterly aboutthe missing functions with names starting with "PQ."](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-207-2048.jpg&f=jpg&w=240)
![PostgreSQL201$g++ test.cpp -lpqxx -lpq$./a.outOpened database successfully: testdbCreateaTableThe following C code segment will be used to create a table in previously created database-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create SQL statement */sql = "CREATE TABLE COMPANY(" "ID INT PRIMARY KEY NOT NULL," "NAME TEXT NOT NULL," "AGE INT NOT NULL," "ADDRESS CHAR(50)," "SALARY REAL );";/* Create a transactional object. */work W(C);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-208-2048.jpg&f=jpg&w=240)
![PostgreSQL202/* Execute SQL query */W.exec( sql );W.commit();cout << "Table created successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will create COMPANY table inyour testdb database and will display the following statements-Opened database successfully: testdbTable created successfullyINSERTOperationThe following C code segment shows how we can create records in our COMPANY tablecreated in above example-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;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;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-209-2048.jpg&f=jpg&w=240)

![PostgreSQL204SELECTOperationThe following C code segment shows how we can fetch and display records from ourCOMPANY table created in above example-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create SQL statement */sql = "SELECT * from COMPANY";/* Create a non-transactional object. */nontransaction N(C);/* Execute SQL query */result R( N.exec( sql ));/* List down all the records */for (result::const_iterator c = R.begin(); c != R.end(); ++c) {cout << "ID = " << c[0].as<int>() << endl;cout << "Name = " << c[1].as<string>() << endl;cout << "Age = " << c[2].as<int>() << endl;cout << "Address = " << c[3].as<string>() << endl;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-211-2048.jpg&f=jpg&w=240)
![PostgreSQL205cout << "Salary = " << c[4].as<float>() << endl;}cout << "Operation done successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will produce the followingresult-Opened database successfully: testdbID = 1Name = PaulAge = 32Address = CaliforniaSalary = 20000ID = 2Name = AllenAge = 25Address = TexasSalary = 15000ID = 3Name = TeddyAge = 23Address = NorwaySalary = 20000ID = 4Name = MarkAge = 25Address = Rich-MondSalary = 65000Operation done successfully](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-212-2048.jpg&f=jpg&w=240)
![PostgreSQL206UPDATEOperationThe following C code segment shows how we can use the UPDATE statement to updateany record and then fetch and display updated records from our COMPANY table-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create a transactional object. */work W(C);/* Create SQL UPDATE statement */sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1";/* Execute SQL query */W.exec( sql );W.commit();cout << "Records updated successfully" << endl;/* Create SQL SELECT statement */sql = "SELECT * from COMPANY";/* Create a non-transactional object. */nontransaction N(C);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-213-2048.jpg&f=jpg&w=240)
![PostgreSQL207/* Execute SQL query */result R( N.exec( sql ));/* List down all the records */for (result::const_iterator c = R.begin(); c != R.end(); ++c) {cout << "ID = " << c[0].as<int>() << endl;cout << "Name = " << c[1].as<string>() << endl;cout << "Age = " << c[2].as<int>() << endl;cout << "Address = " << c[3].as<string>() << endl;cout << "Salary = " << c[4].as<float>() << endl;}cout << "Operation done successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will produce the followingresult-Opened database successfully: testdbRecords updated successfullyID = 2Name = AllenAge = 25Address = TexasSalary = 15000ID = 3Name = TeddyAge = 23Address = NorwaySalary = 20000ID = 4Name = Mark](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-214-2048.jpg&f=jpg&w=240)
![PostgreSQL208Age = 25Address = Rich-MondSalary = 65000ID = 1Name = PaulAge = 32Address = CaliforniaSalary = 25000Operation done successfullyDELETEOperationThe following C code segment shows how we can use the DELETE statement to delete anyrecord and then fetch and display remaining records from our COMPANY table-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create a transactional object. */work W(C);/* Create SQL DELETE statement */sql = "DELETE from COMPANY where ID = 2";](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-215-2048.jpg&f=jpg&w=240)
![PostgreSQL209/* Execute SQL query */W.exec( sql );W.commit();cout << "Records deleted successfully" << endl;/* Create SQL SELECT statement */sql = "SELECT * from COMPANY";/* Create a non-transactional object. */nontransaction N(C);/* Execute SQL query */result R( N.exec( sql ));/* List down all the records */for (result::const_iterator c = R.begin(); c != R.end(); ++c) {cout << "ID = " << c[0].as<int>() << endl;cout << "Name = " << c[1].as<string>() << endl;cout << "Age = " << c[2].as<int>() << endl;cout << "Address = " << c[3].as<string>() << endl;cout << "Salary = " << c[4].as<float>() << endl;}cout << "Operation done successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will produce the followingresult-Opened database successfully: testdb](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-216-2048.jpg&f=jpg&w=240)

![PostgreSQL211InstallationBefore we start using PostgreSQL in our Java programs, we need to make sure that wehave PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial forJava installation on your machine. Now let us check how to set up PostgreSQL JDBC driver. Download the latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository. Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or youcan use it along with -classpath option as explained below in the examples.The following section assumes you have little knowledge about Java JDBC concepts. If youdo not have, then it is suggested to spent half and hour with JDBC Tutorial to becomecomfortable with concepts explained below.ConnectingToDatabaseThe following Java code shows how to connect to an existing database. If the databasedoes not exist, then it will be created and finally a database object will be returned.import java.sql.Connection;import java.sql.DriverManager;public class PostgreSQLJDBC {public static void main(String args[]) {Connection c = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","postgres", "123");} catch (Exception e) {e.printStackTrace();System.err.println(e.getClass().getName()+": "+e.getMessage());System.exit(0);}System.out.println("Opened database successfully");}}45. PostgreSQL – JAVA Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-218-2048.jpg&f=jpg&w=240)
![PostgreSQL212Before you compile and run above program, find pg_hba.conf file in your PostgreSQLinstallation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can start/restart the postgres server, in case it is not running, using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]Now, let us compile and run the above program to connect with testdb. Here, we areusing postgres as user ID and 123 as password to access the database. You can changethis as per your database configuration and setup. We are also assuming current versionof JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path.C:JavaPostgresIntegration>javac PostgreSQLJDBC.javaC:JavaPostgresIntegration>java -cp c:toolspostgresql-9.2-1002.jdbc3.jar;C:JavaPostgresIntegration PostgreSQLJDBCOpen database successfullyCreateaTableThe 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;public class PostgreSQLJDBC {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-219-2048.jpg&f=jpg&w=240)
![PostgreSQL213System.out.println("Opened database successfully");stmt = c.createStatement();String sql = "CREATE TABLE COMPANY " +"(ID INT PRIMARY KEY NOT NULL," +" NAME TEXT NOT NULL, " +" AGE INT NOT NULL, " +" ADDRESS CHAR(50), " +" SALARY REAL)";stmt.executeUpdate(sql);stmt.close();c.close();} catch ( Exception e ) {System.err.println( e.getClass().getName()+": "+ e.getMessage() );System.exit(0);}System.out.println("Table created successfully");}}When a program is compiled and executed, it will create the COMPANY tablein testdb database and will display the following two lines-Opened database successfullyTable created successfullyINSERTOperationThe following Java program shows how we can create records in our COMPANY tablecreated in above example-import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;public class PostgreSQLJDBC {public static void main(String args[]) {Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-220-2048.jpg&f=jpg&w=240)

![PostgreSQL215Records created successfullySELECTOperationThe following Java program shows how we can fetch and display records from ourCOMPANY table created in above example-import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");c.setAutoCommit(false);System.out.println("Opened database successfully");stmt = c.createStatement();ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );while ( rs.next() ) {int id = rs.getInt("id");String name = rs.getString("name");int age = rs.getInt("age");String address = rs.getString("address");float salary = rs.getFloat("salary");System.out.println( "ID = " + id );System.out.println( "NAME = " + name );System.out.println( "AGE = " + age );System.out.println( "ADDRESS = " + address );System.out.println( "SALARY = " + salary );System.out.println();}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-222-2048.jpg&f=jpg&w=240)

![PostgreSQL217UPDATEOperationThe following Java code shows how we can use the UPDATE statement to update anyrecord and then fetch and display updated records from our COMPANY table-import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");c.setAutoCommit(false);System.out.println("Opened database successfully");stmt = c.createStatement();String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";stmt.executeUpdate(sql);c.commit();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 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-224-2048.jpg&f=jpg&w=240)

![PostgreSQL219Operation done successfullyDELETEOperationThe following Java code shows how we can use the DELETE statement to delete any recordand then fetch and display remaining records from our COMPANY table-import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC6 {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");c.setAutoCommit(false);System.out.println("Opened database successfully");stmt = c.createStatement();String sql = "DELETE from COMPANY where ID=2;";stmt.executeUpdate(sql);c.commit();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 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-226-2048.jpg&f=jpg&w=240)


![PostgreSQL222InstallationThe PostgreSQL extension is enabled by default in the latest releases of PHP 5.3.x. It ispossible to disable it by using --without-pgsql at compile time. Still you can use yumcommand to install PHP -PostgreSQL interface-yum install php-pgsqlBefore you start using the PHP PostgreSQL interface, find the pg_hba.conf file in yourPostgreSQL installation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can the start/restart postgres server, in case it is not running, using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]Windows users must enable php_pgsql.dll in order to use this extension. This DLL isincluded with Windows distributions in the latest releases of PHP 5.3.xFor detailed installation instructions, kindly check our PHP tutorial and its official website.PHPInterfaceAPIsThe following are important PHP routines, which can suffice your requirement to work withPostgreSQL database from your PHP program. If you are looking for a more sophisticatedapplication, then you can look into the PHP official documentation.S.No. API & Description1resource pg_connect ( string $connection_string [, int $connect_type ] )This opens a connection to a PostgreSQL database specified by theconnection_string.If PGSQL_CONNECT_FORCE_NEW is passed as connect_type, then a newconnection is created in case of a second call to pg_connect() , even if theconnection_string is identical to an existing connection.46. PostgreSQL – PHP Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-229-2048.jpg&f=jpg&w=240)
![PostgreSQL2232bool pg_connection_reset ( resource $connection )This routine resets the connection. It is useful for error recovery. ReturnsTRUE on success or FALSE on failure.3int pg_connection_status ( resource $connection )This routine returns the status of the specified connection. ReturnsPGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.4string pg_dbname ([ resource $connection ] )This routine returns the name of the database that the given PostgreSQLconnection resource.5resource pg_prepare ([ resource $connection ], string $stmtname ,string $query )This submits a request to create a prepared statement with the givenparameters and waits for completion.6resource pg_execute ([ resource $connection ], string $stmtname ,array $params )This routine sends a request to execute a prepared statement with givenparameters and waits for the result.7resource pg_query ([ resource $connection ], string $query )This routine executes the query on the specified database connection.8array pg_fetch_row ( resource $result [, int $row ] )This routine fetches one row of data from the result associated with thespecified result resource.9array pg_fetch_all ( resource $result )This routine returns an array that contains all rows (records) in the resultresource.10int pg_affected_rows ( resource $result )This routine returns the number of rows affected by INSERT, UPDATE, andDELETE queries.11int pg_num_rows ( resource $result )](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-230-2048.jpg&f=jpg&w=240)
![PostgreSQL224This routine returns the number of rows in a PostgreSQL result resource forexample number of rows returned by SELECT statement.12bool pg_close ([ resource $connection ] )This routine closes the non-persistent connection to a PostgreSQL databaseassociated with the given connection resource.13string pg_last_error ([ resource $connection ] )This routine returns the last error message for a given connection.14string pg_escape_literal ([ resource $connection ], string $data )This routine escapes a literal for insertion into a text field.15string pg_escape_string ([ resource $connection ], string $data )This routine escapes a string for querying the database.ConnectingtoDatabaseThe following PHP code shows how to connect to an existing database on a local machineand 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";$db = pg_connect( "$host $port $dbname $credentials" );if(!$db){echo "Error : Unable to open databasen";} else {echo "Opened database successfullyn";}?>Now, let us run the above given program to open our database testdb; if the database issuccessfully opened, then it will give the following message-Opened database successfully](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-231-2048.jpg&f=jpg&w=240)


![PostgreSQL227When the above given program is executed, it will create the given records in COMPANYtable and will display the following two lines-Opened database successfullyRecords created successfullySELECTOperationThe following PHP program shows how we can fetch and display records from ourCOMPANY table created in above example-<?php$host = "host=127.0.0.1";$port = "port=5432";$dbname = "dbname=testdb";$credentials = "user=postgres password=pass123";$db = pg_connect( "$host $port $dbname $credentials" );if(!$db){echo "Error : Unable to open databasen";} else {echo "Opened database successfullyn";}$sql =<<<EOFSELECT * from COMPANY;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;}while($row = pg_fetch_row($ret)){echo "ID = ". $row[0] . "n";echo "NAME = ". $row[1] ."n";echo "ADDRESS = ". $row[2] ."n";echo "SALARY = ".$row[4] ."nn";}echo "Operation done successfullyn";](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-234-2048.jpg&f=jpg&w=240)

![PostgreSQL229$db = pg_connect( "$host $port $dbname $credentials" );if(!$db){echo "Error : Unable to open databasen";} else {echo "Opened database successfullyn";}$sql =<<<EOFUPDATE COMPANY set SALARY = 25000.00 where ID=1;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;} else {echo "Record updated successfullyn";}$sql =<<<EOFSELECT * from COMPANY;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;}while($row = pg_fetch_row($ret)){echo "ID = ". $row[0] . "n";echo "NAME = ". $row[1] ."n";echo "ADDRESS = ". $row[2] ."n";echo "SALARY = ".$row[4] ."nn";}echo "Operation done successfullyn";pg_close($db);?>When the above given program is executed, it will produce the following result-](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-236-2048.jpg&f=jpg&w=240)

![PostgreSQL231DELETE from COMPANY where ID=2;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;} else {echo "Record deleted successfullyn";}$sql =<<<EOFSELECT * from COMPANY;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;}while($row = pg_fetch_row($ret)){echo "ID = ". $row[0] . "n";echo "NAME = ". $row[1] ."n";echo "ADDRESS = ". $row[2] ."n";echo "SALARY = ".$row[4] ."nn";}echo "Operation done successfullyn";pg_close($db);?>When the above given program is executed, it will produce the following result-Opened database successfully](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-238-2048.jpg&f=jpg&w=240)

![PostgreSQL233InstallationThe PostgreSQL can be integrated with Perl using Perl DBI module, which is a databaseaccess module for the Perl programming language. It defines a set of methods, variablesand 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 installIf 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 installBefore you start using Perl PostgreSQL interface, find the pg_hba.conf file in yourPostgreSQL installation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can start/restart the postgres server, in case it is not running, using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]47. PostgreSQL – Perl Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-240-2048.jpg&f=jpg&w=240)




![PostgreSQL238my $userid = "postgres";my $password = "pass123";my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })or die $DBI::errstr;print "Opened database successfullyn";my $stmt = qq(SELECT id, name, address, salary from COMPANY;);my $sth = $dbh->prepare( $stmt );my $rv = $sth->execute() or die $DBI::errstr;if($rv < 0){print $DBI::errstr;}while(my @row = $sth->fetchrow_array()) {print "ID = ". $row[0] . "n";print "NAME = ". $row[1] ."n";print "ADDRESS = ". $row[2] ."n";print "SALARY = ". $row[3] ."nn";}print "Operation done successfullyn";$dbh->disconnect();When the above given program is executed, it will produce the following result-Opened database successfullyID = 1NAME = PaulADDRESS = CaliforniaSALARY = 20000ID = 2NAME = AllenADDRESS = TexasSALARY = 15000ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-245-2048.jpg&f=jpg&w=240)
![PostgreSQL239ID = 4NAME = MarkADDRESS = Rich-MondSALARY = 65000Operation done successfullyUPDATEOperationThe following Perl code shows how we can use the UPDATE statement to update any recordand then fetch and display updated records from our COMPANY table-#!/usr/bin/perluse 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 successfullyn";my $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);my $rv = $dbh->do($stmt) or die $DBI::errstr;if( $rv < 0 ){print $DBI::errstr;}else{print "Total number of rows updated : $rvn";}$stmt = qq(SELECT id, name, address, salary from COMPANY;);my $sth = $dbh->prepare( $stmt );$rv = $sth->execute() or die $DBI::errstr;if($rv < 0){print $DBI::errstr;}while(my @row = $sth->fetchrow_array()) {print "ID = ". $row[0] . "n";](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-246-2048.jpg&f=jpg&w=240)
![PostgreSQL240print "NAME = ". $row[1] ."n";print "ADDRESS = ". $row[2] ."n";print "SALARY = ". $row[3] ."nn";}print "Operation done successfullyn";$dbh->disconnect();When the above given program is executed, it will produce the following result-Opened database successfullyTotal number of rows updated : 1ID = 1NAME = PaulADDRESS = CaliforniaSALARY = 25000ID = 2NAME = AllenADDRESS = TexasSALARY = 15000ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000ID = 4NAME = MarkADDRESS = Rich-MondSALARY = 65000Operation done successfullyDELETEOperationThe following Perl code shows how we can use the DELETE statement to delete any recordand then fetch and display the remaining records from our COMPANY table-#!/usr/bin/perl](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-247-2048.jpg&f=jpg&w=240)
![PostgreSQL241use 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 successfullyn";my $stmt = qq(DELETE from COMPANY where ID=2;);my $rv = $dbh->do($stmt) or die $DBI::errstr;if( $rv < 0 ){print $DBI::errstr;}else{print "Total number of rows deleted : $rvn";}$stmt = qq(SELECT id, name, address, salary from COMPANY;);my $sth = $dbh->prepare( $stmt );$rv = $sth->execute() or die $DBI::errstr;if($rv < 0){print $DBI::errstr;}while(my @row = $sth->fetchrow_array()) {print "ID = ". $row[0] . "n";print "NAME = ". $row[1] ."n";print "ADDRESS = ". $row[2] ."n";print "SALARY = ". $row[3] ."nn";}print "Operation done successfullyn";$dbh->disconnect();When the above given program is executed, it will produce the following result-Opened database successfullyTotal number of rows deleted : 1](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-248-2048.jpg&f=jpg&w=240)

![PostgreSQL243InstallationThe PostgreSQL can be integrated with Python using psycopg2 module. sycopg2 is aPostgreSQL database adapter for the Python programming language. psycopg2 waswritten with the aim of being very small and fast, and stable as a rock. You do not needto install this module separately because it is shipped, by default, along with Pythonversion 2.5.x onwards.If you do not have it installed on your machine then you can use yum command to installit as follows-$yum install python-psycopg2To use psycopg2 module, you must first create a Connection object that represents thedatabase and then optionally you can create cursor object which will help you in executingall the SQL statements.Pythonpsycopg2moduleAPIsFollowing are important psycopg2 module routines, which can suffice your requirement towork with PostgreSQL database from your Python program. If you are looking for a moresophisticated application, then you can look into Python psycopg2 module's officialdocumentation.S. No. API & Description1psycopg2.connect(database="testdb", user="postgres",password="cohondob", host="127.0.0.1", port="5432")This API opens a connection to the PostgreSQL database. If database isopened successfully, it returns a connection object.2connection.cursor()This routine creates a cursor which will be used throughout of your databaseprogramming with Python.3cursor.execute(sql [, optional parameters])This routine executes an SQL statement. The SQL statement may beparameterized (i.e., placeholders instead of SQL literals). The psycopg2module supports placeholder using %s signFor example:cursor.execute("insert into people values (%s, %s)", (who,age))48. PostgreSQL – Python Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-250-2048.jpg&f=jpg&w=240)
![PostgreSQL2444curosr.executemany(sql, seq_of_parameters)This routine executes an SQL command against all parameter sequences ormappings found in the sequence sql.5curosr.callproc(procname[, parameters])This routine executes a stored database procedure with the given name. Thesequence of parameters must contain one entry for each argument that theprocedure expects.6cursor.rowcountThis read-only attribute which returns the total number of database rows thathave been modified, inserted, or deleted by the last last execute*().7connection.commit()This method commits the current transaction. If you don't call this method,anything you did since the last call to commit() is not visible from otherdatabase connections.8connection.rollback()This method rolls back any changes to the database since the last call tocommit().9connection.close()This method closes the database connection. Note that this does notautomatically call commit(). If you just close your database connectionwithout calling commit() first, your changes will be lost!10cursor.fetchone()This method fetches the next row of a query result set, returning a singlesequence, or None when no more data is available.11cursor.fetchmany([size=cursor.arraysize])This routine fetches the next set of rows of a query result, returning a list. Anempty list is returned when no more rows are available. The method tries tofetch as many rows as indicated by the size parameter.12cursor.fetchall()This routine fetches all (remaining) rows of a query result, returning a list. Anempty list is returned when no rows are available.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-251-2048.jpg&f=jpg&w=240)


![PostgreSQL247SELECTOperationThe following Python program shows how we can fetch and display records from ourCOMPANY table created in the above example-#!/usr/bin/pythonimport psycopg2conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",host="127.0.0.1", port="5432")print "Opened database successfully"cur = conn.cursor()cur.execute("SELECT id, name, address, salary from COMPANY")rows = cur.fetchall()for row in rows:print "ID = ", row[0]print "NAME = ", row[1]print "ADDRESS = ", row[2]print "SALARY = ", row[3], "n"print "Operation done successfully";conn.close()When the above given program is executed, it will produce the following result-Opened database successfullyID = 1NAME = PaulADDRESS = CaliforniaSALARY = 20000.0ID = 2NAME = AllenADDRESS = TexasSALARY = 15000.0ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000.0ID = 4NAME = MarkADDRESS = Rich-Mond](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-254-2048.jpg&f=jpg&w=240)
![PostgreSQL248SALARY = 65000.0Operation done successfullyUPDATEOperationThe following Python code shows how we can use the UPDATE statement to update anyrecord and then fetch and display updated records from our COMPANY table-#!/usr/bin/pythonimport psycopg2conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",host="127.0.0.1", port="5432")print "Opened database successfully"cur = conn.cursor()cur.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")conn.commitprint "Total number of rows updated :", cur.rowcountcur.execute("SELECT id, name, address, salary from COMPANY")rows = cur.fetchall()for row in rows:print "ID = ", row[0]print "NAME = ", row[1]print "ADDRESS = ", row[2]print "SALARY = ", row[3], "n"print "Operation done successfully";conn.close()When the above given program is executed, it will produce the following result-Opened database successfullyTotal number of rows updated : 1ID = 1NAME = PaulADDRESS = CaliforniaSALARY = 25000.0ID = 2NAME = Allen](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-255-2048.jpg&f=jpg&w=240)
![PostgreSQL249ADDRESS = TexasSALARY = 15000.0ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000.0ID = 4NAME = MarkADDRESS = Rich-MondSALARY = 65000.0Operation done successfullyDELETEOperationThe following Python code shows how we can use the DELETE statement to delete anyrecord and then fetch and display the remaining records from our COMPANY table-#!/usr/bin/pythonimport psycopg2conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",host="127.0.0.1", port="5432")print "Opened database successfully"cur = conn.cursor()cur.execute("DELETE from COMPANY where ID=2;")conn.commitprint "Total number of rows deleted :", cur.rowcountcur.execute("SELECT id, name, address, salary from COMPANY")rows = cur.fetchall()for row in rows:print "ID = ", row[0]print "NAME = ", row[1]print "ADDRESS = ", row[2]print "SALARY = ", row[3], "n"](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-256-2048.jpg&f=jpg&w=240)


PostgreSQL is an open source relational database management system. It has over 15 years of active development and supports most operating systems. The tutorial provides instructions on installing PostgreSQL on Linux, Windows, and Mac operating systems. It also gives an overview of PostgreSQL's features and procedural language support.









![PostgreSQL3To start understanding the PostgreSQL basics, first let us install the PostgreSQL. Thischapter explains about installing the PostgreSQL on Linux, Windows and Mac OS platforms.InstallingPostgreSQLonLinux/UnixFollow the given steps to install PostgreSQL on your Linux machine. Make sure you arelogged in as root before you proceed for the installation. Pick the version number of PostgreSQL you want and, as exactly as possible, theplatform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-linux-x64.run for my 64-bit CentOS-6machine. Now, let us execute it as follows:[root@host]# chmod +x postgresql-9.2.4-1-linux-x64.run[root@host]# ./postgresql-9.2.4-1-linux-x64.run------------------------------------------------------------------------Welcome to the PostgreSQL Setup Wizard.------------------------------------------------------------------------Please specify the directory where PostgreSQL will be installed.Installation Directory [/opt/PostgreSQL/9.2]: Once you launch the installer, it asks you a few basic questions like location of theinstallation, password of the user who will use database, port number, etc. So keepall of them at their default values except password, which you can provide passwordas per your choice. It will install PostgreSQL at your Linux machine and will displaythe following message:Please wait while Setup installs PostgreSQL on your computer.Installing0% ______________ 50% ______________ 100%#########################################-----------------------------------------------------------------------Setup has finished installing PostgreSQL on your computer. Follow the following post-installation steps to create your database:[root@host]# su - postgresPassword:2. PostgreSQL – Environment Setup](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-10-2048.jpg&f=jpg&w=240)
![PostgreSQL4bash-4.1$ createdb testdbbash-4.1$ psql testdbpsql (8.4.13, server 9.2.4)test=# You can start/restart postgres server in case it is not running, using the followingcommand:[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ] If your installation was correct, you will have PotsgreSQL prompt test=# as shownabove.InstallingPostgreSQLonWindowsFollow the given steps to install PostgreSQL on your Windows machine. Make sure youhave turned Third Party Antivirus off while installing. Pick the version number of PostgreSQL you want and, as exactly as possible, theplatform you want from EnterpriseDB I downloaded postgresql-9.2.4-1-windows.exe for my Windows PC running in 32-bit mode, so let us run postgresql-9.2.4-1-windows.exe as administrator toinstall PostgreSQL. Select the location where you want to install it. By default, it isinstalled within Program Files folder.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-11-2048.jpg&f=jpg&w=240)






![PostgreSQL11This chapter provides a list of the PostgreSQL SQL commands, followed by the precisesyntax rules for each of these commands. This set of commands is taken from the psqlcommand-line tool. Now that you have Postgres installed, open the psql as:Program Files > PostgreSQL 9.2 > SQL Shell(psql).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:postgres-# help <command_name>TheSQLStatementAn SQL statement is comprised of tokens where each token can represent either akeyword, identifier, quoted identifier, constant, or special character symbol. The tablegiven below uses a simple SELECT statement to illustrate a basic, but complete, SQLstatement and its components.SELECT id, name FROM statesToken Type Keyword Identifiers Keyword IdentifierDescription Command Id and name columns Clause Table namePostgreSQLSQLcommandsABORTAbort the current transaction.ABORT [ WORK | TRANSACTION ]ALTER AGGREGATEChange the definition of an aggregate function.ALTER AGGREGATE name ( type ) RENAME TO new_nameALTER AGGREGATE name ( type ) OWNER TO new_owner3. PostgreSQL – Syntax](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-18-2048.jpg&f=jpg&w=240)
![PostgreSQL12ALTER CONVERSIONChange the definition of a conversion.ALTER CONVERSION name RENAME TO new_nameALTER CONVERSION name OWNER TO new_ownerALTER DATABASEChange a database specific parameter.ALTER DATABASE name SET parameter { TO | = } { value | DEFAULT }ALTER DATABASE name RESET parameterALTER DATABASE name RENAME TO new_nameALTER DATABASE name OWNER TO new_ownerALTER DOMAINChange the definition of a domain specific parameter.ALTER DOMAIN name { SET DEFAULT expression | DROP DEFAULT }ALTER DOMAIN name { SET | DROP } NOT NULLALTER DOMAIN name ADD domain_constraintALTER DOMAIN name DROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ]ALTER DOMAIN name OWNER TO new_ownerALTER FUNCTIONChange the definition of a function.ALTER FUNCTION name ( [ type [, ...] ] ) RENAME TO new_nameALTER FUNCTION name ( [ type [, ...] ] ) OWNER TO new_ownerALTER GROUPChange a user group.ALTER GROUP groupname ADD USER username [, ... ]ALTER GROUP groupname DROP USER username [, ... ]ALTER GROUP groupname RENAME TO new_name](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-19-2048.jpg&f=jpg&w=240)
![PostgreSQL13ALTER INDEXChange the definition of an index.ALTER INDEX name OWNER TO new_ownerALTER INDEX name SET TABLESPACE indexspace_nameALTER INDEX name RENAME TO new_nameALTER LANGUAGEChange the definition of a procedural language.ALTER LANGUAGE name RENAME TO new_nameALTER OPERATORChange the definition of an operator.ALTER OPERATOR name ( { lefttype | NONE } , { righttype | NONE } )OWNER TO new_ownerALTER OPERATOR CLASSChange the definition of an operator class.ALTER OPERATOR CLASS name USING index_method RENAME TO new_nameALTER OPERATOR CLASS name USING index_method OWNER TO new_ownerALTER SCHEMAChange the definition of a schema.ALTER SCHEMA name RENAME TO new_nameALTER SCHEMA name OWNER TO new_ownerALTER SEQUENCEChange the definition of a sequence generator.ALTER SEQUENCE name [ INCREMENT [ BY ] increment ][ MINVALUE minvalue | NO MINVALUE ][ MAXVALUE maxvalue | NO MAXVALUE ][ RESTART [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-20-2048.jpg&f=jpg&w=240)
![PostgreSQL14ALTER TABLEChange the definition of a table.ALTER TABLE [ ONLY ] name [ * ]action [, ... ]ALTER TABLE [ ONLY ] name [ * ]RENAME [ COLUMN ] column TO new_columnALTER TABLE nameRENAME TO new_nameWhere action is one of the following lines:ADD [ COLUMN ] column_type [ column_constraint [ ... ] ]DROP [ COLUMN ] column [ RESTRICT | CASCADE ]ALTER [ COLUMN ] column TYPE type [ USING expression ]ALTER [ COLUMN ] column SET DEFAULT expressionALTER [ COLUMN ] column DROP DEFAULTALTER [ COLUMN ] column { SET | DROP } NOT NULLALTER [ COLUMN ] column SET STATISTICS integerALTER [ COLUMN ] column SET STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN }ADD table_constraintDROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ]CLUSTER ON index_nameSET WITHOUT CLUSTERSET WITHOUT OIDSOWNER TO new_ownerSET TABLESPACE tablespace_nameALTER TABLESPACEChange the definition of a tablespace.ALTER TABLESPACE name RENAME TO new_nameALTER TABLESPACE name OWNER TO new_ownerALTER TRIGGERChange the definition of a trigger.ALTER TRIGGER name ON table RENAME TO new_name](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-21-2048.jpg&f=jpg&w=240)
![PostgreSQL15ALTER TYPEChange the definition of a type.ALTER TYPE name OWNER TO new_ownerALTER USERChange a database user account.ALTER USER name [ [ WITH ] option [ ... ] ]ALTER USER name RENAME TO new_nameALTER USER name SET parameter { TO | = } { value | DEFAULT }ALTER USER name RESET parameterWhere option can be:[ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'| CREATEDB | NOCREATEDB| CREATEUSER | NOCREATEUSER| VALID UNTIL 'abstime'ANALYZECollect statistics about a database.ANALYZE [ VERBOSE ] [ table [ (column [, ...] ) ] ]BEGINStart a transaction block.BEGIN [ WORK | TRANSACTION ] [ transaction_mode [, ...] ]Where transaction_mode is one of:ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED| READ UNCOMMITTED }READ WRITE | READ ONLYCHECKPOINTForce a transaction log checkpoint.CHECKPOINT](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-22-2048.jpg&f=jpg&w=240)
![PostgreSQL16CLOSEClose a cursor.CLOSE nameCLUSTERCluster a table according to an index.CLUSTER index_name ON table_nameCLUSTER table_nameCLUSTERCOMMENTDefine or change the comment of an object.COMMENT ON{TABLE object_name |COLUMN table_name.column_name |AGGREGATE agg_name (agg_type) |CAST (source_type AS target_type) |CONSTRAINT constraint_name ON table_name |CONVERSION object_name |DATABASE object_name |DOMAIN object_name |FUNCTION func_name (arg1_type, arg2_type, ...) |INDEX object_name |LARGE OBJECT large_object_oid |OPERATOR op (left_operand_type, right_operand_type) |OPERATOR CLASS object_name USING index_method |[ PROCEDURAL ] LANGUAGE object_name |RULE rule_name ON table_name |SCHEMA object_name |SEQUENCE object_name |TRIGGER trigger_name ON table_name |TYPE object_name |VIEW object_name} IS 'text'](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-23-2048.jpg&f=jpg&w=240)
![PostgreSQL17COMMITCommit the current transaction.COMMIT [ WORK | TRANSACTION ]COPYCopy data between a file and a table.COPY table_name [ ( column [, ...] ) ]FROM { 'filename' | STDIN }[ [ WITH ][ BINARY ][ OIDS ][ DELIMITER [ AS ] 'delimiter' ][ NULL [ AS ] 'null string' ][ CSV [ QUOTE [ AS ] 'quote' ][ 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 [, ...] ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-24-2048.jpg&f=jpg&w=240)
![PostgreSQL18CREATE AGGREGATEDefine a new aggregate function.CREATE AGGREGATE name (BASETYPE = input_data_type,SFUNC = sfunc,STYPE = state_data_type[ , FINALFUNC = ffunc ][ , INITCOND = initial_condition ])CREATE CASTDefine a new cast.CREATE CAST (source_type AS target_type)WITH FUNCTION func_name (arg_types)[ AS ASSIGNMENT | AS IMPLICIT ]CREATE CAST (source_type AS target_type)WITHOUT FUNCTION[ AS ASSIGNMENT | AS IMPLICIT ]CREATE CONSTRAINT TRIGGERDefine a new constraint trigger.CREATE CONSTRAINT TRIGGER nameAFTER events ONtable_name constraint attributesFOR EACH ROW EXECUTE PROCEDURE func_name ( args )CREATE CONVERSIONDefine a new conversion.CREATE [DEFAULT] CONVERSION nameFOR source_encoding TO dest_encoding FROM func_nameCREATE DATABASE](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-25-2048.jpg&f=jpg&w=240)
![PostgreSQL19Create a new database.CREATE DATABASE name[ [ WITH ] [ OWNER [=] db_owner ][ TEMPLATE [=] template ][ ENCODING [=] encoding ][ TABLESPACE [=] tablespace ] ]CREATE DOMAINDefine a new domain.CREATE DOMAIN name [AS] data_type[ DEFAULT expression ][ constraint [ ... ] ]Where constraint is:[ CONSTRAINT constraint_name ]{ NOT NULL | NULL | CHECK (expression) }CREATE FUNCTIONDefine a new function.CREATE [ OR REPLACE ] FUNCTION name ( [ [ arg_name ] arg_type [, ...] ] )RETURNS ret_type{ LANGUAGE lang_name| IMMUTABLE | STABLE | VOLATILE| CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT| [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER| AS 'definition'| AS 'obj_file', 'link_symbol'} ...[ WITH ( attribute [, ...] ) ]CREATE GROUPDefine a new user group.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-26-2048.jpg&f=jpg&w=240)
![PostgreSQL20CREATE GROUP name [ [ WITH ] option [ ... ] ]Where option can be:SYSID gid| USER username [, ...]CREATE INDEXDefine a new index.CREATE [ UNIQUE ] INDEX name ON table [ USING method ]( { column | ( expression ) } [ opclass ] [, ...] )[ TABLESPACE tablespace ][ WHERE predicate ]CREATE LANGUAGEDefine a new procedural language.CREATE [ TRUSTED ] [ PROCEDURAL ] LANGUAGE nameHANDLER call_handler [ VALIDATOR val_function ]CREATE OPERATORDefine a new operator.CREATE OPERATOR name (PROCEDURE = func_name[, LEFTARG = left_type ] [, RIGHTARG = right_type ][, COMMUTATOR = com_op ] [, NEGATOR = neg_op ][, RESTRICT = res_proc ] [, JOIN = join_proc ][, HASHES ] [, MERGES ][, SORT1 = left_sort_op ] [, SORT2 = right_sort_op ][, LTCMP = less_than_op ] [, GTCMP = greater_than_op ])CREATE OPERATOR CLASSDefine a new operator class.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-27-2048.jpg&f=jpg&w=240)
![PostgreSQL21CREATE OPERATOR CLASS name [ DEFAULT ] FOR TYPE data_typeUSING index_method AS{ OPERATOR strategy_number operator_name [ ( op_type, op_type ) ] [ RECHECK ]| FUNCTION support_number func_name ( argument_type [, ...] )| STORAGE storage_type} [, ... ]CREATE RULEDefine a new rewrite rule.CREATE [ OR REPLACE ] RULE name AS ON eventTO table [ WHERE condition ]DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }CREATE SCHEMADefine a new schema.CREATE SCHEMA schema_name[ AUTHORIZATION username ] [ schema_element [ ... ] ]CREATE SCHEMA AUTHORIZATION username[ schema_element [ ... ] ]CREATE SEQUENCEDefine a new sequence generator.CREATE [ TEMPORARY | TEMP ] SEQUENCE name[ INCREMENT [ BY ] increment ][ MINVALUE minvalue | NO MINVALUE ][ MAXVALUE maxvalue | NO MAXVALUE ][ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]CREATE TABLEDefine a new table.CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name ({ column_name data_type [ DEFAULT default_expr ] [ column_constraint [ ... ] ]| table_constraint| LIKE parent_table [ { INCLUDING | EXCLUDING } DEFAULTS ] } [, ... ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-28-2048.jpg&f=jpg&w=240)
![PostgreSQL22)[ INHERITS ( parent_table [, ... ] ) ][ WITH OIDS | WITHOUT OIDS ][ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ][ TABLESPACE tablespace ]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 ]CREATE TABLE ASDefine a new table from the results of a query.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-29-2048.jpg&f=jpg&w=240)
![PostgreSQL23CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name[ (column_name [, ...] ) ] [ [ WITH | WITHOUT ] OIDS ]AS queryCREATE TABLESPACEDefine a new tablespace.CREATE TABLESPACE tablespace_name [ OWNER username ] LOCATION 'directory'CREATE TRIGGERDefine a new trigger.CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }ON table [ FOR [ EACH ] { ROW | STATEMENT } ]EXECUTE PROCEDURE func_name ( arguments )CREATE TYPEDefine a new data type.CREATE TYPE name AS( attribute_name data_type [, ... ] )CREATE TYPE name (INPUT = input_function,OUTPUT = output_function[ , RECEIVE = receive_function ][ , SEND = send_function ][ , ANALYZE = analyze_function ][ , INTERNALLENGTH = { internal_length | VARIABLE } ][ , PASSEDBYVALUE ][ , ALIGNMENT = alignment ][ , STORAGE = storage ][ , DEFAULT = default ][ , ELEMENT = element ][ , DELIMITER = delimiter ])CREATE USERDefine a new database user account.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-30-2048.jpg&f=jpg&w=240)
![PostgreSQL24CREATE USER name [ [ WITH ] option [ ... ] ]Where option can be:SYSID uid| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'| CREATEDB | NOCREATEDB| CREATEUSER | NOCREATEUSER| IN GROUP group_name [, ...]| VALID UNTIL 'abs_time'CREATE VIEWDefine a new view.CREATE [ OR REPLACE ] VIEW name [ ( column_name [, ...] ) ] AS queryDEALLOCATEDeallocate a prepared statement.DEALLOCATE [ PREPARE ] plan_nameDECLAREDefine a cursor.DECLARE name [ BINARY ] [ INSENSITIVE ] [ [ NO ] SCROLL ]CURSOR [ { WITH | WITHOUT } HOLD ] FOR query[ FOR { READ ONLY | UPDATE [ OF column [, ...] ] } ]DELETEDelete rows of a table.DELETE FROM [ ONLY ] table [ WHERE condition ]DROP AGGREGATERemove an aggregate function.DROP AGGREGATE name ( type ) [ CASCADE | RESTRICT ]DROP CASTRemove a cast.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-31-2048.jpg&f=jpg&w=240)
![PostgreSQL25DROP CAST (source_type AS target_type) [ CASCADE | RESTRICT ]DROP CONVERSIONRemove a conversion.DROP CONVERSION name [ CASCADE | RESTRICT ]DROP DATABASERemove a database.DROP DATABASE nameDROP DOMAINRemove a domain.DROP DOMAIN name [, ...] [ CASCADE | RESTRICT ]DROP FUNCTIONRemove a function.DROP FUNCTION name ( [ type [, ...] ] ) [ CASCADE | RESTRICT ]DROP GROUPRemove a user group.DROP GROUP nameDROP INDEXRemove an index.DROP INDEX name [, ...] [ CASCADE | RESTRICT ]DROP LANGUAGERemove a procedural language.DROP [ PROCEDURAL ] LANGUAGE name [ CASCADE | RESTRICT ]DROP OPERATORRemove an operator.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-32-2048.jpg&f=jpg&w=240)
![PostgreSQL26DROP OPERATOR name ( { left_type | NONE } , { right_type | NONE } )[ CASCADE | RESTRICT ]DROP OPERATOR CLASSRemove an operator class.DROP OPERATOR CLASS name USING index_method [ CASCADE | RESTRICT ]DROP RULERemove a rewrite rule.DROP RULE name ON relation [ CASCADE | RESTRICT ]DROP SCHEMARemove a schema.DROP SCHEMA name [, ...] [ CASCADE | RESTRICT ]DROP SEQUENCERemove a sequence.DROP SEQUENCE name [, ...] [ CASCADE | RESTRICT ]DROP TABLERemove a table.DROP TABLE name [, ...] [ CASCADE | RESTRICT ]DROP TABLESPACERemove a tablespace.DROP TABLESPACE tablespace_nameDROP TRIGGERRemove a trigger.DROP TRIGGER name ON table [ CASCADE | RESTRICT ]DROP TYPERemove a data type.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-33-2048.jpg&f=jpg&w=240)
![PostgreSQL27DROP TYPE name [, ...] [ CASCADE | RESTRICT ]DROP USERRemove a database user account.DROP USER nameDROP VIEWRemove a view.DROP VIEW name [, ...] [ CASCADE | RESTRICT ]ENDCommit the current transaction.END [ WORK | TRANSACTION ]EXECUTEExecute a prepared statement.EXECUTE plan_name [ (parameter [, ...] ) ]EXPLAINShow the execution plan of a statement.EXPLAIN [ ANALYZE ] [ VERBOSE ] statementFETCHRetrieve rows from a query using a cursor.FETCH [ direction { FROM | IN } ] cursor_nameWhere direction can be empty or one of:NEXTPRIORFIRSTLASTABSOLUTE countRELATIVE countcountALLFORWARDFORWARD count](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-34-2048.jpg&f=jpg&w=240)
![PostgreSQL28FORWARD ALLBACKWARDBACKWARD countBACKWARD ALLGRANTDefine access privileges.GRANT { { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }[,...] | ALL [ PRIVILEGES ] }ON [ TABLE ] table_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { { CREATE | TEMPORARY | TEMP } [,...] | ALL [ PRIVILEGES ] }ON DATABASE db_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { CREATE | ALL [ PRIVILEGES ] }ON TABLESPACE tablespace_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { EXECUTE | ALL [ PRIVILEGES ] }ON FUNCTION func_name ([type, ...]) [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { USAGE | ALL [ PRIVILEGES ] }ON LANGUAGE lang_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]GRANT { { CREATE | USAGE } [,...] | ALL [ PRIVILEGES ] }ON SCHEMA schema_name [, ...]TO { username | GROUP group_name | PUBLIC } [, ...] [ WITH GRANT OPTION ]INSERTCreate new rows in a table.INSERT INTO table [ ( column [, ...] ) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-35-2048.jpg&f=jpg&w=240)
![PostgreSQL29{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) | query }LISTENListen for a notification.LISTEN nameLOADLoad or reload a shared library file.LOAD 'filename'LOCKLock a table.LOCK [ TABLE ] name [, ...] [ IN lock_mode MODE ] [ NOWAIT ]Where lock_mode is one of:ACCESS SHARE | ROW SHARE | ROW EXCLUSIVE | SHARE UPDATE EXCLUSIVE| SHARE | SHARE ROW EXCLUSIVE | EXCLUSIVE | ACCESS EXCLUSIVEMOVEPosition a cursor.MOVE [ direction { FROM | IN } ] cursor_nameNOTIFYGenerate a notification.NOTIFY namePREPAREPrepare a statement for execution.PREPARE plan_name [ (data_type [, ...] ) ] AS statementREINDEXRebuild indexes.REINDEX { DATABASE | TABLE | INDEX } name [ FORCE ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-36-2048.jpg&f=jpg&w=240)
![PostgreSQL30RELEASE SAVEPOINTDestroy a previously defined savepoint.RELEASE [ SAVEPOINT ] savepoint_nameRESETRestore the value of a runtime parameter to the default value.RESET nameRESET ALLREVOKERemove access privileges.REVOKE [ GRANT OPTION FOR ]{ { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }[,...] | ALL [ PRIVILEGES ] }ON [ TABLE ] table_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ { CREATE | TEMPORARY | TEMP } [,...] | ALL [ PRIVILEGES ] }ON DATABASE db_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ CREATE | ALL [ PRIVILEGES ] }ON TABLESPACE tablespace_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ EXECUTE | ALL [ PRIVILEGES ] }ON FUNCTION func_name ([type, ...]) [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ USAGE | ALL [ PRIVILEGES ] }ON LANGUAGE lang_name [, ...]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-37-2048.jpg&f=jpg&w=240)
![PostgreSQL31FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]REVOKE [ GRANT OPTION FOR ]{ { CREATE | USAGE } [,...] | ALL [ PRIVILEGES ] }ON SCHEMA schema_name [, ...]FROM { username | GROUP group_name | PUBLIC } [, ...][ CASCADE | RESTRICT ]ROLLBACKAbort the current transaction.ROLLBACK [ WORK | TRANSACTION ]ROLLBACK TO SAVEPOINTRoll back to a savepoint.ROLLBACK [ WORK | TRANSACTION ] TO [ SAVEPOINT ] savepoint_nameSAVEPOINTDefine a new savepoint within the current transaction.SAVEPOINT savepoint_nameSELECTRetrieve rows from a table or view.SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]* | expression [ AS output_name ] [, ...][ FROM from_item [, ...] ][ WHERE condition ][ GROUP BY expression [, ...] ][ HAVING condition [, ...] ][ { UNION | INTERSECT | EXCEPT } [ ALL ] select ][ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ][ LIMIT { count | ALL } ][ OFFSET start ][ FOR UPDATE [ OF table_name [, ...] ] ]Where from_item can be one of:[ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]( select ) [ AS ] alias [ ( column_alias [, ...] ) ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-38-2048.jpg&f=jpg&w=240)
![PostgreSQL32function_name ( [ argument [, ...] ] )[ AS ] alias [ ( column_alias [, ...] | column_definition [, ...] ) ]function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )from_item [ NATURAL ] join_type from_item[ ON join_condition | USING ( join_column [, ...] ) ]SELECT INTODefine a new table from the results of a query.SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]* | expression [ AS output_name ] [, ...]INTO [ TEMPORARY | TEMP ] [ TABLE ] new_table[ FROM from_item [, ...] ][ WHERE condition ][ GROUP BY expression [, ...] ][ HAVING condition [, ...] ][ { UNION | INTERSECT | EXCEPT } [ ALL ] select ][ ORDER BY expression [ ASC | DESC | USING operator ] [, ...] ][ LIMIT { count | ALL } ][ OFFSET start ][ FOR UPDATE [ OF table_name [, ...] ] ]SETChange a runtime parameter.SET [ SESSION | LOCAL ] name { TO | = } { value | 'value' | DEFAULT }SET [ SESSION | LOCAL ] TIME ZONE { time_zone | LOCAL | DEFAULT }SET CONSTRAINTSSet constraint checking modes for the current transaction.SET CONSTRAINTS { ALL | name [, ...] } { DEFERRED | IMMEDIATE }SET SESSION AUTHORIZATION](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-39-2048.jpg&f=jpg&w=240)
![PostgreSQL33Set the session user identifier and the current user identifier of the current session.SET [ SESSION | LOCAL ] SESSION AUTHORIZATION usernameSET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULTRESET SESSION AUTHORIZATIONSET TRANSACTIONSet the characteristics of the current transaction.SET TRANSACTION transaction_mode [, ...]SET SESSION CHARACTERISTICS AS TRANSACTION transaction_mode [, ...]Where transaction_mode is one of:ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED| READ UNCOMMITTED }READ WRITE | READ ONLYSHOWShow the value of a runtime parameter.SHOW nameSHOW ALLSTART TRANSACTIONStart a transaction block.START TRANSACTION [ transaction_mode [, ...] ]Where transaction_mode is one of:ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED| READ UNCOMMITTED }READ WRITE | READ ONLYTRUNCATEEmpty a table.TRUNCATE [ TABLE ] nameUNLISTEN](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-40-2048.jpg&f=jpg&w=240)
![PostgreSQL34Stop listening for a notification.UNLISTEN { name | * }UPDATEUpdate rows of a table.UPDATE [ ONLY ] table SET column = { expression | DEFAULT } [, ...][ FROM from_list ][ WHERE condition ]VACUUMGarbage-collect and optionally analyze a database.VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ table ]VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-41-2048.jpg&f=jpg&w=240)


![PostgreSQL37BinaryDataTypesThe bytea data type allows storage of binary strings as in the table given below.Name Storage Size Descriptionbytea 1 or 4 bytes plus the actual binary string variable-length binary stringDate/TimeTypesPostgreSQL supports a full set of SQL date and time types, as shown in table below. Datesare counted according to the Gregorian calendar. Here, all the types have resolution of 1microsecond / 14 digits except date type, whose resolution is day.Name Storage Size Description Low Value High Valuetimestamp[(p)] [withouttime zone ]8 bytesboth date andtime (no timezone)4713 BC 294276 ADtimestamp[(p) ] withtime zone8 bytesboth date andtime, with timezone4713 BC 294276 ADdate 4 bytesdate (no timeof day)4713 BC 5874897 ADtime [ (p)] [without timezone ]8 bytestime of day (nodate)00:00:00 24:00:00time [ (p)]with timezone12 bytestimes of dayonly, with timezone00:00:00+1459 24:00:00-1459interval[fields ] [(p) ]12 bytes time interval-178000000years178000000 yearsBooleanTypePostgreSQL provides the standard SQL type Boolean. The Boolean data type can have thestates- true, false, and a third state, unknown, which is represented by the SQL null value.Name Storage Size Descriptionboolean 1 byte state of true or false](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-44-2048.jpg&f=jpg&w=240)
![PostgreSQL38EnumeratedTypeEnumerated (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');Enumerated, once created, can be used like any other types.GeometricTypeGeometric data types represent two-dimensional spatial objects. The most fundamentaltype, the point, forms the basis for all of the other types.Name Storage Size Representation Descriptionpoint 16 bytes Point on a plane (x,y)line 32 bytesInfinite line (not fullyimplemented)((x1,y1),(x2,y2))lseg 32 bytes Finite line segment ((x1,y1),(x2,y2))box 32 bytes Rectangular box ((x1,y1),(x2,y2))path 16+16n bytes Closed path (similar to polygon) ((x1,y1),...)path 16+16n bytes Open path [(x1,y1),...]polygon 40+16n Polygon (similar to closed path) ((x1,y1),...)circle 24 bytes Circle<(x,y),r> (center pointand radius)NetworkAddressTypePostgreSQL offers data types to store IPv4, IPv6, and MAC addresses. It is better to usethese types instead of plain text types to store network addresses because these typesoffer input error checking and specialized operators and functions.Name Storage Size Descriptioncidr 7 or 19 bytes IPv4 and IPv6 networksinet 7 or 19 bytes IPv4 and IPv6 hosts and networks](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-45-2048.jpg&f=jpg&w=240)

![PostgreSQL40JSONTypeThe json data type can be used to store JSON (JavaScript Object Notation) data. Suchdata can also be stored as text, but the json data type has the advantage of checking thateach 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-Example Example Resultarray_to_json('{{1,5},{99,100}}'::int[]) [[1,5],[99,100]]row_to_json(row(1,'foo')) {"f1":1,"f2":"foo"}ArrayTypePostgreSQL gives the opportunity to define a column of a table as a variable lengthmultidimensional array. Arrays of any built-in or user-defined base type, enum type, orcomposite type can be created.Declaration of ArraysArray type can be declared as-CREATE TABLE monthly_savings (name text,saving_per_quarter integer[],scheme text[][]);or by using the keyword "ARRAY" as-CREATE TABLE monthly_savings (name text,saving_per_quarter integer ARRAY[4],scheme text[][]);Inserting valuesArray values can be inserted as a literal constant, enclosing the element values withincurly braces and separating them by commas. An example is shown below.INSERT INTO monthly_savingsVALUES (‘Manisha’,‘{20000, 14600, 23500, 13250}’,‘{{“FD”, “MF”}, {“FD”, “Property”}}’);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-47-2048.jpg&f=jpg&w=240)
![PostgreSQL41Accessing ArraysAn example for accessing Arrays is shown below. The command given below will select thepersons whose savings are more in second quarter than fourth quarter.SELECT name FROM monhly_savings WHERE saving_per_quarter[2] >saving_per_quarter[4];Modifying ArraysAn example of modifying arrays is as shown below.UPDATE monthly_savings SET saving_per_quarter = '{25000,25000,27000,27000}'WHERE name = 'Manisha';or using the ARRAY expression syntax:UPDATE monthly_savings SET saving_per_quarter = ARRAY[25000,25000,27000,27000]WHERE name = 'Manisha';Searching ArraysAn example of searching arrays is as shown below.SELECT * FROM monthly_savings WHERE saving_per_quarter[1] = 10000 ORsaving_per_quarter[2] = 10000 ORsaving_per_quarter[3] = 10000 ORsaving_per_quarter[4] = 10000;If the size of array is known, the search method given above can be used. Else, thefollowing example shows how to search when the size is not known.SELECT * FROM monthly_savings WHERE 10000 = ANY (saving_per_quarter);CompositeTypesThis type represents a list of field names and their data types, i.e., structure of a row orrecord of a table.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-48-2048.jpg&f=jpg&w=240)

![PostgreSQL43 int8range - Range of bigint numrange - Range of numeric tsrange - Range of timestamp without time zone tstzrange - Range of timestamp with time zone daterange - Range of dateCustom range types can be created to make new types of ranges available, such as IPaddress ranges using the inet type as a base, or float ranges using the float data type asa base.Range types support inclusive and exclusive range boundaries using the [ ] and ( )characters, respectively. For example, '[4,9]' represents all the integers starting from andincluding 4 up to but not including 9.ObjectIdentifierTypesObject identifiers (OIDs) are used internally by PostgreSQL as primary keys for varioussystem tables. If WITH OIDS is specified or default_with_oids configuration variable isenabled, only then, in such cases OIDs are added to user-created tables. The followingtable lists several alias types. The OID alias types have no operations of their own exceptfor specialized input and output routines.Name References Description Value Exampleoid any numeric object identifier 564182regproc pg_proc function name sumregprocedure pg_proc function with argument types sum(int4)regoper pg_operator operator name +regoperator pg_operator operator with argument types *(integer,integer) or -(NONE,integer)regclass pg_class relation name pg_typeregtype pg_type data type name integerregconfig pg_ts_config text search configuration Englishregdictionary pg_ts_dict text search dictionary simplePseudoTypesThe PostgreSQL type system contains a number of special-purpose entries that arecollectively called pseudo-types. A pseudo-type cannot be used as a column data type,but it can be used to declare a function's argument or result type.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-50-2048.jpg&f=jpg&w=240)

![PostgreSQL45This chapter discusses about how to create a new database in your PostgreSQL.PostgreSQL provides two ways of creating a new database: Using CREATE DATABASE, an SQL command. Using createdb a command-line executable.Using CREATE DATABASEThis command will create a database from PostgreSQL shell prompt, but you should haveappropriate privilege to create a database. By default, the new database will be createdby cloning the standard system database template1.SyntaxThe basic syntax of CREATE DATABASE statement is as follows-CREATE DATABASE dbname;where dbname is the name of a database to create.ExampleFollowing is a simple example, which will create testdb in your PostgreSQL schema-postgres=# CREATE DATABASE testdb;postgres-#UsingcreatedbCommandPostgreSQL command line executable createdb is a wrapper around the SQLcommand CREATE DATABASE. The only difference between this command and SQLcommand CREATE DATABASE is that the former can be directly run from the commandline and it allows a comment to be added into the database, all in one command.SyntaxThe syntax for createdb is as shown below-createdb [option...] [dbname [description]]5. PostgreSQL – CREATE Database](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-52-2048.jpg&f=jpg&w=240)




![PostgreSQL50In this chapter, we will discuss how to delete the database in PostgreSQL. There are twooptions to delete a database- Using DROP DATABASE, an SQL command. Using dropdb a command-line executable.Be careful before using this operation because deleting an existing database would resultin loss of complete information stored in the database.Using DROP DATABASEThis command drops a database. It removes the catalog entries for the database anddeletes 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 targetdatabase (connect to postgres or any other database to issue this command).SyntaxThe syntax for DROP DATABASE is given below-DROP DATABASE [ IF EXISTS ] nameParametersThe table lists the parameters with their descriptions.Parameter DescriptionIF EXISTSDo not throw an error if the database does not exist. A notice is issued inthis case.name The name of the database to remove.We cannot drop a database that has any open connections, including our own connectionfrom psql or pgAdmin III. We must switch to another database or template1 if we want todelete the database we are currently connected to. Thus, it might be more convenient touse the program dropdb instead, which is a wrapper around this command.ExampleFollowing is a simple example, which will delete testdb from your PostgreSQL schema-postgres=# DROP DATABASE testdb;postgres-#7. PostgreSQL – DROP Database](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-57-2048.jpg&f=jpg&w=240)
![PostgreSQL51UsingdropdbCommandPostgresSQL command line executable dropdb is a command-line wrapper around theSQL command DROP DATABASE. There is no effective difference between droppingdatabases via this utility and via other methods for accessing the server. dropdb destroysan existing PostgreSQL database. The user, who executes this command must be adatabase super user or the owner of the database.SyntaxThe syntax for createdb is as shown below-dropdb [option...] dbnameParametersThe following table lists the parameters with their descriptions-Parameter Descriptiondbname The name of a database to be deleted.option command-line arguments, which dropdb accepts.OptionsThe following table lists the command-line arguments dropdb accepts-Option Description-e Shows the commands being sent to the server.-iIssues a verification prompt before doing anythingdestructive.-V Print the dropdb version and exit.--if-existsDo not throw an error if the database does not exist. Anotice is issued in this case.--helpShow help about dropdb command-line arguments, andexit.-h hostSpecifies the host name of the machine on which the serveris running.-p portSpecifies the TCP port or the local UNIX domain socket fileextension on which the server is listening for connections.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-58-2048.jpg&f=jpg&w=240)



















![PostgreSQL71An expression is a combination of one or more values, operators, and PostgresSQLfunctions that evaluate to a value.PostgreSQL EXPRESSIONS are like formulas and they are written in query language. Youcan also use to query the database for specific set of data.SyntaxConsider the basic syntax of the SELECT statement as follows-SELECT column1, column2, columnNFROM table_nameWHERE [CONTION | EXPRESSION];There are different types of PostgreSQL expressions, which are mentioned below.PostgreSQL–BooleanExpressionsPostgreSQL Boolean Expressions fetch the data on the basis of matching single value.Following is the syntax-SELECT column1, column2, columnNFROM table_nameWHERE SINGLE VALUE MATCHTING EXPRESSION;Consider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)14. PostgreSQL – Expressions](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-78-2048.jpg&f=jpg&w=240)
![PostgreSQL72Here is the simple example showing usage of PostgreSQL Boolean Expressions-testdb=# SELECT * FROM COMPANY WHERE SALARY = 10000;The above given PostgreSQL statement will produce the following result-id | name | age | address | salary----+-------+-----+----------+--------7 | James | 24 | Houston | 10000(1 row)PostgreSQL–NumericExpressionThese expressions are used to perform any mathematical operation in any query. Followingis the syntax-SELECT numerical_expression as OPERATION_NAME[FROM table_name WHERE CONDITION] ;Here numerical_expression is used for mathematical expression or any formula. Followingis a simple example showing usage of SQL Numeric Expressions-testdb=# SELECT (15 + 6) AS ADDITION ;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 knownas aggregate data calculations against a table or a specific table column.testdb=# SELECT COUNT(*) AS "RECORDS" FROM COMPANY;The above given PostgreSQL statement will produce the following result-RECORDS---------7(1 row)](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-79-2048.jpg&f=jpg&w=240)

![PostgreSQL74The PostgreSQL WHERE clause is used to specify a condition while fetching the data fromsingle table or joining with multiple tables.If the given condition is satisfied, only then it returns specific value from the table. Youcan filter out rows that you do not want included in the result-set by using the WHEREclause.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.SyntaxThe basic syntax of SELECT statement with WHERE clause is as follows-SELECT column1, column2, columnNFROM table_nameWHERE [search_condition]You can specify a search_condition using comparison or logical operators.like >, <, =,LIKE, NOT, etc. The following examples would make this concept clear.ExampleConsider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)15. PostgreSQL – WHERE Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-81-2048.jpg&f=jpg&w=240)




![PostgreSQL79The PostgreSQL AND and OR operators are used to combine multiple conditions to narrowdown selected data in a PostgreSQL statement. These two operators are called conjunctiveoperators.These operators provide a means to make multiple comparisons with different operatorsin the same PostgreSQL statement.TheANDOperatorThe AND operator allows the existence of multiple conditions in a PostgreSQL statement'sWHERE clause. While using AND operator, complete condition will be assumed true whenall the conditions are true. For example [condition1] AND [condition2] will be true onlywhen both condition1 and condition2 are true.SyntaxThe basic syntax of AND operator with WHERE clause is as follows-SELECT column1, column2, columnNFROM table_nameWHERE [condition1] AND [condition2]...AND [conditionN];You can combine N number of conditions using AND operator. For an action to be takenby the PostgreSQL statement, whether it be a transaction or query, all conditionsseparated by the AND must be TRUE.ExampleConsider the table COMPANY, having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)16. PostgreSQL – AND & OR Conjunctive Operators](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-86-2048.jpg&f=jpg&w=240)
![PostgreSQL80Following SELECT statement lists down all the records where AGE is greater than or equalto 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-id | name | age | address | salary----+-------+-----+------------+--------4 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 85000(2 rows)TheOROperatorThe OR operator is also used to combine multiple conditions in a PostgreSQL statement'sWHERE clause. While using OR operator, complete condition will be assumed true when atleast any of the conditions is true. For example [condition1] OR [condition2] will be true ifeither condition1 or condition2 is true.SyntaxThe basic syntax of OR operator with WHERE clause is as follows-SELECT column1, column2, columnNFROM table_nameWHERE [condition1] OR [condition2]...OR [conditionN]You can combine N number of conditions using OR operator. For an action to be taken bythe PostgreSQL statement, whether it be a transaction or query, only any ONE of theconditions separated by the OR must be TRUE.ExampleConsider the COMPANY table, having the following records-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 45000](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-87-2048.jpg&f=jpg&w=240)

![PostgreSQL82The PostgreSQL UPDATE Query is used to modify the existing records in a table. You canuse WHERE clause with UPDATE query to update the selected rows. Otherwise, all the rowswould be updated.SyntaxThe basic syntax of UPDATE query with WHERE clause is as follows-UPDATE table_nameSET column1 = value1, column2 = value2...., columnN = valueNWHERE [condition];You can combine N number of conditions using AND or OR operators.ExampleConsider the table COMPANY, having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which would update ADDRESS for a customer, whose ID is 6-testdb=# UPDATE COMPANY SET SALARY = 15000 WHERE ID = 3;Now, COMPANY table would have the following records-id | name | age | address | salary----+-------+-----+------------+--------1 | Paul | 32 | California | 200002 | Allen | 25 | Texas | 1500017. PostgreSQL – UPDATE Query](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-89-2048.jpg&f=jpg&w=240)

![PostgreSQL84The PostgreSQL DELETE Query is used to delete the existing records from a table. Youcan use WHERE clause with DELETE query to delete the selected rows. Otherwise, all therecords would be deleted.SyntaxThe basic syntax of DELETE query with WHERE clause is as follows-DELETE FROM table_nameWHERE [condition];You can combine N number of conditions using AND or OR operators.ExampleConsider the table COMPANY, having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which would DELETE a customer whose ID is 7-testdb=# DELETE FROM COMPANY WHERE ID = 2;Now, COMPANY table will have the following records-id | name | age | address | salary----+-------+-----+-------------+--------1 | Paul | 32 | California | 200003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 6500018. PostgreSQL – DELETE Query](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-91-2048.jpg&f=jpg&w=240)




![PostgreSQL89The PostgreSQL LIMIT clause is used to limit the data amount returned by the SELECTstatement.SyntaxThe basic syntax of SELECT statement with LIMIT clause is as follows-SELECT column1, column2, columnNFROM table_nameLIMIT [no of rows]Following is the syntax of LIMIT clause when it is used along with OFFSET clause-SELECT column1, column2, columnNFROM table_nameLIMIT [no of rows] OFFSET [row num]LIMIT and OFFSET allow you to retrieve just a portion of the rows that are generated bythe rest of the query.ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which limits the row in the table according to the number of rowsyou want to fetch from table-testdb=# SELECT * FROM COMPANY LIMIT 4;20. PostgreSQL – LIMIT Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-96-2048.jpg&f=jpg&w=240)

![PostgreSQL91The PostgreSQL ORDER BY clause is used to sort the data in ascending or descendingorder, based on one or more columns.Syntax-The basic syntax of ORDER BY clause is as follows-SELECT column-listFROM 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 columnyou are using to sort, that column should be available in column-list.ExampleConsider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Following is an example, which would sort the result in descending order by SALARY-testdb=# SELECT * FROM COMPANY ORDER BY AGE ASC;21. PostgreSQL – ORDER BY Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-98-2048.jpg&f=jpg&w=240)


![PostgreSQL94The PostgreSQL GROUP BY clause is used in collaboration with the SELECT statement togroup together those rows in a table that have identical data. This is done to eliminateredundancy in the output and/or compute aggregates that apply to these groups.The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes theORDER BY clause.SyntaxThe basic syntax of GROUP BY clause is given below. The GROUP BY clause must followthe conditions in the WHERE clause and must precede the ORDER BY clause if one is used.SELECT column-listFROM table_nameWHERE [ conditions ]GROUP BY column1, column2....columnNORDER BY column1, column2....columnNYou can use more than one column in the GROUP BY clause. Make sure whatever columnyou are using to group, that column should be available in column-list.ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)22. PostgreSQL – GROUP BY](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-101-2048.jpg&f=jpg&w=240)


![PostgreSQL97In PostgreSQL, the WITH query provides a way to write auxiliary statements for use in alarger query. It helps in breaking down complicated and large queries into simpler forms,which are easily readable. These statements often referred to as Common TableExpressions or CTEs, can be thought of as defining temporary tables that exist just for onequery.The WITH query being CTE query, is particularly useful when subquery is executed multipletimes. It is equally helpful in place of temporary tables. It computes the aggregation onceand allows us to reference it by its name (may be multiple times) in the queries.The WITH clause must be defined before it is used in the query.SyntaxThe basic syntax of WITH query is as follows-WITHname_for_summary_data AS (SELECT Statement)SELECT columnsFROM name_for_summary_dataWHERE conditions <=> (SELECT columnFROM name_for_summary_data)[ORDER BY columns]Where name_for_summary_data is the name given to the WITH clause. Thename_for_summary_data can be the same as an existing table name and will takeprecedence.You can use data-modifying statements (INSERT, UPDATE or DELETE) in WITH. This allowsyou to perform several different operations in the same query.RecursiveWITHRecursive WITH or Hierarchical queries, is a form of CTE where a CTE can reference toitself, i.e., a WITH query can refer to its own output, hence the name recursive.23. PostgreSQL – WITH Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-104-2048.jpg&f=jpg&w=240)



![PostgreSQL101The HAVING clause allows us to pick out particular rows where the function's result meetssome condition.The WHERE clause places conditions on the selected columns, whereas the HAVING clauseplaces conditions on groups created by the GROUP BY clause.SyntaxThe following is the position of the HAVING clause in a SELECT query-SELECTFROMWHEREGROUP BYHAVINGORDER BYThe HAVING clause must follow the GROUP BY clause in a query and must also precedethe ORDER BY clause if used. The following is the syntax of the SELECT statement,including the HAVING clause-SELECT column1, column2FROM table1, table2WHERE [ conditions ]GROUP BY column1, column2HAVING [ conditions ]ORDER BY column1, column2ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 6500024. PostgreSQL – HAVING Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-108-2048.jpg&f=jpg&w=240)


![PostgreSQL104The PostgreSQL DISTINCT keyword is used in conjunction with SELECT statement toeliminate all the duplicate records and fetching only unique records.There may be a situation when you have multiple duplicate records in a table. Whilefetching such records, it makes more sense to fetch only unique records instead of fetchingduplicate records.SyntaxThe basic syntax of DISTINCT keyword to eliminate duplicate records is as follows-SELECT DISTINCT column1, column2,.....columnNFROM table_nameWHERE [condition]ExampleConsider the table COMPANY having records as follows-# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Let us add two more records to this table as follows-INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)VALUES (8, 'Paul', 32, 'California', 20000.00 );INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)VALUES (9, 'Allen', 25, 'Texas', 15000.00 );25. PostgreSQL – DISTINCT Keyword](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-111-2048.jpg&f=jpg&w=240)














![PostgreSQL119The PostgreSQL UNION clause/operator is used to combine the results of two or moreSELECT statements without returning any duplicate rows.To use UNION, each SELECT must have the same number of columns selected, the samenumber of column expressions, the same data type, and have them in the same order butthey do not have to be the same length.SyntaxThe basic syntax of UNION is as follows-SELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]UNIONSELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]Here, given condition could be any given expression based on your requirement.ExampleConsider the following two tables, (a) COMPANY table is as follows-testdb=# SELECT * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)28. PostgreSQL – UNIONS Clause](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-126-2048.jpg&f=jpg&w=240)

![PostgreSQL121TheUNIONALLClauseThe UNION ALL operator is used to combine the results of two SELECT statementsincluding duplicate rows. The same rules that apply to UNION apply to the UNION ALLoperator as well.Syntax:The basic syntax of UNION ALL is as follows-SELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]UNION ALLSELECT column1 [, column2 ]FROM table1 [, table2 ][WHERE condition]Here, given condition could be any given expression based on your requirement.ExampleNow, let us join above-mentioned two tables in our SELECT statement as follows-testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENTON COMPANY.ID = DEPARTMENT.EMP_IDUNION ALLSELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENTON COMPANY.ID = DEPARTMENT.EMP_ID;This would produce the following result-emp_id | name | dept--------+-------+--------------1 | Paul | IT Billing2 | Allen | Engineering7 | James | Finance3 | Teddy | Engineering4 | Mark | Finance5 | David | Engineering6 | Kim | Finance1 | Paul | IT Billing2 | Allen | Engineering](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-128-2048.jpg&f=jpg&w=240)




![PostgreSQL126You can rename a table or a column temporarily by giving another name, which is knownas ALIAS. The use of table aliases means to rename a table in a particular PostgreSQLstatement. Renaming is a temporary change and the actual table name does not changein the database.The column aliases are used to rename a table's columns for the purpose of a particularPostgreSQL query.SyntaxThe basic syntax of table alias is as follows-SELECT column1, column2....FROM table_name AS alias_nameWHERE [condition];The basic syntax of column alias is as follows-SELECT column_name AS alias_nameFROM table_nameWHERE [condition];ExampleConsider the following two tables, (a) COMPANY table is as follows-testdb=# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)30. PostgreSQL – ALIAS Syntax](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-133-2048.jpg&f=jpg&w=240)



![PostgreSQL130 A CONSTRAINT option when specified creates a constraint trigger. This is the sameas a regular trigger except that the timing of the trigger firing can be adjustedusing SET CONSTRAINTS. Constraint triggers are expected to raise an exceptionwhen the constraints they implement are violated.SyntaxThe basic syntax of creating a trigger is as follows-CREATE TRIGGER trigger_name [BEFORE|AFTER|INSTEAD OF] event_nameON table_name[-- Trigger logic goes here....];Here, event_name could be INSERT, DELETE, UPDATE, and TRUNCATE databaseoperation on the mentioned table table_name. You can optionally specify FOR EACH ROWafter table name.Following is the syntax of creating a trigger on an UPDATE operation on one or morespecified columns of a table as follows-CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_nameON table_name[-- Trigger logic goes here....];ExampleLet us consider a case where we want to keep audit trial for every record being insertedin COMPANY table, which we will create newly as follows (Drop COMPANY table if youalready have it).testdb=# CREATE TABLE COMPANY(ID INT PRIMARY KEY NOT NULL,NAME TEXT NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(50),SALARY REAL);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-137-2048.jpg&f=jpg&w=240)









![PostgreSQL140Views are pseudo-tables. That is, they are not real tables; nevertheless appear as ordinarytables to SELECT. A view can represent a subset of a real table, selecting certain columnsor certain rows from an ordinary table. A view can even represent joined tables. Becauseviews are assigned separate permissions, you can use them to restrict table access so thatthe 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 viewcan be created from one or many tables, which depends on the written PostgreSQL queryto create a view.Views, which are kind of virtual tables, allow users to do the following- Structure data in a way that users or classes of users find natural or intuitive. Restrict access to the data such that a user can only see limited data instead ofcomplete table. Summarize data from various tables, which can be used to generate reports.Since views are not ordinary tables, you may not be able to execute a DELETE, INSERT,or UPDATE statement on a view. However, you can create a RULE to correct this problemof using DELETE, INSERT or UPDATE on a view.CreatingViewsThe PostgreSQL views are created using the CREATE VIEW statement. The PostgreSQLviews can be created from a single table, multiple tables, or another view.The basic CREATE VIEW syntax is as follows-CREATE [TEMP | TEMPORARY] VIEW view_name ASSELECT column1, column2.....FROM table_nameWHERE [condition];You can include multiple tables in your SELECT statement in very similar way as you usethem in normal PostgreSQL SELECT query. If the optional TEMP or TEMPORARY keywordis present, the view will be created in the temporary space. Temporary views areautomatically dropped at the end of the current session.35. PostgreSQL – VIEWS](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-147-2048.jpg&f=jpg&w=240)





![PostgreSQL146Locks or Exclusive Locks or Write Locks prevent users from modifying a row or an entiretable. Rows modified by UPDATE and DELETE are then exclusively locked automatically forthe duration of the transaction. This prevents other users from changing the row until thetransaction is either committed or rolled back.The only time when users must wait for other users is when they are trying to modify thesame row. If they modify different rows, no waiting is necessary. SELECT queries neverhave to wait.The database performs locking automatically. In certain cases, however, locking must becontrolled manually. Manual locking can be done by using the LOCK command. It allowsspecification of a transaction's lock type and scope.Syntax for LOCK commandThe basic syntax for LOCK command is as follows-LOCK [ TABLE ]nameINlock_mode name: The name (optionally schema-qualified) of an existing table to lock. If ONLYis specified before the table name, only that table is locked. If ONLY is not specified,the table and all its descendant tables (if any) are locked. lock_mode: The lock mode specifies which locks this lock conflicts with. If no lockmode is specified, then ACCESS EXCLUSIVE, the most restrictive mode, is used.Possible values are: ACCESS SHARE, ROW SHARE , ROW EXCLUSIVE, SHAREUPDATE EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, ACCESSEXCLUSIVE.Once obtained, the lock is held for the remainder of the current transaction. There is noUNLOCK TABLE command; locks are always released at the transaction end.DeadLocksDeadlocks can occur when two transactions are waiting for each other to finish theiroperations. While PostgreSQL can detect them and end them with a ROLLBACK, deadlockscan still be inconvenient. To prevent your applications from running into this problem,make sure to design them in such a way that they will lock objects in the same order.37. PostgreSQL – LOCKS](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-153-2048.jpg&f=jpg&w=240)

![PostgreSQL148A subquery or Inner query or Nested query is a query within another PostgreSQL queryand embedded within the WHERE clause.A subquery is used to return data that will be used in the main query as a condition tofurther restrict the data to be retrieved.Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE statements alongwith the operators like =, <, >, >=, <=, IN, etc.There are a few rules that subqueries must follow. Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiplecolumns are in the main query for the subquery to compare its selected columns. An ORDER BY cannot be used in a subquery, although the main query can use anORDER BY. The GROUP BY can be used to perform the same function as the ORDERBY in a subquery. Subqueries that return more than one row can only be used with multiple valueoperators, such as the IN, EXISTS, NOT IN, ANY/SOME, ALL operator. The BETWEEN operator cannot be used with a subquery; however, the BETWEENcan be used within the subquery.SubquerieswiththeSELECTStatementSubqueries are most frequently used with the SELECT statement. The basic syntax is asfollows-SELECT column_name [, column_name ]FROM table1 [, table2 ]WHERE column_name OPERATOR(SELECT column_name [, column_name ]FROM table1 [, table2 ][WHERE])38. PostgreSQL – Sub Queries](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-155-2048.jpg&f=jpg&w=240)
![PostgreSQL149ExampleConsider the COMPANY table having the following records-id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)Now, let us check the following sub-query with SELECT statement-testdb=# SELECT *FROM COMPANYWHERE ID IN (SELECT IDFROM COMPANYWHERE SALARY > 45000) ;This would produce the following result-id | name | age | address | salary----+-------+-----+-------------+--------4 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 85000(2 rows)SubquerieswiththeINSERTStatementSubqueries also can be used with INSERT statements. The INSERT statement uses thedata returned from the subquery to insert into another table. The selected data in thesubquery can be modified with any of the character, date, or number functions.The basic syntax is as follows-INSERT INTO table_name [ (column1 [, column2 ]) ]SELECT [ *|column1 [, column2 ]FROM table1 [, table2 ][ WHERE VALUE OPERATOR ]](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-156-2048.jpg&f=jpg&w=240)
[ WHERE) ]ExampleAssuming, we have COMPANY_BKP table available, which is backup of the COMPANY table.The following example updates SALARY by 0.50 times in the COMPANY table for all thecustomers, whose AGE is greater than or equal to 27-testdb=# UPDATE COMPANYSET SALARY = SALARY * 0.50WHERE AGE IN (SELECT AGE FROM COMPANY_BKPWHERE AGE >= 27 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-157-2048.jpg&f=jpg&w=240)
[ WHERE) ]ExampleAssuming, we have COMPANY_BKP table available, which is a backup of the COMPANYtable.The following example deletes records from the COMPANY table for all the customers,whose AGE is greater than or equal to 27-testdb=# DELETE FROM COMPANYWHERE AGE IN (SELECT AGE FROM COMPANY_BKPWHERE AGE > 27 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-158-2048.jpg&f=jpg&w=240)



![PostgreSQL155Whenever an object is created in a database, an owner is assigned to it. The owner isusually the one who executed the creation statement. For most kinds of objects, the initialstate is that only the owner (or a superuser) can modify or delete the object. To allowother roles or users to use it, privileges or permission must be granted.Different kinds of privileges in PostgreSQL are- SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, CREATE, CONNECT, TEMPORARY, EXECUTE, and USAGEDepending on the type of the object (table, function, etc.,), privileges are applied to theobject. To assign privileges to the users, the GRANT command is used.Syntax for GRANTBasic syntax for GRANT command is as follows-GRANT privilege [, ...]ON object [, ...]TO { PUBLIC | GROUP group | username } privilege values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. object: The name of an object to which to grant access. The possible objects are:table, view, sequence PUBLIC: A short form representing all users. GROUP group: A group to whom to grant privileges.40. PostgreSQL – PRIVILEGES](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-162-2048.jpg&f=jpg&w=240)
![PostgreSQL156 username: The name of a user to whom to grant privileges. PUBLIC is a shortform representing all users.The privileges can be revoked using the REVOKE command.Syntax for REVOKEBasic syntax for REVOKE command is as follows-REVOKE privilege [, ...]ON object [, ...]FROM { PUBLIC | GROUP groupname | username } privilege values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. object: The name of an object to which to grant access. The possible objects are:table, view, sequence PUBLIC: A short form representing all users. GROUP group: A group to whom to grant privileges. username: The name of a user to whom to grant privileges. PUBLIC is a shortform representing all users.ExampleTo understand the privileges, let us first create a USER as follows-testdb=# CREATE USER manisha WITH PASSWORD 'password';CREATE ROLEThe message CREATE ROLE indicates that the USER "manisha" is created.Consider the table COMPANY having records as follows-testdb# select * from COMPANY;id | name | age | address | salary----+-------+-----+-----------+--------1 | Paul | 32 | California| 200002 | Allen | 25 | Texas | 150003 | Teddy | 23 | Norway | 200004 | Mark | 25 | Rich-Mond | 650005 | David | 27 | Texas | 850006 | Kim | 22 | South-Hall| 450007 | James | 24 | Houston | 10000(7 rows)](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-163-2048.jpg&f=jpg&w=240)









![PostgreSQL166PostgreSQL functions, also known as Stored Procedures, allow you to carry outoperations that would normally take several queries and round trips in a single functionwithin the database. Functions allow database reuse as other applications can interactdirectly with your stored procedures instead of a middle-tier or duplicating code.Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc.SyntaxThe basic syntax to create a function is as follows-CREATE [OR REPLACE] FUNCTION function_name (arguments)RETURNS return_datatype AS $variable_name$DECLAREdeclaration;[...]BEGIN< function_body >[...]RETURN { variable_name | value }END; LANGUAGE plpgsql;Where, function-name specifies the name of the function. [OR REPLACE] option allows modifying an existing function. The function must contain a return statement. 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 referencethe type of a table column. function-body contains the executable part. The AS keyword is used for creating a standalone function. plpgsql is the name of the language that the function is implemented in. Here, weuse 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 beenclosed by single quotes.42. PostgreSQL – Functions](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-173-2048.jpg&f=jpg&w=240)

























![PostgreSQL192(1 row)expr REGEXP patternREGEXP_MATCHES(string text, pattern text [, flags text]) function performs a patternmatch of expr against pattern. Returns 1 if expr matches pat; otherwise it returns 0. Ifeither expr or pat is NULL, the result is NULL. REGEXP_MATCHES is not case sensitive,except when used with binary strings.REGEXP_REPLACE(string text, pattern text, replacement text [, flags text]) functionreplaces substring(s) matching a POSIX regular expression.REGEXP_SPLIT_TO_ARRAY(string text, pattern text [, flags text ]), Split string using aPOSIX regular expression as the delimiter.REGEXP_SPLIT_TO_TABLE(string text, pattern text [, flags text]), splits string using aPOSIX regular expression as the delimiter.Following are the examples for all these functions-testdb=# SELECT REGEXP_MATCHES('ABCDEF' ,'A%C%%');regexp_matches----------------(0 rows)testdb=# SELECT REGEXP_REPLACE('Thomas', '.[mN]a.', 'M');regexp_replace----------------ThM(1 row)testdb=# SELECT REGEXP_SPLIT_TO_ARRAY('hello world', E's+');regexp_split_to_array-----------------------{hello,world}(1 row)testdb=# SELECT REGEXP_SPLIT_TO_TABLE('hello world', E's+');regexp_split_to_table-----------------------helloworld](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-199-2048.jpg&f=jpg&w=240)


![PostgreSQL195(1 row)testdb=# SELECT SUBSTRING('foobarbar' FROM 4);substring-----------barbar(1 row)testdb=# SELECT SUBSTRING('Quadratically',5,6);substring-----------ratica(1 row)TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)TRIM([remstr FROM] str)Returns the string str with all remstr prefixes or suffixes removed. If none of the specifiersBOTH, LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if notspecified, spaces are removed.testdb=# SELECT TRIM(' bar ');btrim-------bar(1 row)testdb=# SELECT TRIM(LEADING 'x' FROM 'xxxbarxxx');ltrim--------barxxx(1 row)testdb=# SELECT TRIM(BOTH 'x' FROM 'xxxbarxxx');btrim-------bar(1 row)](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-202-2048.jpg&f=jpg&w=240)


![PostgreSQL198This tutorial is going to use libpqxx library, which is the official C++ client API forPostgreSQL. The source code for libpqxx is available under the BSD license, so you're freeto download it, pass it on to others, change it, sell it, include it in your own code, andshare your changes with anyone you choose.InstallationThe the latest version of libpqxx is available to be downloaded from the link DownloadLibpqxx. So download the latest version and follow the following steps-wget http://pqxx.org/download/software/libpqxx/libpqxx-4.0.tar.gztar xvfz libpqxx-4.0.tar.gzcd libpqxx-4.0./configuremakemake installBefore you start using C/C++ PostgreSQL interface, find the pg_hba.conf file in yourPostgreSQL installation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can start/restart postgres server in case it is not running using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]44. PostgreSQL – C/C++ Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-205-2048.jpg&f=jpg&w=240)

![PostgreSQL2009N.exec(const std::string & sql)This public method from non-transactional object will be used to execute SQLstatement and returns a result object which is actually an interator holding allthe returned records.ConnectingToDatabaseThe following C code segment shows how to connect to an existing database running onlocal machine at port 5432. Here, I used backslash for line continuation.#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){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;}C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}}Now, let us compile and run the above program to connect to our database testdb, whichis already available in your schema and can be accessed using user postgres andpassword pass123.You can use the user ID and password based on your database setting. Remember to keepthe -lpqxx and -lpq in the given order! Otherwise, the linker will complain bitterly aboutthe missing functions with names starting with "PQ."](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-207-2048.jpg&f=jpg&w=240)
![PostgreSQL201$g++ test.cpp -lpqxx -lpq$./a.outOpened database successfully: testdbCreateaTableThe following C code segment will be used to create a table in previously created database-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create SQL statement */sql = "CREATE TABLE COMPANY(" "ID INT PRIMARY KEY NOT NULL," "NAME TEXT NOT NULL," "AGE INT NOT NULL," "ADDRESS CHAR(50)," "SALARY REAL );";/* Create a transactional object. */work W(C);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-208-2048.jpg&f=jpg&w=240)
![PostgreSQL202/* Execute SQL query */W.exec( sql );W.commit();cout << "Table created successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will create COMPANY table inyour testdb database and will display the following statements-Opened database successfully: testdbTable created successfullyINSERTOperationThe following C code segment shows how we can create records in our COMPANY tablecreated in above example-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;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;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-209-2048.jpg&f=jpg&w=240)

![PostgreSQL204SELECTOperationThe following C code segment shows how we can fetch and display records from ourCOMPANY table created in above example-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create SQL statement */sql = "SELECT * from COMPANY";/* Create a non-transactional object. */nontransaction N(C);/* Execute SQL query */result R( N.exec( sql ));/* List down all the records */for (result::const_iterator c = R.begin(); c != R.end(); ++c) {cout << "ID = " << c[0].as<int>() << endl;cout << "Name = " << c[1].as<string>() << endl;cout << "Age = " << c[2].as<int>() << endl;cout << "Address = " << c[3].as<string>() << endl;](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-211-2048.jpg&f=jpg&w=240)
![PostgreSQL205cout << "Salary = " << c[4].as<float>() << endl;}cout << "Operation done successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will produce the followingresult-Opened database successfully: testdbID = 1Name = PaulAge = 32Address = CaliforniaSalary = 20000ID = 2Name = AllenAge = 25Address = TexasSalary = 15000ID = 3Name = TeddyAge = 23Address = NorwaySalary = 20000ID = 4Name = MarkAge = 25Address = Rich-MondSalary = 65000Operation done successfully](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-212-2048.jpg&f=jpg&w=240)
![PostgreSQL206UPDATEOperationThe following C code segment shows how we can use the UPDATE statement to updateany record and then fetch and display updated records from our COMPANY table-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create a transactional object. */work W(C);/* Create SQL UPDATE statement */sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1";/* Execute SQL query */W.exec( sql );W.commit();cout << "Records updated successfully" << endl;/* Create SQL SELECT statement */sql = "SELECT * from COMPANY";/* Create a non-transactional object. */nontransaction N(C);](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-213-2048.jpg&f=jpg&w=240)
![PostgreSQL207/* Execute SQL query */result R( N.exec( sql ));/* List down all the records */for (result::const_iterator c = R.begin(); c != R.end(); ++c) {cout << "ID = " << c[0].as<int>() << endl;cout << "Name = " << c[1].as<string>() << endl;cout << "Age = " << c[2].as<int>() << endl;cout << "Address = " << c[3].as<string>() << endl;cout << "Salary = " << c[4].as<float>() << endl;}cout << "Operation done successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will produce the followingresult-Opened database successfully: testdbRecords updated successfullyID = 2Name = AllenAge = 25Address = TexasSalary = 15000ID = 3Name = TeddyAge = 23Address = NorwaySalary = 20000ID = 4Name = Mark](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-214-2048.jpg&f=jpg&w=240)
![PostgreSQL208Age = 25Address = Rich-MondSalary = 65000ID = 1Name = PaulAge = 32Address = CaliforniaSalary = 25000Operation done successfullyDELETEOperationThe following C code segment shows how we can use the DELETE statement to delete anyrecord and then fetch and display remaining records from our COMPANY table-#include <iostream>#include <pqxx/pqxx>using namespace std;using namespace pqxx;int main(int argc, char* argv[]){char * sql;try{connection C("dbname=testdb user=postgres password=cohondob hostaddr=127.0.0.1 port=5432");if (C.is_open()) {cout << "Opened database successfully: " << C.dbname() << endl;} else {cout << "Can't open database" << endl;return 1;}/* Create a transactional object. */work W(C);/* Create SQL DELETE statement */sql = "DELETE from COMPANY where ID = 2";](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-215-2048.jpg&f=jpg&w=240)
![PostgreSQL209/* Execute SQL query */W.exec( sql );W.commit();cout << "Records deleted successfully" << endl;/* Create SQL SELECT statement */sql = "SELECT * from COMPANY";/* Create a non-transactional object. */nontransaction N(C);/* Execute SQL query */result R( N.exec( sql ));/* List down all the records */for (result::const_iterator c = R.begin(); c != R.end(); ++c) {cout << "ID = " << c[0].as<int>() << endl;cout << "Name = " << c[1].as<string>() << endl;cout << "Age = " << c[2].as<int>() << endl;cout << "Address = " << c[3].as<string>() << endl;cout << "Salary = " << c[4].as<float>() << endl;}cout << "Operation done successfully" << endl;C.disconnect ();}catch (const std::exception &e){cerr << e.what() << std::endl;return 1;}return 0;}When the above given program is compiled and executed, it will produce the followingresult-Opened database successfully: testdb](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-216-2048.jpg&f=jpg&w=240)

![PostgreSQL211InstallationBefore we start using PostgreSQL in our Java programs, we need to make sure that wehave PostgreSQL JDBC and Java set up on the machine. You can check Java tutorial forJava installation on your machine. Now let us check how to set up PostgreSQL JDBC driver. Download the latest version of postgresql-(VERSION).jdbc.jar from postgresql-jdbc repository. Add downloaded jar file postgresql-(VERSION).jdbc.jar in your class path, or youcan use it along with -classpath option as explained below in the examples.The following section assumes you have little knowledge about Java JDBC concepts. If youdo not have, then it is suggested to spent half and hour with JDBC Tutorial to becomecomfortable with concepts explained below.ConnectingToDatabaseThe following Java code shows how to connect to an existing database. If the databasedoes not exist, then it will be created and finally a database object will be returned.import java.sql.Connection;import java.sql.DriverManager;public class PostgreSQLJDBC {public static void main(String args[]) {Connection c = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","postgres", "123");} catch (Exception e) {e.printStackTrace();System.err.println(e.getClass().getName()+": "+e.getMessage());System.exit(0);}System.out.println("Opened database successfully");}}45. PostgreSQL – JAVA Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-218-2048.jpg&f=jpg&w=240)
![PostgreSQL212Before you compile and run above program, find pg_hba.conf file in your PostgreSQLinstallation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can start/restart the postgres server, in case it is not running, using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]Now, let us compile and run the above program to connect with testdb. Here, we areusing postgres as user ID and 123 as password to access the database. You can changethis as per your database configuration and setup. We are also assuming current versionof JDBC driver postgresql-9.2-1002.jdbc3.jar is available in the current path.C:JavaPostgresIntegration>javac PostgreSQLJDBC.javaC:JavaPostgresIntegration>java -cp c:toolspostgresql-9.2-1002.jdbc3.jar;C:JavaPostgresIntegration PostgreSQLJDBCOpen database successfullyCreateaTableThe 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;public class PostgreSQLJDBC {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-219-2048.jpg&f=jpg&w=240)
![PostgreSQL213System.out.println("Opened database successfully");stmt = c.createStatement();String sql = "CREATE TABLE COMPANY " +"(ID INT PRIMARY KEY NOT NULL," +" NAME TEXT NOT NULL, " +" AGE INT NOT NULL, " +" ADDRESS CHAR(50), " +" SALARY REAL)";stmt.executeUpdate(sql);stmt.close();c.close();} catch ( Exception e ) {System.err.println( e.getClass().getName()+": "+ e.getMessage() );System.exit(0);}System.out.println("Table created successfully");}}When a program is compiled and executed, it will create the COMPANY tablein testdb database and will display the following two lines-Opened database successfullyTable created successfullyINSERTOperationThe following Java program shows how we can create records in our COMPANY tablecreated in above example-import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;public class PostgreSQLJDBC {public static void main(String args[]) {Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-220-2048.jpg&f=jpg&w=240)

![PostgreSQL215Records created successfullySELECTOperationThe following Java program shows how we can fetch and display records from ourCOMPANY table created in above example-import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");c.setAutoCommit(false);System.out.println("Opened database successfully");stmt = c.createStatement();ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );while ( rs.next() ) {int id = rs.getInt("id");String name = rs.getString("name");int age = rs.getInt("age");String address = rs.getString("address");float salary = rs.getFloat("salary");System.out.println( "ID = " + id );System.out.println( "NAME = " + name );System.out.println( "AGE = " + age );System.out.println( "ADDRESS = " + address );System.out.println( "SALARY = " + salary );System.out.println();}](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-222-2048.jpg&f=jpg&w=240)

![PostgreSQL217UPDATEOperationThe following Java code shows how we can use the UPDATE statement to update anyrecord and then fetch and display updated records from our COMPANY table-import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");c.setAutoCommit(false);System.out.println("Opened database successfully");stmt = c.createStatement();String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";stmt.executeUpdate(sql);c.commit();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 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-224-2048.jpg&f=jpg&w=240)

![PostgreSQL219Operation done successfullyDELETEOperationThe following Java code shows how we can use the DELETE statement to delete any recordand then fetch and display remaining records from our COMPANY table-import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC6 {public static void main( String args[] ){Connection c = null;Statement stmt = null;try {Class.forName("org.postgresql.Driver");c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb","manisha", "123");c.setAutoCommit(false);System.out.println("Opened database successfully");stmt = c.createStatement();String sql = "DELETE from COMPANY where ID=2;";stmt.executeUpdate(sql);c.commit();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 );](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-226-2048.jpg&f=jpg&w=240)


![PostgreSQL222InstallationThe PostgreSQL extension is enabled by default in the latest releases of PHP 5.3.x. It ispossible to disable it by using --without-pgsql at compile time. Still you can use yumcommand to install PHP -PostgreSQL interface-yum install php-pgsqlBefore you start using the PHP PostgreSQL interface, find the pg_hba.conf file in yourPostgreSQL installation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can the start/restart postgres server, in case it is not running, using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]Windows users must enable php_pgsql.dll in order to use this extension. This DLL isincluded with Windows distributions in the latest releases of PHP 5.3.xFor detailed installation instructions, kindly check our PHP tutorial and its official website.PHPInterfaceAPIsThe following are important PHP routines, which can suffice your requirement to work withPostgreSQL database from your PHP program. If you are looking for a more sophisticatedapplication, then you can look into the PHP official documentation.S.No. API & Description1resource pg_connect ( string $connection_string [, int $connect_type ] )This opens a connection to a PostgreSQL database specified by theconnection_string.If PGSQL_CONNECT_FORCE_NEW is passed as connect_type, then a newconnection is created in case of a second call to pg_connect() , even if theconnection_string is identical to an existing connection.46. PostgreSQL – PHP Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-229-2048.jpg&f=jpg&w=240)
![PostgreSQL2232bool pg_connection_reset ( resource $connection )This routine resets the connection. It is useful for error recovery. ReturnsTRUE on success or FALSE on failure.3int pg_connection_status ( resource $connection )This routine returns the status of the specified connection. ReturnsPGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.4string pg_dbname ([ resource $connection ] )This routine returns the name of the database that the given PostgreSQLconnection resource.5resource pg_prepare ([ resource $connection ], string $stmtname ,string $query )This submits a request to create a prepared statement with the givenparameters and waits for completion.6resource pg_execute ([ resource $connection ], string $stmtname ,array $params )This routine sends a request to execute a prepared statement with givenparameters and waits for the result.7resource pg_query ([ resource $connection ], string $query )This routine executes the query on the specified database connection.8array pg_fetch_row ( resource $result [, int $row ] )This routine fetches one row of data from the result associated with thespecified result resource.9array pg_fetch_all ( resource $result )This routine returns an array that contains all rows (records) in the resultresource.10int pg_affected_rows ( resource $result )This routine returns the number of rows affected by INSERT, UPDATE, andDELETE queries.11int pg_num_rows ( resource $result )](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-230-2048.jpg&f=jpg&w=240)
![PostgreSQL224This routine returns the number of rows in a PostgreSQL result resource forexample number of rows returned by SELECT statement.12bool pg_close ([ resource $connection ] )This routine closes the non-persistent connection to a PostgreSQL databaseassociated with the given connection resource.13string pg_last_error ([ resource $connection ] )This routine returns the last error message for a given connection.14string pg_escape_literal ([ resource $connection ], string $data )This routine escapes a literal for insertion into a text field.15string pg_escape_string ([ resource $connection ], string $data )This routine escapes a string for querying the database.ConnectingtoDatabaseThe following PHP code shows how to connect to an existing database on a local machineand 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";$db = pg_connect( "$host $port $dbname $credentials" );if(!$db){echo "Error : Unable to open databasen";} else {echo "Opened database successfullyn";}?>Now, let us run the above given program to open our database testdb; if the database issuccessfully opened, then it will give the following message-Opened database successfully](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-231-2048.jpg&f=jpg&w=240)


![PostgreSQL227When the above given program is executed, it will create the given records in COMPANYtable and will display the following two lines-Opened database successfullyRecords created successfullySELECTOperationThe following PHP program shows how we can fetch and display records from ourCOMPANY table created in above example-<?php$host = "host=127.0.0.1";$port = "port=5432";$dbname = "dbname=testdb";$credentials = "user=postgres password=pass123";$db = pg_connect( "$host $port $dbname $credentials" );if(!$db){echo "Error : Unable to open databasen";} else {echo "Opened database successfullyn";}$sql =<<<EOFSELECT * from COMPANY;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;}while($row = pg_fetch_row($ret)){echo "ID = ". $row[0] . "n";echo "NAME = ". $row[1] ."n";echo "ADDRESS = ". $row[2] ."n";echo "SALARY = ".$row[4] ."nn";}echo "Operation done successfullyn";](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-234-2048.jpg&f=jpg&w=240)

![PostgreSQL229$db = pg_connect( "$host $port $dbname $credentials" );if(!$db){echo "Error : Unable to open databasen";} else {echo "Opened database successfullyn";}$sql =<<<EOFUPDATE COMPANY set SALARY = 25000.00 where ID=1;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;} else {echo "Record updated successfullyn";}$sql =<<<EOFSELECT * from COMPANY;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;}while($row = pg_fetch_row($ret)){echo "ID = ". $row[0] . "n";echo "NAME = ". $row[1] ."n";echo "ADDRESS = ". $row[2] ."n";echo "SALARY = ".$row[4] ."nn";}echo "Operation done successfullyn";pg_close($db);?>When the above given program is executed, it will produce the following result-](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-236-2048.jpg&f=jpg&w=240)

![PostgreSQL231DELETE from COMPANY where ID=2;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;} else {echo "Record deleted successfullyn";}$sql =<<<EOFSELECT * from COMPANY;EOF;$ret = pg_query($db, $sql);if(!$ret){echo pg_last_error($db);exit;}while($row = pg_fetch_row($ret)){echo "ID = ". $row[0] . "n";echo "NAME = ". $row[1] ."n";echo "ADDRESS = ". $row[2] ."n";echo "SALARY = ".$row[4] ."nn";}echo "Operation done successfullyn";pg_close($db);?>When the above given program is executed, it will produce the following result-Opened database successfully](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-238-2048.jpg&f=jpg&w=240)

![PostgreSQL233InstallationThe PostgreSQL can be integrated with Perl using Perl DBI module, which is a databaseaccess module for the Perl programming language. It defines a set of methods, variablesand 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 installIf 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 installBefore you start using Perl PostgreSQL interface, find the pg_hba.conf file in yourPostgreSQL installation directory and add the following line-# IPv4 local connections:host all all 127.0.0.1/32 md5You can start/restart the postgres server, in case it is not running, using the followingcommand-[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]47. PostgreSQL – Perl Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-240-2048.jpg&f=jpg&w=240)




![PostgreSQL238my $userid = "postgres";my $password = "pass123";my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })or die $DBI::errstr;print "Opened database successfullyn";my $stmt = qq(SELECT id, name, address, salary from COMPANY;);my $sth = $dbh->prepare( $stmt );my $rv = $sth->execute() or die $DBI::errstr;if($rv < 0){print $DBI::errstr;}while(my @row = $sth->fetchrow_array()) {print "ID = ". $row[0] . "n";print "NAME = ". $row[1] ."n";print "ADDRESS = ". $row[2] ."n";print "SALARY = ". $row[3] ."nn";}print "Operation done successfullyn";$dbh->disconnect();When the above given program is executed, it will produce the following result-Opened database successfullyID = 1NAME = PaulADDRESS = CaliforniaSALARY = 20000ID = 2NAME = AllenADDRESS = TexasSALARY = 15000ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-245-2048.jpg&f=jpg&w=240)
![PostgreSQL239ID = 4NAME = MarkADDRESS = Rich-MondSALARY = 65000Operation done successfullyUPDATEOperationThe following Perl code shows how we can use the UPDATE statement to update any recordand then fetch and display updated records from our COMPANY table-#!/usr/bin/perluse 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 successfullyn";my $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);my $rv = $dbh->do($stmt) or die $DBI::errstr;if( $rv < 0 ){print $DBI::errstr;}else{print "Total number of rows updated : $rvn";}$stmt = qq(SELECT id, name, address, salary from COMPANY;);my $sth = $dbh->prepare( $stmt );$rv = $sth->execute() or die $DBI::errstr;if($rv < 0){print $DBI::errstr;}while(my @row = $sth->fetchrow_array()) {print "ID = ". $row[0] . "n";](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-246-2048.jpg&f=jpg&w=240)
![PostgreSQL240print "NAME = ". $row[1] ."n";print "ADDRESS = ". $row[2] ."n";print "SALARY = ". $row[3] ."nn";}print "Operation done successfullyn";$dbh->disconnect();When the above given program is executed, it will produce the following result-Opened database successfullyTotal number of rows updated : 1ID = 1NAME = PaulADDRESS = CaliforniaSALARY = 25000ID = 2NAME = AllenADDRESS = TexasSALARY = 15000ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000ID = 4NAME = MarkADDRESS = Rich-MondSALARY = 65000Operation done successfullyDELETEOperationThe following Perl code shows how we can use the DELETE statement to delete any recordand then fetch and display the remaining records from our COMPANY table-#!/usr/bin/perl](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-247-2048.jpg&f=jpg&w=240)
![PostgreSQL241use 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 successfullyn";my $stmt = qq(DELETE from COMPANY where ID=2;);my $rv = $dbh->do($stmt) or die $DBI::errstr;if( $rv < 0 ){print $DBI::errstr;}else{print "Total number of rows deleted : $rvn";}$stmt = qq(SELECT id, name, address, salary from COMPANY;);my $sth = $dbh->prepare( $stmt );$rv = $sth->execute() or die $DBI::errstr;if($rv < 0){print $DBI::errstr;}while(my @row = $sth->fetchrow_array()) {print "ID = ". $row[0] . "n";print "NAME = ". $row[1] ."n";print "ADDRESS = ". $row[2] ."n";print "SALARY = ". $row[3] ."nn";}print "Operation done successfullyn";$dbh->disconnect();When the above given program is executed, it will produce the following result-Opened database successfullyTotal number of rows deleted : 1](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-248-2048.jpg&f=jpg&w=240)

![PostgreSQL243InstallationThe PostgreSQL can be integrated with Python using psycopg2 module. sycopg2 is aPostgreSQL database adapter for the Python programming language. psycopg2 waswritten with the aim of being very small and fast, and stable as a rock. You do not needto install this module separately because it is shipped, by default, along with Pythonversion 2.5.x onwards.If you do not have it installed on your machine then you can use yum command to installit as follows-$yum install python-psycopg2To use psycopg2 module, you must first create a Connection object that represents thedatabase and then optionally you can create cursor object which will help you in executingall the SQL statements.Pythonpsycopg2moduleAPIsFollowing are important psycopg2 module routines, which can suffice your requirement towork with PostgreSQL database from your Python program. If you are looking for a moresophisticated application, then you can look into Python psycopg2 module's officialdocumentation.S. No. API & Description1psycopg2.connect(database="testdb", user="postgres",password="cohondob", host="127.0.0.1", port="5432")This API opens a connection to the PostgreSQL database. If database isopened successfully, it returns a connection object.2connection.cursor()This routine creates a cursor which will be used throughout of your databaseprogramming with Python.3cursor.execute(sql [, optional parameters])This routine executes an SQL statement. The SQL statement may beparameterized (i.e., placeholders instead of SQL literals). The psycopg2module supports placeholder using %s signFor example:cursor.execute("insert into people values (%s, %s)", (who,age))48. PostgreSQL – Python Interface](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-250-2048.jpg&f=jpg&w=240)
![PostgreSQL2444curosr.executemany(sql, seq_of_parameters)This routine executes an SQL command against all parameter sequences ormappings found in the sequence sql.5curosr.callproc(procname[, parameters])This routine executes a stored database procedure with the given name. Thesequence of parameters must contain one entry for each argument that theprocedure expects.6cursor.rowcountThis read-only attribute which returns the total number of database rows thathave been modified, inserted, or deleted by the last last execute*().7connection.commit()This method commits the current transaction. If you don't call this method,anything you did since the last call to commit() is not visible from otherdatabase connections.8connection.rollback()This method rolls back any changes to the database since the last call tocommit().9connection.close()This method closes the database connection. Note that this does notautomatically call commit(). If you just close your database connectionwithout calling commit() first, your changes will be lost!10cursor.fetchone()This method fetches the next row of a query result set, returning a singlesequence, or None when no more data is available.11cursor.fetchmany([size=cursor.arraysize])This routine fetches the next set of rows of a query result, returning a list. Anempty list is returned when no more rows are available. The method tries tofetch as many rows as indicated by the size parameter.12cursor.fetchall()This routine fetches all (remaining) rows of a query result, returning a list. Anempty list is returned when no rows are available.](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-251-2048.jpg&f=jpg&w=240)


![PostgreSQL247SELECTOperationThe following Python program shows how we can fetch and display records from ourCOMPANY table created in the above example-#!/usr/bin/pythonimport psycopg2conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",host="127.0.0.1", port="5432")print "Opened database successfully"cur = conn.cursor()cur.execute("SELECT id, name, address, salary from COMPANY")rows = cur.fetchall()for row in rows:print "ID = ", row[0]print "NAME = ", row[1]print "ADDRESS = ", row[2]print "SALARY = ", row[3], "n"print "Operation done successfully";conn.close()When the above given program is executed, it will produce the following result-Opened database successfullyID = 1NAME = PaulADDRESS = CaliforniaSALARY = 20000.0ID = 2NAME = AllenADDRESS = TexasSALARY = 15000.0ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000.0ID = 4NAME = MarkADDRESS = Rich-Mond](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-254-2048.jpg&f=jpg&w=240)
![PostgreSQL248SALARY = 65000.0Operation done successfullyUPDATEOperationThe following Python code shows how we can use the UPDATE statement to update anyrecord and then fetch and display updated records from our COMPANY table-#!/usr/bin/pythonimport psycopg2conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",host="127.0.0.1", port="5432")print "Opened database successfully"cur = conn.cursor()cur.execute("UPDATE COMPANY set SALARY = 25000.00 where ID=1")conn.commitprint "Total number of rows updated :", cur.rowcountcur.execute("SELECT id, name, address, salary from COMPANY")rows = cur.fetchall()for row in rows:print "ID = ", row[0]print "NAME = ", row[1]print "ADDRESS = ", row[2]print "SALARY = ", row[3], "n"print "Operation done successfully";conn.close()When the above given program is executed, it will produce the following result-Opened database successfullyTotal number of rows updated : 1ID = 1NAME = PaulADDRESS = CaliforniaSALARY = 25000.0ID = 2NAME = Allen](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-255-2048.jpg&f=jpg&w=240)
![PostgreSQL249ADDRESS = TexasSALARY = 15000.0ID = 3NAME = TeddyADDRESS = NorwaySALARY = 20000.0ID = 4NAME = MarkADDRESS = Rich-MondSALARY = 65000.0Operation done successfullyDELETEOperationThe following Python code shows how we can use the DELETE statement to delete anyrecord and then fetch and display the remaining records from our COMPANY table-#!/usr/bin/pythonimport psycopg2conn = psycopg2.connect(database="testdb", user="postgres", password="pass123",host="127.0.0.1", port="5432")print "Opened database successfully"cur = conn.cursor()cur.execute("DELETE from COMPANY where ID=2;")conn.commitprint "Total number of rows deleted :", cur.rowcountcur.execute("SELECT id, name, address, salary from COMPANY")rows = cur.fetchall()for row in rows:print "ID = ", row[0]print "NAME = ", row[1]print "ADDRESS = ", row[2]print "SALARY = ", row[3], "n"](/image.pl?url=https%3a%2f%2fimage.slidesharecdn.com%2fpostgresqltutorial-180620080804%2f75%2fPostgresql-tutorial-256-2048.jpg&f=jpg&w=240)
