0% found this document useful (0 votes)
362 views

PostgreSQL Developer s Guide 1st Edition Ahmed - Download the ebook and start exploring right away

The document promotes instant ebook access through ebookgate.com, featuring various titles including 'PostgreSQL Developer's Guide' and 'Unlocking Android'. It provides links to download ebooks in multiple formats such as PDF, ePub, and MOBI. Additionally, it includes information about the authors and reviewers of the PostgreSQL Developer's Guide, highlighting their expertise and contributions.

Uploaded by

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

PostgreSQL Developer s Guide 1st Edition Ahmed - Download the ebook and start exploring right away

The document promotes instant ebook access through ebookgate.com, featuring various titles including 'PostgreSQL Developer's Guide' and 'Unlocking Android'. It provides links to download ebooks in multiple formats such as PDF, ePub, and MOBI. Additionally, it includes information about the authors and reviewers of the PostgreSQL Developer's Guide, highlighting their expertise and contributions.

Uploaded by

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

Instant Ebook Access, One Click Away – Begin at ebookgate.

com

PostgreSQL Developer s Guide 1st Edition Ahmed

https://ebookgate.com/product/postgresql-developer-s-
guide-1st-edition-ahmed/

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

PostgreSQL 9 6 High Performance 1st Edition Ibrar Ahmed

https://ebookgate.com/product/postgresql-9-6-high-performance-1st-
edition-ibrar-ahmed/

ebookgate.com

Unlocking Android a developer s guide 1st Edition Frank


Ableson

https://ebookgate.com/product/unlocking-android-a-developer-s-
guide-1st-edition-frank-ableson/

ebookgate.com

Common Warehouse Metamodel Developer s Guide 1st Edition


John Poole

https://ebookgate.com/product/common-warehouse-metamodel-developer-s-
guide-1st-edition-john-poole/

ebookgate.com

ActionScript Developer s Guide to Robotlegs 1st Edition


Joel Hooks

https://ebookgate.com/product/actionscript-developer-s-guide-to-
robotlegs-1st-edition-joel-hooks/

ebookgate.com
Magento PHP Developer s Guide 2nd Edition Allan Macgregor

https://ebookgate.com/product/magento-php-developer-s-guide-2nd-
edition-allan-macgregor/

ebookgate.com

Wittgenstein s Philosophical Investigations A Critical


Guide 1st Edition Arif Ahmed

https://ebookgate.com/product/wittgenstein-s-philosophical-
investigations-a-critical-guide-1st-edition-arif-ahmed/

ebookgate.com

Oracle9i PL SQL A Developer s Guide 1st Edition Bulusu


Lakshman (Auth.)

https://ebookgate.com/product/oracle9i-pl-sql-a-developer-s-guide-1st-
edition-bulusu-lakshman-auth/

ebookgate.com

Troubleshooting PostgreSQL 1st Edition Schonig

https://ebookgate.com/product/troubleshooting-postgresql-1st-edition-
schonig/

ebookgate.com

Advanced Oracle PL SQL Developer s Guide 2nd Edition


Saurabh K. Gupta

https://ebookgate.com/product/advanced-oracle-pl-sql-developer-s-
guide-2nd-edition-saurabh-k-gupta/

ebookgate.com
PostgreSQL Developer's Guide

Design, develop, and implement streamlined databases


with PostgreSQL

Ibrar Ahmed
Asif Fayyaz
Amjad Shahzad

BIRMINGHAM - MUMBAI
PostgreSQL Developer's Guide

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the authors, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2015

Production reference: 1230215

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78398-902-7

www.packtpub.com
Credits

Authors Copy Editors


Ibrar Ahmed Shivangi Chaturvedi
Asif Fayyaz Deepa Nambiar
Amjad Shahzad Adithi Shetty

Reviewers Project Coordinator


Daniel Durante Sanchita Mandal
Vinit Kumar
Proofreaders
Jean Lazarou
Ting Baker
Ľuboš Medovarský
Simran Bhogal

Commissioning Editor Paul Hindle


Julian Ursell
Indexer
Acquisition Editors Hemangini Bari
Richard Harvey
Production Coordinator
Greg Wild
Melwyn D'sa

Content Development Editor


Cover Work
Samantha Gonsalves
Melwyn D'sa

Technical Editor
Gaurav Suri
About the Authors

Ibrar Ahmed has over 15 years of experience in software development. He is


currently working as a software architect for a PostgreSQL-based company. He is an
open source evangelist. He has contributed features such as pg_migrator (now called
pg_upgrade) and Index Only Scans to PostgreSQL and has contributed to Google
Chromium projects such as platform-independent FTP implementations of the
Google Chrome browser, Chromium test framework enhancements, and porting of
listen_socket and telnet_server to Linux. He has a lot of experience in implementing
network protocols and writing Linux kernel modules. Apart from his professional
life, he delivers lectures at universities and reads books.

I would like to thank my loving parents for everything they did for
me. Personal time always belongs to family, and I did this in my
personal time, so thanks to my family for all the support. I would also
like to thank Mr. Richard Harvey, who encouraged me to write the
book, and my early age mentor, Mr. Mahmood Hussain, who helped
me a lot at the start of my professional career. It has been a really great
experience to work with Amjad Shahzad and Asif Fayyaz.

Asif Fayyaz is an open source technology lover and practitioner. He is currently


working as a senior software quality assurance engineer at a leading PostgreSQL-
based company. He has been learning and using PostgreSQL for the last 7 years.
His areas of interest are exploring PostgreSQL replication solutions and software
test automation solutions for desktop, web, and mobile applications. His future
endeavors include joining a sports channel for set-top box automation in Python.

Apart from his professional activities, he, along with his dedicated friends,
is keen to find ways that can make life easier for those who are facing the worst
living conditions.
His other passions include, but are not limited to, traveling to different places, trying
different cuisines, and reading books if somehow permitted by his loving family.

I would like to thank my loving parents, encouraging siblings,


friends, colleagues, my caring wife, and adorable daughter for not
only bearing with my busy schedule but motivating me as well to
get all this done.

I would also like to thank my colleagues, Ibrar Ahmed, for his


technical expertise and guidance, and Amjad Shahzad, for his
constant moral and technical support.

A thumbs up to Packt Publishing and notably to Richard, Gregory,


Azhar, and Samantha. You folks were great mentors and got the best
out of us. Undoubtedly a great experience!

Amjad Shahzad has been working in the open source software industry for the
last 10 years. He is currently working as a senior quality assurance engineer at
a leading PostgreSQL-based company, which is the only worldwide provider of
enterprise-class products and services based on PostgreSQL. Amjad's core expertise
lies in the areas of pg_upgrade, slony and streaming replication, Cloud database,
and database partitioning. His future endeavors include exploring PostgreSQL
replication solutions.

Apart from his professional activities, he is also involved in doing social activities that
involve helping people stand on their feet. In his free time, he likes to explore nature by
doing outdoor activities, including hiking, trekking, and nature photography.

I would like to say a special thank you to my parents, who have


been my source of inspiration since the start of my career. I would
also like to thank my wife for putting up with my late night writing
sessions. I would also like to thank Ibrar Ahmed, without whom this
book would not have been possible.

Finally, I want to thank the Packt Publishing staff, which includes


Richard, Gregory, Azhar, and Samantha for their continuous support.
About the Reviewers

Daniel Durante is an avid coffee drinker, motorcyclist, and rugby player. He has
been programming since he was 12 years old. He has been mostly involved with web
development from PHP-to-Golang while using PostgreSQL as his main choice of
data storage.

He has worked on text-based browser games that have reached over 1,000,000
players, created bin-packing software for CNC machines, and helped contribute
to one of the oldest ORMs of Node.js.

I would like to thank my parents, my brother, and friends who've


all put up with my insanity sitting in front of a computer day in
and day out. I would not have been here today if it wasn't for their
patience, guidance, and love.

Vinit Kumar is an autodidact engineer who cares about writing beautiful code that
scales well.

He has a good amount of experience in building social networks, multi-tenant systems,


content management systems, and embedded website infrastructure. His main areas
of interest are building performant systems, functional programming, and solving
problems that really matter.

Vinit is an active member of the free and open source software community and has
contributed to many projects, including Node.js, Python, and Django.

Prior to his current position, he worked as an application development consultant


and wrote applications for clients all over the world.
Vinit is a full-time developer who builds Socialschools (http://socialschools.nl),
which is a safe and secure social network for schools.

These days, he writes a lot of Django code along with frontend work on backbone
layers. He also works closely with the mobile team (iOS and Android) to ensure that
they get proper APIs and documentation support to get their job done.

He also helps his team write good maintainable code by doing code reviews
and following good practices such as Git, documentation, and tooling.

I would like to thank my family and fiance for having enough


patience to allow me to spend time on reviewing this book. Also,
I would like to thank the folks at Packt Publishing for being in
constant touch during the course of review.

Jean Lazarou started spending time with computers at the age of 15.
He has worked in various sectors, such as the medical industry, the manufacturing
industry, university education, and the multimedia world.

He mainly uses Basic, C/C++, Java, and Ruby to develop fat clients, web
applications, frameworks, tools, and compilers, often involving databases.

He has published his personal works on GitHub and some technical articles
on his blog.
Ľuboš Medovarský is an entrepreneur and open source C/C++, Pascal, Python,
and Java software developer with experience in GNU/Linux and OpenBSD
administration, configuration management, monitoring, networking, firewalls,
and embedded systems.

Discontented with today's fragmented and broken state of home automation and
the Internet of Things, he has developed hardware and software for the Whistler
automation smart house project, which aims to disrupt the market with platform
unification, privacy by design, device autonomy, built-in artificial intelligence,
and security – all in open source packages and affordable for the masses. Accelera
Networks s.r.o., the company he founded in 2006, develops custom software and
hardware applications as well as provides IT management services. Previously, he
was employed with Alcatel, Hewlett-Packard, AT&T, Erste Group, and a handful of
smaller companies. When he's not at work, the trekkie inside him dreams of space
colonization and the technological advancement of humanity. His favorite outdoor
activities include biking and flying in a glider.

I would like to thank my wife, Izabela, and daughter, Zoja, for their
patience and understanding and for the joy of life in their proximity.
www.PacktPub.com

Support files, eBooks, discount offers,


and more
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib
today and view 9 entirely free books. Simply use your login credentials for immediate access.
Table of Contents
Preface 1
Chapter 1: Getting Started with PostgreSQL 9
Writing queries using psql 10
Creating, altering, and truncating a table 11
Creating tables 12
Altering tables 13
Truncating tables 14
Inserting, updating, and deleting data from tables 15
Inserting data 15
Updating data 16
Deleting data 16
PostgreSQL's supported data types 18
PostgreSQL's operators and usage 20
Logical operators 20
Comparison operators 21
Mathematical operators 21
Constraints in PostgreSQL 22
Unique constraints 22
Not-null constraints 23
Exclusion constraints 24
Primary key constraints 24
Foreign key constraints 25
Check constraints 26
Privileges in PostgreSQL 26
Summary 27
Chapter 2: The Procedural Language 29
Why should you use PL/pgSQL? 30
Installing PL/pgSQL 30
Table of Contents

Understanding the structure of PL/pgSQL 31


Using comments in PL/pgSQL 33
Declaring variables in PL/pgSQL 34
Declaring function parameters 36
Declaring the %TYPE attribute 38
Declaring the row-type and record type variables 38
Statements and expressions 38
Using statements 39
The assignment statement 39
The call/return function 39
The RETURN expression 40
Exception handling statements 40
Compound statements 40
Expressions 41
Control structures 42
Conditional statements 42
IF-THEN 43
IF-THEN-ELSE 43
IF-THEN-ELSIF 44
Simple CASE 45
Searched CASE 47
Loops 48
The simple loop 48
The WHILE loop 49
The FOR loop 50
Exception handling 52
Native support for other procedural languages 55
PL/Python 55
Installing PL/Python 55
Writing functions in PL/Python 56
Handling arguments with PL/Python 56
Accessing the database with PL/Python 57
PL/Perl 58
Installing PL/Perl 58
Writing functions in PL/Perl 58
Handling arguments with PL/Perl 58
Accessing the database with PL/Perl 59
PL/Tcl 60
Installing PL/Tcl 60
Writing functions in PL/Tcl 61
Handling arguments with PL/Tcl 61
Accessing the database with PL/Tcl 62
Summary 63

[ ii ]
Table of Contents

Chapter 3: Working with Indexes 65


What is an index? 65
How to create an index 67
How to drop an index 68
Types of indexes 68
The single-column index 69
The multicolumn index 70
The partial index 72
The unique index 73
Explicitly creating an index using the CREATE INDEX command 74
The expression index 75
The implicit index 77
The concurrent index 77
Index types 77
The B-tree index 78
The hash index 78
The GiST index 79
The GIN index 79
Index bloating 81
Dump and restore 82
VACUUM 82
CLUSTER 82
Reindexing 83
Points to ponder 84
Summary 84
Chapter 4: Triggers, Rules, and Views 85
Understanding triggers 86
Tricky triggers 87
Creating triggers and trigger functions with PL/pgSQL 88
Creating triggers on views 94
Creating triggers in PL/Perl 96
Creating triggers in PL/Tcl 98
Creating triggers in PL/Python 100
PostgreSQL rules 102
Rules versus triggers – creating updateable views with rules 103
Understanding views 104
Materialized views 107
Creating materialized views 108
Summary 109

[ iii ]
Table of Contents

Chapter 5: Window Functions 111


Understanding window functions 111
The cume_dist() function 112
The row_number() function 113
The rank() function 114
The dense_rank() function 115
The percent_rank() function 116
The first_value() function 117
The last_value() function 118
The nth_value() function 118
The ntile() function 119
The lag() function 120
The lead() function 121
Summary 122
Chapter 6: Partitioning 123
Creating a table partition 123
Partitioning in PostgreSQL 124
Range partition 124
Creating the master table 124
Creating a range partition table 125
Creating an index on child tables 127
Creating a trigger on the master table 127
Enabling the constraint exclusion 129
Performing DML operations on a partition table 129
Handling the UPDATE and DELETE statements on a partition table 131
List partition 132
Summary 135
Chapter 7: Query Optimization 137
What is EXPLAIN? 138
Working with EXPLAIN ANALYZE 139
EXPLAIN VERBOSE 140
EXPLAIN pretty formats 140
Cost parameters 141
Sequential scans 142
Index scans 143
Index-only scans 144
Bitmap scans 144
Common Table Expressions 145
Joins 146
Nested loop joins 146
Merge joins 147

[ iv ]
Table of Contents

Hash joins 147


Hash semi and anti joins 148
Join ordering 149
Query planning 149
Window functions 150
Hints 151
Configuration parameters to optimize queries 153
Summary 155
Chapter 8: Dealing with Large Objects 157
Why large objects? 157
PostgreSQL large objects 158
Implementing large objects 159
Large objects in action 160
Manipulating large objects through the libpq client interface library 164
lo_create 165
lo_import 165
lo_export 165
lo_open 167
lo_write 168
lo_read 168
lo_close 168
lo_unlink 169
Summary 173
Chapter 9: Communicating with PostgreSQL Using LibPQ 175
Connecting and disconnecting to PostgreSQL 175
Using PQconnectdb 176
Using PQconnectdbParams 177
Using PQsetdbLogin 178
Using PQsetdb 178
Using PQfinish 181
Using PQreset 181
Establishing a connection asynchronously 182
Using PQconnectStartParams 182
Using PQconnectStart 182
Using PQconnectPoll 182
Using PQresetStart 183
Using PQresetPoll 183
Connection-supporting functions 183
Using PQconninfoParse 183
Using PQpingParams 184

[v]
Table of Contents

Executing a query 184


Using PQexec 184
Using PQexecParams 185
Executing prepared statements 185
Using PQprepare 185
Using PQexecPrepared 186
Retrieving data 189
Using PQntuples 189
Using PQnfields 189
Using PQfname 189
Using PQfnumber 190
Using PQftable 190
Using PQftablecol 191
Using PQfformat 191
Using PQftype 191
Using PQfmod 191
Using PQfsize 191
Using PQbinaryTuples 191
Using PQgetvalue 192
Using PQgetisnull 192
Using PQgetlength 192
Using PQnparams 193
Using PQparamtype 193
Using status functions 195
Using PQresultStatus 195
Using PQresStatus 196
Summary 196
Chapter 10: Embedded SQL in C – ECPG 197
Writing ECPG programs 197
Compiling an ECPG program 199
ECPG DECLARE sections 201
Connection using ECPG 201
Disconnecting using ECPG 202
Selecting a connection 202
Running SQL commands 203
Using host variables 205
Passing values to SQL 205
Getting values from SQL 205
Dynamic SQL 206

[ vi ]
Table of Contents

Error handling 207


How to set an error callback 207
Conditions 207
Actions 208
Using sqlca for error handling 210
Summary 212
Chapter 11: Foreign Data Wrapper 213
Creating foreign data wrappers 213
The basic components of foreign data wrappers 214
The C file 214
Makefile to compile the foreign data wrapper 216
A SQL file to map SQL functions to C functions 216
The control file to manage version and module path 217
Loading foreign data wrappers 217
Creating a server 217
Creating user mapping 218
Creating a foreign table 219
Using foreign data wrappers 219
Working with postgres_fdw 220
Working with file_fdw 220
Summary 221
Chapter 12: Extensions 223
Features of an extension 223
Creating extensions 225
Altering extensions 226
Dropping extensions 228
How to check available extensions 229
Additional supplied extensions 231
The adminpack extension 233
The chkpass extension 234
The citext extension 235
The cube extension 237
The dblink extension 239
The file_fdw extension 239
Other available extensions 239
Summary 239
Index 241

[ vii ]
Preface
PostgreSQL is the world's most advanced community-driven open source database.
The first open source version of PostgreSQL was released on 1st August 1996, an
combined effort between Bruce Momjian and Vadim B. Mikheev. Since then, major
releases have come annually, and all releases are available under its free and open
source software PostgreSQL license similar to the BSD and MIT licenses. Modern
technologies are emerging with new features on a regular basis, and PostgreSQL is
one of the fantastic examples of this happening, adding more robust features to cope
with the changing trends of technology. Developer and database administrators love
to use PostgreSQL because of its reliability, scalability, and continuous support from
the open source community.

PostgreSQL Developer's Guide is for database developers fascinated with learning


and understanding PostgreSQL from its release. A basic awareness of database
concepts is required to understand all of the PostgreSQL technical terms. As a result,
by reading this guide, you, as a reader, will be able to understand how applications
can be programmed with PostgreSQL, along with the core development concepts.
By the end of this book, you will have a solid base in the fundamental development
concepts and be able to develop database applications by leveraging the core
programming functionality of PostgreSQL.

The main objective of this book is to teach you in programming database applications
and custom programmatic functions. It is a practical tutorial book with an emphasis
to provide authentic world examples of how applications can be programmed with
PostgreSQL and grips on core development concepts and functions. By the end of
this book, we will show you how to write custom programming functions, which
extends the PostgreSQL database beyond its core capabilities. We wish you the best
of luck on your quest of seeking knowledge of PostgreSQL, where we hope that at
the end of this book, you will feel like you deserve a pat on the back for your efforts
in acquiring some hands-on expertise with PostgreSQL.
Preface

What this book covers


Chapter 1, Getting Started with PostgreSQL, explains the birth, present, and future
along with the evolution of PostgreSQL in terms of its features, maintainability, and
its immensely huge global following. This chapter will explain the concepts of DDL
(Data Description Language) and DML (Data Manipulation Language), and explain
how to write DDL and DML statements.

Chapter 2, The Procedural Language, encompasses the diversified features of PL/


pgSQL, native support for four languages, and extensibility for others. We will
skim through the description of PL/pgSQL by explaining its structure, declarations,
and verbal expressions. This chapter will shed light on using native support and
utilization examples of other procedural languages such as PL/Python, PL/Tcl,
and PL/Perl.

Chapter 3, Working with Indexes, is all about indexes, so expect to see a discussion
of the fundamental concepts of indexes, such as the kinds of indexes PostgreSQL
supports and the syntax to create them. The main story of this chapter is where to
utilize what kind of index and which condition it is best suited for. You can then
build different kinds of indexes in the warehouse database to explicate the practical
use of indexes.

Chapter 4, Triggers, Rules, and Views, consists of three sections: triggers, rules, and
views. The first section of this chapter will explain what a trigger is and how to
create triggers in PostgreSQL. The second part will deal with PostgreSQL rules.
There will be a focus on how the rules work by explaining their call, input, and the
results. The final third part will revolve around views and why they are important in
database design.

Chapter 5, Window Functions, discusses the power and concepts of window functions
in conjunction with aggregate functions. We will also cover the scope, structure,
and usage of window functions with examples. Another objective will be to acquire
a crystal clear understanding of the core of window functions and the data that is
processed with the help of frame, OVER, PARTITION BY, and ORDER BY clauses.
This chapter will also discuss the available built-in window functions, along with
custom ones.

Chapter 6, Partitioning, deals with table partitioning. Table partitioning in PostgreSQL


is implemented through table inheritance. In this section, there will be a brief overview
of partition in order to improve the performance of queries before moving on to its
implementation in PostgreSQL. The chapter also covers the list (that utilizes key
values) and range (that utilizes key columns) partitions.

[2]
Preface

Chapter 7, Query Optimization, is about query analysis and optimization.


Queries can be optimized utilizing indexes and hints and manipulating planner
parameters. As a reader, you will find this chapter very useful in utilizing and
optimizing your queries.

Chapter 8, Dealing with Large Objects, is about the handling of Large Objects (LO)
as there is a need to store large objects such as audio and video files. PostgreSQL
has support to manipulate these objects. The handling of sizably huge objects is
consummately different from the other objects such as text, varchar, and int. This
chapter will explain why we need to store Large Objects (LO) and how PostgreSQL
implements LO storage.

Chapter 9, Communicating with PostgreSQL Using LibPQ, explains how to write C


programs and connect and execute queries in the C language using libpq, which
is a PostgreSQL client library to communicate with the PostgreSQL server. In this
chapter, we will grip on the different ways of communication by utilizing libpq and
the utilization of all libpq functions. To extend our story of the warehouse database,
we will write a program to manipulate the data from the database.

Chapter 10, Embedded SQL in C – ECPG, covers all the syntax and utilization of
Embedded SQL to manipulate the data inside this code. Other than libpq, there
is an alternative to communicate in C code to a PostgreSQL server called ECPG.
Additionally, there will be coverage of how to compile the ECPG program, and
we will discuss the command-line options of the ECPG binary.

Chapter 11, Foreign Data Wrapper, covers how to explain the building blocks of the
foreign data wrapper and discusses how to utilize postgres_fdw and file_fdw to
manipulate foreign data. PostgreSQL introduces an incipient feature called the
foreign data wrapper. It's a template to write the module to access foreign data.
This is rigorously based in SQL/MED standards (SQL Management of External
Data). There are only two community maintained wrappers, postgres_fdw and
file_fdw, along with many externally maintained foreign data wrappers.

Chapter 12, Extensions, covers how to install and use available extensions in
PostgreSQL. PostgreSQL has features to install the loadable modules called
extensions. Instead of creating a bunch of objects by running SQL queries, an
extension, which is a collection of objects, can be created and dropped using
a single command. The main advantage of an extension is maintainability.
There are several extensions available.

[3]
Preface

What you need for this book


To get the most out of this book along with practical, hands-on experience,
you should practice the examples described. For this, you'll need the following:

• PostgreSQL installed through the installer, which is available at


http://www.postgresql.org/download/
• A basic text editor such as vim, gedit, or kate
• An OS Command-Line Interface (CLI) to run PostgreSQL binaries,
for example, psql, postmaster, or pg_ctl

Who this book is for


This book is for database developers who are interested in learning and
understanding PostgreSQL from scratch. Though you will need to know the basic
database concepts in order to understand the technical terms used throughout this
book, PostgreSQL is an open source and growing database community at, so having
a firm grasp on this will definitely increase your confidence in the domain of open
source databases.

You will be able to understand how applications can be programmed with


PostgreSQL, along with understanding the core development concepts. All the
examples will cover the functionality and syntax that is in compliance with the
latest versions of PostgreSQL, 9.3 and 9.4.

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"With the ALTER TABLE command, we can add, remove, or rename table columns."

A block of code is set as follows:


warehouse_db=# CREATE TABLE item
(
item_unique INTEGER PRIMARY KEY,
item_name TEXT,
item_price NUMERIC,
item_data TEXT
);

[4]
Preface

When we wish to draw your attention to a particular part of a code block,


the relevant lines or items are set in bold:
warehouse_db=# CREATE OR REPLACE FUNCTION getRecords()
RETURNS INTEGER AS $$
DECLARE
total INTEGER;
BEGIN
SELECT COUNT(*) INTO total FROM warehouse_tbl;
IF (total > 0) THEN
RETURN total;
ELSE
RAISE NOTICE 'table is empty';
END IF;
END;
$$ LANGUAGE plpgsql;

Any command-line input or output is written as follows:


$ createlang plpgsql warehouse_db -U postgres

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "The
team added core object-oriented features in Ingres and named the new version
PostgreSQL."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to [email protected],


and mention the book title via the subject of your message.

[5]
Preface

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things
to help you to get the most from your purchase.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to
have the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from http://www.packtpub.com/support.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at [email protected] with a link to the suspected


pirated material.

We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

[6]
Preface

Questions
You can contact us at [email protected] if you are having a problem with
any aspect of the book, and we will do our best to address it.

[7]
Getting Started with
PostgreSQL
Before starting our journey with SQL, allow me to quickly go through the history of
PostgreSQL. It all starts from the University of California, Berkeley, in the late 1970s
with the aim of developing a relational database possessing object-oriented features.
They named it Ingres. Later on, around the mid 1980s, a team of core developers led
by Michael Stonebraker from the University of California started work on Ingres.
The team added core object-oriented features in Ingres and named the new version
PostgreSQL.

This team was attached to the development of PostgreSQL for around 8 years.
During this time, they introduced object-oriented concepts, procedures, rules,
indexes, and types. In 1994, Andrew Yu and Jolly Chen replaced the Ingres-
based query language with the SQL query language. After this change, in 1995,
PostgreSQL was renamed Postgres95. In 1996, after entering the open source
world, Postgres95 went through multiple changes and new features such as Multi
Version Concurrency Control (MVCC), and built-in types were added. Over a
period of time, following the addition of new features and with the devoted work
of developers, Postgres95 achieved consistency and uniformity in code. They finally
renamed Postgres95 to PostgreSQL.

PostgreSQL is widely considered to be one of the most stable database servers


available today, with multiple features that include:

• A wide range of built-in types


• MVCC
• New SQL enhancements, including foreign keys, primary keys,
and constraints
• Open source code, maintained by a team of developers
Getting Started with PostgreSQL

• Trigger and procedure support with multiple procedural languages


• Extensibility in the sense of adding new data types and the client language

From the early releases of PostgreSQL (from version 6.0 that is), many changes have
been made, with each new major version adding new and more advanced features.
The current version is PostgreSQL 9.4 and is available from several sources and in
various binary formats.

We will be using PostgreSQL 9.4 throughout this book. So, let's


download and install it so that we can start our remarkable journey in
this book.

In this chapter, you will learn about the following topics:

• Writing queries using psql


• Creating, altering, and truncating a table
• Inserting, updating, and deleting data
• PostgreSQL-supported data types
• PostgreSQL-supported operators and usage
• Constraints and privileges in PostgreSQL

Writing queries using psql


Before proceeding, allow me to explain to you that throughout this book, we will use
a warehouse database called warehouse_db. In this section, I will show you how you
can create such a database, providing you with sample code for assistance. You will
need to do the following:

1. We are assuming here that you have successfully installed PostgreSQL and
faced no issues. Now, you will need to connect with the default database that
is created by the PostgreSQL installer. To do this, navigate to the default path
of installation, which is /opt/PostgreSQL/9.4/bin from your command
line, and execute the following command that will prompt for a postgres
user password that you provided during the installation:
/opt/PostgreSQL/9.4/bin$./psql -U postgres
Password for user postgres:

[ 10 ]
Chapter 1

2. Using the following command, you can log in to the default database
with the user postgres and you will be able to see the following on your
command line:
psql (9.4beta1)
Type "help" for help
postgres=#

3. You can then create a new database called warehouse_db using the following
statement in the terminal:
postgres=# CREATE DATABASE warehouse_db;

4. You can then connect with the warehouse_db database using the
following command:
postgres=# \c warehouse_db

5. You are now connected to the warehouse_db database as the user postgres,
and you will have the following warehouse_db shell:
warehouse_db=#

Let's summarize what we have achieved so far. We are now able to connect with the
default database postgres and created a warehouse_db database successfully. It's
now time to actually write queries using psql and perform some Data Definition
Language (DDL) and Data Manipulation Language (DML) operations, which we
will cover in the following sections.

In PostgreSQL, we can have multiple databases. Inside the databases, we can have
multiple extensions and schemas. Inside each schema, we can have database objects
such as tables, views, sequences, procedures, and functions.

We are first going to create a schema named record and then we will create some
tables in this schema. To create a schema named record in the warehouse_db
database, use the following statement:
warehouse_db=# CREATE SCHEMA record;

Creating, altering, and truncating a table


In this section, we will learn about creating a table, altering the table definition,
and truncating the table.

[ 11 ]
Getting Started with PostgreSQL

Creating tables
Now, let's perform some DDL operations starting with creating tables. To create
a table named warehouse_tbl, execute the following statements:
warehouse_db=# CREATE TABLE warehouse_tbl
(
warehouse_id INTEGER NOT NULL,
warehouse_name TEXT NOT NULL,
year_created INTEGER,
street_address TEXT,
city CHARACTER VARYING(100),
state CHARACTER VARYING(2),
zip CHARACTER VARYING(10),
CONSTRAINT "PRIM_KEY" PRIMARY KEY (warehouse_id)
);

The preceding statements created the table warehouse_tbl that has the primary key
warehouse_id. Now, as you are familiar with the table creation syntax, let's create a
sequence and use that in a table. You can create the hist_id_seq sequence using the
following statement:
warehouse_db=# CREATE SEQUENCE hist_id_seq;

The preceding CREATE SEQUENCE command creates a new sequence number


generator. This involves creating and initializing a new special single-row table
with the name hist_id_seq. The user issuing the command will own the generator.
You can now create the table that implements the hist_id_seq sequence using the
following statement:
warehouse_db=# CREATE TABLE history
(
history_id INTEGER NOT NULL DEFAULT nextval('hist_id_seq'),
date TIMESTAMP WITHOUT TIME ZONE,
amount INTEGER,
data TEXT,
customer_id INTEGER,
warehouse_id INTEGER,
CONSTRAINT "PRM_KEY" PRIMARY KEY (history_id),
CONSTRAINT "FORN_KEY"
FOREIGN KEY (warehouse_id)
REFERENCES warehouse_tbl(warehouse_id)
);

[ 12 ]
Chapter 1

The preceding query will create a history table in the warehouse_db database,
and the history_id column uses the sequence as the default input value.

In this section, we successfully learned how to create a table and also learned how
to use a sequence inside the table creation syntax.

Downloading the example code


You can download the example code files for all Packt books you
have purchased from your account at http://www.packtpub.com.
If you purchased this book elsewhere, you can visit http://www.
packtpub.com/support and register to have the files e-mailed
directly to you.

Altering tables
Now that we have learned how to create multiple tables, we can practice some
ALTER TABLE commands by following this section. With the ALTER TABLE command,
we can add, remove, or rename table columns.

Firstly, with the help of the following example, we will be able to add the phone_no
column in the previously created table warehouse_tbl:
warehouse_db=# ALTER TABLE warehouse_tbl
ADD COLUMN phone_no INTEGER;

We can then verify that a column is added in the table by describing the table
as follows:
warehouse_db=# \d warehouse_tbl
Table "public.warehouse_tbl"
Column | Type | Modifiers
----------------+------------------------+-----------
warehouse_id | integer | not null
warehouse_name | text | not null
year_created | integer |
street_address | text |
city | character varying(100) |
state | character varying(2) |
zip | character varying(10) |
phone_no | integer |
Indexes:
"PRIM_KEY" PRIMARY KEY, btree (warehouse_id)
Referenced by:

[ 13 ]
Getting Started with PostgreSQL

TABLE "history" CONSTRAINT "FORN_KEY"FOREIGN KEY


(warehouse_id) REFERENCES warehouse_tbl(warehouse_id) TABLE
"history" CONSTRAINT "FORN_KEY" FOREIGN KEY (warehouse_id)
REFERENCES warehouse_tbl(warehouse_id)

To drop a column from a table, we can use the following statement:


warehouse_db=# ALTER TABLE warehouse_tbl
DROP COLUMN phone_no;

We can then finally verify that the column has been removed from the table by
describing the table again as follows:
warehouse_db=# \d warehouse_tbl
Table "public.warehouse_tbl"
Column | Type | Modifiers
----------------+------------------------+-----------
warehouse_id | integer | not null
warehouse_name | text | not null
year_created | integer |
street_address | text |
city | character varying(100) |
state | character varying(2) |
zip | character varying(10) |
Indexes:
"PRIM_KEY" PRIMARY KEY, btree (warehouse_id)
Referenced by:
TABLE "history" CONSTRAINT "FORN_KEY" FOREIGN KEY
(warehouse_id) REFERENCES warehouse_tbl(warehouse_id) TABLE
"history" CONSTRAINT "FORN_KEY" FOREIGN KEY (warehouse_id)
REFERENCES warehouse_tbl(warehouse_id)

Truncating tables
The TRUNCATE command is used to remove all rows from a table without providing
any criteria. In the case of the DELETE command, the user has to provide the delete
criteria using the WHERE clause. To truncate data from the table, we can use the
following statement:
warehouse_db=# TRUNCATE TABLE warehouse_tbl;

We can then verify that the warehouse_tbl table has been truncated by performing
a SELECT COUNT(*) query on it using the following statement:
warehouse_db=# SELECT COUNT(*) FROM warehouse_tbl;
count
-------
0
(1 row)

[ 14 ]
Chapter 1

Inserting, updating, and deleting data


from tables
In this section, we will play around with data and learn how to insert, update, and
delete data from a table.

Inserting data
So far, we have learned how to create and alter a table. Now it's time to play around
with some data. Let's start by inserting records in the warehouse_tbl table using the
following command snippet:
warehouse_db=# INSERT INTO warehouse_tbl
(
warehouse_id,
warehouse_name,
year_created,
street_address,
city,
state,
zip
)
VALUES
(
1,
'Mark Corp',
2009,
'207-F Main Service Road East',
'New London',
'CT',
4321
);

We can then verify that the record has been inserted by performing a SELECT query
on the warehouse_tbl table as follows:
warehouse_db=# SELECT warehouse_id, warehouse_name, street_address
FROM warehouse_tbl;
warehouse_id | warehouse_name | street_address
---------------+----------------+-------------------------------
1 | Mark Corp | 207-F Main Service Road East
(1 row)

[ 15 ]
Getting Started with PostgreSQL

Updating data
Once we have inserted data in our table, we should know how to update it. This can
be done using the following statement:
warehouse_db=# UPDATE warehouse_tbl
SET year_created=2010
WHERE year_created=2009;

To verify that a record is updated, let's perform a SELECT query on the warehouse_
tbl table as follows:

warehouse_db=# SELECT warehouse_id, year_created FROM


warehouse_tbl;
warehouse_id | year_created
--------------+--------------
1 | 2010
(1 row)

Deleting data
To delete data from a table, we can use the DELETE command. Let's add a few records
to the table and then later on delete data on the basis of certain conditions:
warehouse_db=# INSERT INTO warehouse_tbl
(
warehouse_id,
warehouse_name,
year_created,
street_address,
city,
state,
zip
)
VALUES
(
2,
'Bill & Co',
2014,
'Lilly Road',
'New London',
'CT',
4321
);
warehouse_db=# INSERT INTO warehouse_tbl

[ 16 ]
Chapter 1

(
warehouse_id,
warehouse_name,
year_created,
street_address,
city,
state,
zip
)
VALUES
(
3,
'West point',
2013,
'Down Town',
'New London',
'CT',
4321
);

We can then delete data from the warehouse.tbl table, where warehouse_name is
Bill & Co, by executing the following statement:

warehouse_db=# DELETE FROM warehouse_tbl


WHERE warehouse_name='Bill & Co';

To verify that a record has been deleted, we will execute the following SELECT query:
warehouse_db=# SELECT warehouse_id, warehouse_name
FROM warehouse_tbl
WHERE warehouse_name='Bill & Co';
warehouse_id | warehouse_name
--------------+----------------
(0 rows)

The DELETE command is used to drop a row from a table, whereas


the DROP command is used to drop a complete table. The TRUNCATE
command is used to empty the whole table.

[ 17 ]
Getting Started with PostgreSQL

PostgreSQL's supported data types


PostgreSQL is very vast when it comes to supporting different data types. Apart
from existing data types, a user can add new data types in PostgreSQL. In order to
add new data types, a user can use the CREATE TYPE command. The following list
shows a number of built-in data types that are supported by PostgreSQL.

Let's go through all the supported data types one by one:

• bigint: This is a signed 8-byte integer, and it is represented as int8.


• bigserial: This is an auto incrementing 8-byte integer represented by
the serial8 keyword.
• bit[(n)]: This is a fixed length bit string and is represented by the
bit keyword.
• bit varying [(n)]: This is a variable length bit string and is represented
by the varbit keyword.
• boolean: This is a logical Boolean expression and has the true or false
value. It is represented by the bool keyword.
• box: This is a rectangular box on a plane and is represented by the box
keyword.
• bytea: This is binary data stored in the form of a byte array and is
represented by the bytea keyword.
• character [(n)]: This is a fixed length character string, and it is
represented by the char[(n)] keyword, where n represents the length
of the string.
• character varying[(n)]: This is a variable length character string, which is
represented by the varchar[(n)] keyword.
• cidr: This is used to store the IPv4 and IPv6 network addresses.
It is represented by the cidr keyword.
• circle: This is a circle on a plane, and it is represented by the
circle keyword.
• date: This is a calendar date, which includes the year, month, and day.
• double Precision: This is a floating-point number of 8 bytes. It is
represented by the float8 keyword.
• inet: This is used to store the IPv4 or IPv6 host addresses. The essential
difference between the inet and cidr data types is that inet accepts values
with nonzero bits to the right of the net mask, whereas cidr does not.
• integer: This is a signed 4-byte integer. It is represented by the int and
int4 keywords.

[ 18 ]
Chapter 1

• interval [fields] [(p)]: This is used to represent the time span.


• json: This is used to store the textual JSON data. Such data can also be stored
as text, but the JSON data types have the advantage of enforcing that each
stored value is valid according to the JSON rules. There are also assorted
JSON-specific functions and operators available for data stored in these
data types.
• jsonb: This is used to store binary JSON data.
• line: This is used to represent the infinite line in a plane.
• lseg: This is used to store data of a line segment on a plane.
• macaddr: This is used to store MAC addresses.
• money: This data type is used to store the currency amount.
• numeric[(p,s)]: This is used to store a numeric of selectable precision. It is
represented by the decimal [(p,s)] keyword. The s parameter is used to
represent the scale. The scale of a numeric is the count of decimal digits in the
fractional part, to the right of the decimal point. The p parameter is used to
represent precision. The precision of a numeric is the total count of significant
digits in the whole number, that is, the number of digits to both sides of the
decimal point. So, the number 23.5141 has a precision of 6 and a scale of 4.
• path: This is used to store a geomantic path on a plane.
• pg_lsn: This is used to store a PostgreSQL log sequence number.
• points: This is used to store a geometric point on a plane.
• polygon: This is used to store a closed geometric path on a plane.
• real: This is used to store a single precision, floating-point number of 4
bytes. It is represented by the float4 keyword.
• smallint: This is used to store a signed 2-byte integer. It is represented
by the int2 keyword.
• smallserial: This is used to store an auto incrementing 2-byte integer.
It is represented by the serial2 keyword.
• serial: This is used to store an auto incrementing 4-byte integer. It is
represented by the serial4 keyword.
• text: This data type is used to store a variable length character string.
• time[(p)][without time zone]: This is used to store the time of the day
without a time zone.
• time[(p)] with time zone: This is used to store the time of the day with a
time zone.

[ 19 ]
Getting Started with PostgreSQL

• timestamp [(p)][without time zone]: This is used to store the date and
time without a time zone.
• timestamp [(p)] with time zone: This is used to store date and time with
a time zone.
• time, timestamp, and interval: These data types accept an optional precision
value p that specifies the number of fractional digits retained in the seconds
field. By default, there is no explicit bound on precision. The allowed range of
p is from 0 to 6 for the timestamp and interval types.
• Tsquery: This is used to store a text search query.
• tsvector: This is used to store a text search document.
• txid_snapshot: This is used to store the user-level transaction ID snapshots.
• uuid: This is used to store universally unique identifiers.
• xml: This data type is served as storage for XML data.

PostgreSQL's operators and usage


As PostgreSQL has multiple operators, we will explain all of them in detail in
this section.

Logical operators
Logical operators are available in PostgreSQL, and these are:

• AND
• OR
• NOT

In PostgreSQL, the values of true, false, and null are used as the valued logic
system. For more detail, see the following truth table that shows how data types
a and b can result in different values when combined with the different AND and OR
logical operators:

a b a AND b a OR b
TRUE TRUE TRUE TRUE
TRUE FALSE FALSE TRUE
TRUE NULL NULL TRUE
FALSE FALSE FALSE FALSE
FALSE NULL FALSE NULL
NULL NULL NULL NULL

[ 20 ]
Chapter 1

You can then see from the following truth table how data type a can result in a
different value when used with the NOT logical operator:

a NOT a
TRUE FALSE
FALSE TRUE
NULL NULL

Comparison operators
In PostgreSQL, we have the following comparison operators, as shown in the
following table:

Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal
to
= Equal
<> or != Not equal

Mathematical operators
PostgreSQL also provides you with the following mathematical operators, as you can
see in the following table:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo (Remainder)
^ Exponentiation
|/ Square root
||/ Cube root
! Factorial
!! Factorial (prefix operator)

[ 21 ]
Getting Started with PostgreSQL

Operator Description
@ Absolute value
& Bitwise AND
| Bitwise OR
# Bitwise XOR
~ Bitwise NOT
<< Bitwise shift left
>> Bitwise shift right

Apart from the logical, comparison, and mathematical operators, PostgreSQL also
has operators for strings, binary strings, bit strings, date/time, geometric, network
address, and text search. Details of these operators are beyond the scope of this book
and can be studied in more detail in the PostgreSQL documentation available at
http://www.postgresql.org/docs/9.4/static/functions-string.html.

Constraints in PostgreSQL
PostgreSQL offers support for constraints and has coverage of multiple-level
constraints. Constraints are used to enforce rules on data insertion in tables.
Only data that complies with the constraint rules is allowed to be added to
the table. The constraints present in PostgreSQL are:

• Unique constraints
• Not-null constraints
• Exclusion constrains
• Primary key constraints
• Foreign key constraints
• Check constraints

We will explain all of these constraints one by one with supportive examples.
Let's start with the unique constraints.

Unique constraints
A unique constraint is a constraint that at the time of an insertion operation makes
sure that data present in a column (or a group of columns) is unique with regard
to all rows already present in the table. Let's create a few tables using unique
constraints in the following manner:

[ 22 ]
Chapter 1

warehouse_db=# CREATE TABLE tools


(
tool_id INTEGER UNIQUE,
tool_name TEXT,
tool_class NUMERIC
);

Alternatively, the same constraint can be declared at the end of all columns.
For instance, this can look like the following:
warehouse_db=# CREATE TABLE tools
(
tool_id INTEGER,
tool_name TEXT,
tool_class NUMERIC,
UNIQUE (tool_id)
);

When defining the unique constraints for a group of columns, all columns must be
listed separately using commas. Consider the following example:
warehouse_db=# CREATE TABLE cards
(
card_id INTEGER,
owner_number INTEGER,
owner_name TEXT,
UNIQUE (card_id, owner_number)
);

The preceding query will create the cards table with a unique constraint
implemented on the card_id and owner_number columns. Note that the unique
constraint is not applicable on null values. This means that in the cards table, two
records can have the same record if they have card_id and owner_number as null.

Not-null constraints
A not-null constraint makes sure that a column must have some values and a value
is not left as null. Drop the previously created tools table and create the tools table
again using this constraint using the following example:
warehouse_db=# CREATE TABLE tools
(
tool_id INTEGER NOT NULL,
tool_name TEXT,
tool_class NUMERIC
);

[ 23 ]
Getting Started with PostgreSQL

The preceding query will create a table with a not-null constraint on the tool_id
column. We can apply the not-null constraint on as many columns as we can.
Consider the following example:
warehouse_db=# CREATE TABLE tools
(
tool_id INTEGER NOT NULL,
tool_name TEXT NOT NULL,
tool_class NUMERIC
);

The preceding query will create the tools table with not-null constraints on tool_id
and tool_name.

Exclusion constraints
An exclusion constraint is used when comparing two rows on nominative columns
or expressions using the nominative operators. The result of the comparison will be
false or null. Consider the following example in which the conflicting tuple is given
the AND operation together:
warehouse_db=# CREATE TABLE movies
(
Title TEXT,
Copies INTEGER
);

Using the ALTER TABLE command, we get the following:


warehouse_db=# ALTER TABLE movies
ADD EXCLUDE (title WITH=, copies WITH=);

We will create an exclusion constraint above the ALTER TABLE command. The
conditions for a conflicting tuple are AND together. Now, in order for two records to
conflict, we'll use the following:
record1.title = record2.title AND record1.copies = record2.copies.

Primary key constraints


In PostgreSQL, we have support for primary key constraints, which is actually a
combination of not-null constraints and unique constraints, which means that for a
column to fulfill the primary key constraints limitation, it should be unique as well as
not null. Let's create a few tables using primary key constraints:
warehouse_db=# CREATE TABLE tools
(

[ 24 ]
Chapter 1

tool_id INTEGER PRIMARY KEY,


tool_name TEXT,
tool_class NUMERIC
);

You can also create a primary key constraint based on two columns. Consider the
following example:
warehouse_db=# CREATE TABLE tools
(
tool_id INTEGER,
tool_name TEXT,
tool_class NUMERIC,
PRIMARY KEY (tool_id, tool_name)
);

Foreign key constraints


Foreign key constraints state that the value in a column must be the same as
the value present in another table's row. This is for the sake of maintaining the
referential integrity between two interlinked tables. Consider the following examples
to understand the concept of foreign key constraints. We will create two tables, and
we will use the column of one table in the second table as a foreign key constraint:
warehouse_db=# CREATE TABLE tools
(
tool_id INTEGER PRIMARY KEY,
tool_name TEXT,
tool_class NUMERIC
);

This will create a table with primary key constraints:


warehouse_db=# CREATE TABLE tools_list
(
list_id INTEGER PRIMARY KEY,
tool_id INTEGER REFERENCES tools (tool_id),
list_name TEXT
);

In the preceding query, we created a table with the name of tools_list that has
a foreign key on the tool_id column with the tool_id reference column from the
tools table.

[ 25 ]
Getting Started with PostgreSQL

A table can have multiple parent tables, which means that we can
have more than one foreign key in a single table.

Check constraints
A check constraint lets you define a condition that a column must fulfill a Boolean
expression. Let's understand this with some examples:
warehouse_db=# CREATE TABLE tools
(
tool_id INTEGER PRIMARY KEY,
tool_name TEXT,
tool_class NUMERIC,
tool_quantity NUMERIC CHECK (tool_quantity > 0)
);

In the preceding query, we have created a table with check constraints on


tool_quantity to make sure that it must be greater than 0.

You can also give your constraints a more user-friendly name, so see the following
example in which we name the constraint positive_quantity:
warehouse_db=# CREATE TABLE tools
(
tool_id INTEGER PRIMARY KEY,
tool_name TEXT,
tool_class NUMERIC,
tool_quantity NUMERIC
CONSTRAINT positive_quantity CHECK
(tool_quantity>0)
);

Privileges in PostgreSQL
In PostgreSQL, multiple privileges are present for every object that is created.
By default, the owner (or a superuser) of an object has all the privileges on it.
In PostgreSQL, the following types of privileges are present:

• SELECT
• INSERT
• UPDATE

[ 26 ]
Discovering Diverse Content Through
Random Scribd Documents
African tribes, their native industry and enterprise yet almost
undisturbed by the busy excitement of civilization. Hence there may
fairly be drawn something like a sample of the real African native
character and condition. They live in families; among them the family
tie and the rights of property are regarded; conscience pronounces
criminal and offensive the same irregularities as are so regarded
among civilized peoples; in stature and physical condition they come
up to the best standards. I argue that the life and condition which
presents this state of things after isolation for thousands of years
from all we call civilized can scarcely be called evil or degraded.

Among these people, both pastoral and agricultural, are to be found


in progress the germs at least of all the useful arts—the procuring
and working of both iron and copper, pottery-making, the spinning
and weaving of cotton cloth, the very beautiful development of
plaiting of all kinds of vegetal fibers into string, rope, mats, baskets
and cloth; and where valuable materials and products are naturally
confined to particular localities, as is the case sometimes with oil,
salt, etc., it is manufactured and distributed. Too often are people
described as lacking in industry who are not the same as ourselves;
but it seems to me ridiculous that a man should be called lazy
because he has ample leisure between his busy times, who has made
with his own hands, from nature's absolutely raw material, his house,
his axe and hoe and spear, his clothing and ornaments, his furniture,
his corn mill, all things that he has, and who, though liable often in a
lifetime to have to repeat that whole process over again, has the
energy and enterprise to commence afresh. Too often have the same
people been called savage and bloodthirsty who, through all
experience and by all their traditions getting naturally to regard
unintroduced armed strangers as enemies, have the same desperate
energy to defend themselves and their own which, as displayed by
our own ancestral relatives, we love to term patriotism and courage.

In a fairly central position on this great central elevation is the


elongated basin surrounded by a mountain rim in the bottom of
which, in a long chasm, lies Lake Tanganyika, in a position alike so
central and so unique that I have termed it the Heart of Africa. Inside
the mountain basin rim, the rainfall all converges into Tanganyika;
outside, it all flows to the outer shores of the continent by the Nile,
the Congo or the Zambesi. Fifteen years ago the waters of Lake
Tanganyika, having very slowly gained upon the evaporation (the
then only means of carrying off its surplus) attained to the height of
the lowest gap in its rim and commenced to flow out, and thence its
surplus water ever since has found an exit and now forms part of the
Congo system. Tanganyika is 400 miles long and from 15 to 50 miles
in width, and is 2,700 feet above the sea.

To leave, however, this very rough general description of Africa at this


point would convey a wrong idea. We have described the verdant
slope from the coast, the terrace of flatter country, the central
elevation and its heart; now we may imagine a series of great ridges
and furrows and other radial features diverging from the heart of
Africa to its very shores, besides certain isolated ridges and peaks,
some of them snow-clad, and certain isolated depressions forming
lakes or swamps; first the three great furrows of the Nile, Zambesi
and Congo and the three great ridges formed by their dividing water-
sheds, and so on through fan-like expansions of rim or ridges and
furrows until the previously described concentric formation, although
still there, is considerably cut up.

The great central mountain mass, buttressed by its far-stretching


ridges, forms the backbone, from which, outward and downward, in
intricate articulations, extends the complicated bony skeleton of
Africa.

Set like sparkling jewels in its crevices and depressions, the great
lakes send forth the streams which, flowing through gaps in their
surrounding mountain barriers, rushing through narrow channels,
oozing slowly through elevated flats or bounding in beautiful
cascades over steep steps, and carrying the vitalizing fluid in every
direction through the length and breadth of Africa, form its system of
circulation.
Bordering the great lakes and clustering on the slopes, forests of
gigantic trees form the flesh and muscle of this great creation;
preserved in perpetual verdure wherever water constantly remains
and in long extending lines and network fringing the ever-winding
banks of the streams, and finally joining with the verdant belt of the
sea-coast to form the brilliant epidermis of the whole, and forming
background and filling to the network of these prominent features, in
broad concentric curves and in belts and patches, the more stunted
thorny growth, long grass, broad savanna and sandy plain, ever
changing in color and aspect.

The great new and beautiful world of Africa lies open before us;
250,000,000 intelligent and courageous people have become exposed
to the influence, for good or evil, of the civilized races. What shall we
do with it and them? Quite possible is it fairly and honestly so to
explore and deal with both country and people as to develop its
resources and benefit them, while adding to the world's treasury of
comfort-bringing products and human brotherhood the riches and the
friendship of a new continent; but it must be by peaceful and just
measures and by honest trade with wholesome wares.

II.

As a practical way of leading you in imagination to the heart of Africa,


and as indicating the circumstances and experience upon which my
observations on Africa are based, I shall describe one of my many
journeys.

In the year 1882 I had the honor to be leader of the largest


European expedition that has yet entered Africa, having in it, for
instance, 200 more men than the Emin Pasha relief expedition. There
were ten Europeans, all told, who represented survey and navigation,
medicine, carpentry, blacksmithing, and other specially selected talent
for the purpose of exploration and civilization, as well as those
specially devoted to the teaching of Christianity, which was the
ultimate aim of all. We entered Africa from the village of Saadani, on
the eastern coast, opposite Zanzibar, our destination being the shores
of Lake Tanganyika at Ujiji.

To make not only our progress sure, but work and residence at our
destination safe and possible in such a land, we had stores of
groceries, medicines, tools and clothing, and a large quantity of calico
and other cloth, which forms the currency of the country, for the
purchase of supplies and payment of wages to porters, servants and
workmen.

The special locality to be worked being the countries surrounding


Lake Tanganyika, to which that extensive and beautiful inland sea
gives access, we carried with us also, for its navigation, a sailing boat
built of steel, of the form of a sea-going life-boat, and constructed in
small sections and pieces for transport. This boat I designed myself.
Six of the sections were to travel on specially constructed light carts,
drawn by African natives, and the rest, in small pieces, were to be
carried by the porters in the ordinary way.

The mode of travel was walking, except when now and then an
invalid was carried in a hammock. The method of transport was by
means of native porters, hundreds of whom devote themselves to
this work. They are paid $5 per month as wages, payable at Zanzibar
on their return to the coast, less such advance in kind as they may
draw from their leader along the road. In addition, they get a regular
allowance of two yards of white calico per seven days, each man, as
barter with which to obtain food.

The organization and start of such a party took some time, and
parties of from 100 to 300 were dispatched along the road as things
were ready, until, when I started with the final rear guard, we had on
the road over 900 of these porters, with their headmen and petty
officers, all under complete organization.
The first start of the boat-section carts was the scene of apparent
disaster. The men, wild with excitement and uniting their shouts with
those of onlookers, were beyond all restraint for the moment, and as
they rounded a sharp turn to get out of the village of Saadani, over
went the carts, one after the other, on their sides; and it was some
time before I could train the men to steer more carefully or to move
gently down a declivity. In time, however, the whole thing worked
well. The fore compartment of the boat, going stem first, often forced
its own way through masses of brush and creeper, helping to clear
the way for the narrower sections, whose carts insinuated themselves
through surprisingly small gaps. The men themselves were most
zealous in the service, and as we emerged from lengthy stretches of
jungle, ascended steep river banks, or jolted whole days over rugged
stony places unharmed, we made up our minds that, these carts
would "go anywhere." In twenty days we reached Upwapwa, 200
miles from the coast, and joined an advance party awaiting us; and
after a few days rest and reorganization, we started once more
westward.

The first village beyond, in the country of Ugogo, was thirty miles off.
The first day was a comparatively easy march to a watering place,
but the next two days gave us tough work. The thick, tangled, thorny
scrub became quite dense, and for those two days we had to cut our
way through it foot by foot. Hour after hour the twang of the sword-
bayonets and the thud of the axes were almost the only sounds to be
heard till the train of carts moved slowly on as the way was opened.
Toward evening of the second day we followed a narrow pass along
the side of a rocky river bed, stout, inflexible trunks and branches
here projecting into our path. On some of these ebony bars the axes
resounded as on an anvil, and they yielded only to the more patient
saw. As the sun descended we began to flag, but help was at hand;
for a party coming back to us from the camp ahead with food and
water, we picked up strength and spirit and reached camp late in the
evening.
The level plains of Ugogo, which here represent the flat, open step or
terrace to which I have referred in the general description of Africa,
enabled us to make a week or so of splendid and comfortable
marches. Ugogo passed, there lay before us the much-dreaded
wilderness, so-called, of the Magunda-Mkali, separated from Ugogo
by a steep, rocky ascent, which we could only tackle one cart at a
time, and we soon came to a point so rugged with broken rocks that
we could proceed no further; but the sections were unlashed, the
carts taken to pieces, and all handed or dragged across the difficult
place and put together again beyond. Over the scrubby, rugged hill
and dale of Magunda-Mkali, without inhabitants, 20 to 25 miles a day
was often made; every man knew the necessity of pushing on for
food and water, and the danger, from wild beasts or wandering
highwaymen, of lagging in the rear.

On, on, went the novel train, through weary miles of forest, across
the scorched plain, rattling over the hard sun-baked footprints of the
elephant and rhinoceros; on through grassy glades where the nimble
antelope bounded, scared out of our path, and the zebra and giraffe
were startled by the rattling of these strange disturbers of their
solitude; on still, through miles of swamp, with its croaking legions;
on through scenes of surpassing beauty, bright flowers and gleaming
birds and butterflies; on past the bleaching bones of other travelers
waylaid or exhausted, till the sun creeps up high overhead and eager
glances are cast at green spots where water once had been; on, till
the pace grows slow with weariness and thirst, and still on, till it
revives again as the welcome messenger from the front appears in
sight with water or the camp-fires tell of food and rest.

Completing this difficult section of the journey and mounting to the


beautiful forests and numerous villages of Unyamwesi, we had
arrived upon the central heights of the continent, which everything
around us bespoke its best part; the clearer, more healthy air, the rich
land, the open forests, the numerous and industrious people, all
spoke eloquently of a better and brighter state of things in the
interior of Africa than on its outside.
At Urambo we elicited the pleased surprise of our friend, the famous
chief Mirambo. Said Mirambo, laying his hand emphatically on one of
the boat sections, "This boat and these carts are mine, and all
Unyamwesi is yours." It was his way of expressing sympathy and
admiration of what he considered to be a very wonderful enterprise,
and we left him pondering more deeply than ever on the doings of
the "white men."

The rains were now at hand and the country rich and verdant; we
hastened on with all speed possible to enable us to cross the
Malagarasi river before it should be too swollen. Emerging from
elevated forest land to a view of the valley of the river, it appears like
a vast level expanse of harmless grass, but the swift river is flowing
in the bottom. The toll required by the natives being paid, we
descended to the river through the thick grass. We crossed the river
in tiny dug-out or bark canoes managed by the natives. One old man,
a leader among these ferrymen, we had especial cause to notice; we
called him "the old admiral." He wore a curious skull cap apparently
made of bladder, and presented a most odd appearance. To him we
paid a special fee of propitiation for the boatmen. As we proceeded
down toward the river the first sign of it among the long grass was
quiet shallow water on the path; this grew deeper and deeper as we
walked on until we were immersed to the armpits, the grass rising
avenue-like overhead. We emerged upon a small island or rising
ground, and the river proper was before us. On this little eminence
stood "the old admiral" superintending all. The porters and their
ordinary loads all crossed in the usual way, two or three at a time in
the little canoes. The two large carts, with the bow and stern
compartments of the boats, were floated along the watery avenue by
the buoyancy of their tank-like loads; the others came, sections and
carts, separately. The fare for each load was one yard of calico, but
when the carts appeared there was general astonishment among the
ferrymen, who showed signs of clearing off altogether; "the old
admiral" alone was unmoved; his stolid countenance showed no sign,
but a deep bass growl, "Eight yards, eight yards for these!" expressed
at once his nonchalance and his determination; and eight yards we
had to pay. All was safely got over in a day. Two of the bark canoes
were lashed together with poles across, and one section or one cart
at a time laid on top, and thus all was carried across.

Obstacles which further back would have been regarded as great


hindrances were now made little of; success seemed assured to all,
and the men even began to rehearse their triumphal entry into Ujiji.
One more difficult river, the Lusugi, we had to cross. We reached its
banks, down a rocky descent, late one night in a heavy fall of rain.
We waited an hour or two next morning till the river had somewhat
subsided, and then commenced work. Two or three volunteers swam
across with a stout rope, which was then hauled tight across the
stream. The porters, holding this rope in one hand, slowly but surely
made their way across. Then the carts and sections were attached to
a block running on the rope, and so, carefully attended by two or
three men, were floated over in safety.

Ujiji was now only a few marches ahead. The view of the lake was
caught at last, a narrow strip of its waters gleaming in the sun in the
distance, and next morning we slowly marched into Ujiji in a compact
body. The boat was duly launched and has now been for years at
work on Lake Tanganyika in the cause of civilization and Christianity.

The completion of this journey, however, was but the commencement


of a still larger enterprise in the region reached. Stations were
established among the tribes on the lake shores; a larger vessel, with
steam power, was built and launched on the lake, and a substantial
mission was established and is still at work at a point which is only
400 miles from that point on the Congo river accessible to the
steamers of the missions there.

All the work I have described was done at the expense of the London
Missionary Society.
REPORT OF COMMITTEE ON EXPLORATION IN
ALASKA.
(Accepted April 3, 1891.)

Washington, D. C., April 3, 1891.

TO THE BOARD OF MANAGERS OF THE NATIONAL GEOGRAPHIC SOCIETY,


Washington, D. C.

Gentlemen: Your Committee, instructed "to consider the advisability


of further Alaskan exploration by the Society this year and if deemed
advisable, to consider and report upon ways and means for
accomplishing it," respectfully submit the following report:

The general question of desirability has been decided affirmatively by


the Board of Managers; it therefore is inferred that the question of
advisability may be taken as involved in that of ways and means.

In outlining a plan of work, concerning which such inquiry is to be


made, it has been found necessary, in the lack of formulated opinion
by the Society, to make assumptions as to what should be its purpose
and policy in undertaking exploration. It is assumed tentatively that
in order best to further the object for which the Society is organized,
namely, "the increase and diffusion of geographic knowledge," the
aim in exploration should be not so much to promote the growth of
science as to diffuse a general interest in geographic work in its
several departments, and, adhering to the principle of attractiveness,
to increase the sum of knowledge by discovery and by the addition of
general and elementary facts rather than by detailed investigation,
for appreciation of which scientific training must be presupposed. It is
furthermore believed that the policy of the Society should be to invite
coöperation, offering opportunity at the same time for special study
in related sciences; to effect the organization and devise the plan,
and itself to take part directly in field work only so far as may be
necessary to initiate and promote it.

Your Committee find that apparently it will be practicable, with


coöperation, for the Society to extend this year the exploration work
of last year in the vicinity of Mount St. Elias. Specifically it is
recommended that the plan be to determine directly, from a long
base line near the coast, the height of the mountain, to ascend it, to
observe systematically the unique phenomena of physical geography
of the Malaspina glacier from Icy bay to the initial point of last year's
exploration, and to explore the Seward glacier to its head if deemed
advisable after the ascent of the peak.

In view of the fact that it is the purpose of the Coast and Geodetic
Survey to carry the international boundary survey into this region
within one or two years, it is considered inexpedient for the Society
to undertake extended topographic work. It is, however, submitted,
as a principle which this Society should emphasize in projecting
exploration, that facts of physical geography have minimum value
and may lead to false conclusions unless correlated through their
space relations; and it is recommended that the expedition aim
always to employ such means as may be practicable for making
record of its course and of its observations in approximate geometric
relation to surroundings.

Conditional offers of coöperation have been made by the Revenue


Marine Service, the Geological Survey, the Coast and Geodetic
Survey, and the Century Company of New York. Transportation from
Seattle to Alaska and return, it is thought, may be secured on the
steamer Corwin, and that vessel's commander, Captain Hooper, has
expressed a desire to extend his coast-line exploration of last year by
making a survey of Disenchantment bay. The Geological Survey offers
to detail Mr. Russell to conduct the expedition, and to bear the
expense of a number of field hands and of their equipment. The
Coast and Geodetic Survey has expressed a desire to aid, if
practicable, by beginning boundary work in the same field this year,
and incidentally to do other surveying with special relation to the
work of the expedition. The Century Company offers to send an artist
experienced in Alpine work and to pay the greater portion of his
expenses. The opportunity for study of the fauna and flora of the
region it is thought should not be neglected.

The cost to the Society, wholly in items of field expense otherwise


unprovided for, which may be considered as the cost of enabling the
combination to work as one organization, is estimated at $500.
The expedition should leave Seattle in the latter part of May, aiming
to reach Icy bay by the first of June, and field work should close by
the end of September.

Your committee consider further exploration in Alaska by the Society


this year as practicable, and recommend that the proposed
expedition be authorized, and that Mr. Russell be at once invited to
organize and conduct it, under the auspices of the Society.

Very respectfully,
G. K. GILBERT,
EVERETT HAYDEN,
WILLARD D. JOHNSON,
Committee on Exploration.

NOTES.

La Carte de France, dite de l'Etat Major, par M. J. Collet. Paris, 1887.


8vo, pp. 92, with 4 plates.—This pamphlet describes the great "Staff
Map" of France, recently completed, giving its history, the methods
employed in the field and office work, the contents of the map, and
the means of representing the various features therein described.
The scale of the map is 1:80,000. Relief is represented by hachures,
for drawing which approximate contour lines have been located, but
these are not otherwise used. A great variety of cultural features are
shown, many of which are ephemeral, and which contribute to the
overloading of the map with details. Moreover, as the time which has
ordinarily elapsed between the survey and the issuance of the work
in printed form is ten or twelve years, most of this culture has
become not only of no value but misleading by the time it is
published.

The account of the organization and methods by which the map has
been produced is of special interest. The primary triangulation upon
which it is based is one of the most elaborate and accurate ever
executed in any country. No expense has been spared in this
direction. Within this triangulation is a secondary triangulation, also
very elaborate, from the stations of which numerous additional
points are cut in, or located by unclosed triangles. All this work is of
the highest order of excellence, being infinitely more accurate than
the map requires. With this, however, the accuracy appears to end.
The detail consists of the map, or the map proper, little more than a
compilation of commune cadastral plans. These were fitted to the
triangulation points and to one another, a process which appears to
have been by no means easy of satisfactory accomplishment. This
adjustment having been completed, the culture was brought up to
date of survey and a survey was made of the relief features by the
use of such inferior instruments as the clinometer compass and
chain.

The principal and obvious criticism upon such work is that it is top-
heavy. The triangulation is far more elaborate than is required, while
the provision for making the map itself is by no means comparable
with it: it is as far below the requirements of the scale as the
triangulation is above it.

This leads up to a broader proposition, which may be stated thus:


That the general tendency of surveying organizations is in the
direction illustrated by that of the "French Staff." Organized originally
for map-making, they progress little by little in the direction of
devoting their energies to geodetic work, while at the same time the
topographic work proper, for which they were created, is belittled
and neglected. As a consequence the latter depreciates in quality
and diminishes in quantity; the main purpose of the organization is
lost, and a mere means becomes the ultimate end of the work. This
tendency should be recognized in map-making organizations. The
weakness of our modern maps is seldom in the primary control. It is
easy to do triangulation of sufficient accuracy for the control of maps
upon such scales as that above considered, little knowledge or
experience being required beyond that gained at our engineering
schools; while the more accurate triangulation, generally known as
geodetic work, requires merely better instruments, more time, and
more experienced observers.

The weak features of maps are generally the details, the part of the
work that, strange to say, is usually relegated to the lowest grade of
professional men. This weakness consists in an insufficiency of minor
locations for the control of the sketch and in unfaithful sketching. It
is the sketching that requires the most careful attention and the best
and most experienced men. The instrumental portion of the work is
the least difficult; the artistic portion, or sketching, is the most
difficult. It would seem more logical and would doubtless produce
better results to reverse the usual order of promotion and place the
topographer above the triangulator. Moreover, the triangulation
should be regarded as merely a means for the correction of the
sketching, and it should be required only that it be of sufficiently
high grade to meet this condition. The minor locations should be
sufficiently numerous and well distributed to fully control and correct
the sketching; and finally the sketching should be as faithful a
representation of the topography as is consistent with the necessary
generalization of the surface features.

H. G.

Polar Regions.—The Societe de Geographie of Paris in its


Proceedings publishes the following communication from M. Ch.
Rabot on the new Danish expedition engaged in the exploration of
the eastern coast of Greenland, under the command of Lieutenant
Ryder, of the royal Danish navy. The expedition has in view the
examination of the unknown coast between Franz-Josef fiord, in
latitude 73°, and the most northerly point reached by Commander
Holm and Lieutenant Garde, about latitude 66°. Lieutenant Ryder
left Copenhagen June 7, 1891, in the Norwegian whaler Hekla, which
had been chartered by the Danish government. The first ice was met
on the 20th, in latitude 68° 12', longitude 13° 05' west. Unable to
pass through the pack to the Greenland shore after several
attempts, the ship proceeded northward, and in the vicinity of Jan
Mayen made soundings and successful dredgings. Several attempts
to reach the coast of Greenland were made from the 75th parallel
southward, but without success up to July 2, when the Hekla was in
latitude 71° 31', longitude 6° 30' west. Since that date there has
been no direct news, but on July 26, in latitude 72° 40', longitude
14° 25' west, the English whaler Active saw the Hekla a few miles to
the northeast, heading to the south-southwest. On August 2 the
Active, in latitude 71° 40', approached within 12 miles of the coast,
and on August 20, in 70° 30', was within 7 miles of the mainland. In
both instances the intervening sea was free of ice. The English
captain believes that the Hekla made the eastern coast in about 71°
30'. The Hekla is provisioned for the winter, and there is a prospect
of marked success by the Danish officers in their undertaking.

The Crossing of Tibet.—The explorations of Mr. Rockhill in Tibet and


his renewed attempt to reach Lassa, the "holy city" of that country,
creates an unusual interest for Americans in the account of the
crossing of Tibet by M. G. Bonvalot, Prince Henri d'Orleans, and P.
Dedeken, published in the last Bulletin of the Paris Geographical
Society.

Six days' journey from Moscow brought the party through Russia
and Turkestan to Kouldja (45° N., 41° W.), in extreme western
Mongolia. Having obtained authority from the Chinese governor of
the province to proceed, the party, aggregating 15 in number, left
that place September 12, 1889, with Batang, China, as an objective
point. On October 5, after a journey of about 450 miles, during
which they crossed the Thian-chan ("heavenly") mountains by Narat
pass, they camped at Korla, near Bagratch-koul. Here they were
warned that they could proceed no farther, and the governor of Ili
sent an order to arrest them. The mandarin and other local
authorities did not, however, actively oppose their departure, which
took place during the night of October 10, the party then consisting
of 20 horsemen and 40 pack-animals. On October 28 they reached
Kara-douran, the western end of Lob-nor. A side trip by d'Orleans
and Dedeken to Lob-nor proved it to be no longer a lake but a series
of swamps and sandy islands, with the water nowhere more than
four feet deep. Meantime Bonavolot accumulated supplies and
replaced from the hardy Mongols the more timid among their camp-
followers, the party being reduced to seven, with a few extra men
for a short distance.

Quitting Tcharkalik on November 17, they followed the route taken


by Carey; but on the advice of the natives they resolved after
crossing the Altyn-tagh to go directly southward instead of turning
eastward, and thus to attempt a new route, on which they were
beset by the usual physical discomforts attendant on travel at great
elevations. On these mountain ranges they saw only wild sheep,
blue hares, wild horses, crows and partridges. On December 5, just
south of a large salt lake (Ouzoun-tchour), they, saw a caravan of
Kalmouk pilgrims returning from Lassa by an unknown route, which
they refused to make known, and decided to temporarily abandon
their idea of reaching Batang and instead to go direct to Lassa by
retracing the caravan trail. From this point (about 38° 30' N. and 87°
30' W.) they proceeded directly southward. The region penetrated
was unknown, the winds violent the entire day, the desert treeless
and without water, the route lined with the carcasses of camels and
their drivers, the only fuel the dung of wandering yaks or caravan
camels, and the trail so indistinct that at times they marched by
compass. The elevation gradually and steadily increased to 15,000
and even 16,500 feet; the mountain fever became worse, the storms
more violent and continuous, and the temperature ranged from 7°
(–14° C.), with wind, at midday to 30° below zero (–33° C.) at night.
One by one their horses and camels died, and also an old Kirgese
who followed them. Extensive glaciers were passed, from which flow
on the one side the Salouen and Mekong into Indian ocean, and on
the other the Yang-tse to China sea. On January 8, 1890, they
skirted a large unfrozen lake named Montcalm, 50 miles long by 12
miles wide, and on January 14 traversed Duplex pass, 20,000 feet
elevation. On the 31st they finally ran across a man, a wild Tibetan,
small, thin, with enormous lips, long knotted hair, clothed in
sheepskin and armed with a saber and flint-lock gun, whom they
called "appa" (father); he knew neither Chinese nor Mogul, but
spoke Tibetan of which the travelers knew scarcely a dozen words.
Other Tibetans, with flocks of sheep, soon appeared and sold them
mutton, a little salt, and rancid butter, and then followed on
horseback for fifteen days without losing sight of the explorers.
Often they were counseled in Mogul by those in authority to turn
back.

In the middle of February they reached lake Nam-tso ("heaven"), or


Tengri-nor, a large frozen body of water. Out of 40 camels only 15
remained, and, of 20 horses but one survived; three of the party of
seven were in desperate state of health, while all were worn out and
almost without provisions. They were finally obliged to stop in a
mountain pass of the Nindjin-tangla, which led directly to Lassa,
then not more than sixty miles distant. On February 17 the Tibetan
authorities sent a large party to meet them and ask their intentions.
Mistaken for Russians, it took 13 days to convince the authorities
that they were French. They received presents from the authorities
and obtained costumes from Lassa, but found it impossible to visit
the "holy city." After 49 days of negotiation, on April 5, provided with
arms, provisions and horses, and also a safe permit from the Talia
lama to cross Tibet to Batang by an unknown route, they started
eastward, on a course nearly parallel to and north of Salouen river,
reaching Sô and once again seeing houses on April 15. They arrived
at Batang early in June, their route some distance west of it having
joined the Imperial highway from Pekin to Lassa over which l'Abbe
Huc travelled. From Tatsien-lou, where the French Tibetan mission is
located, their route turned southward to Red river, which was
reached, at Manhoau, on September 21, when their journey
practically ended, as Hanoai was reached two days later.

An excellent map of the itinerary, by Prince Henri, accompanies the


article.

A. W. G.

Third Annual Report on the Statistics of Railways in the United States


to the Interstate Commerce Commission, for the year ending June
30, 1890: Washington, Government Printing Office, 1891 (advance
copy, pp. 1–100).—This pamphlet, by Professor Henry C. Adams, is
issued in advance of the full report, which is promised to comprise
about 875 pages. It contains a summary, digest and discussion of
the full report.

It appears that the total railroad mileage on June 30, 1890, was
163,597, an increase of 5,838 miles during the year. The increase
came mainly from southeastern and western states. This mileage
was owned by 1,797 distinct corporate bodies, but entirely controlled
in one way or another by only 747 companies. To illustrate the
extent to which consolidation of railroad property has gone, it may
be stated that 47.5 per cent of all railroad mileage is controlled by
but forty companies, and that 65.4 per cent is controlled by seventy-
five companies. The greatest mileage controlled by one company is
6,053, operated by the Southern Pacific company.
The total capital and bonded debt of railroad companies was
$9,871,378,389, or $60,340 per mile. Stock and bonds were about
equal in amount. Mr. Adams estimates the value of railroad property
by capitalizing at 5 per cent the dividends and interest on bonds paid
during the year, reaching as a result $6,627,461,140, or about 2/3 of
the nominal capital and bonded debt. The justice of this method may
fairly be questioned. A comparison of the ruling prices of dividend-
paying stocks with the rate per cent of the dividend shows that 5 per
cent stocks are above par and that 4 per cent stocks average nearly
par. Moreover, it is well known that many railroads are built and
operated, not for their own immediate earnings but to give value to
other property of the companies, notably to lands, from the sale or
lease of which the companies derive profits. Again, many railroads
are built, not for present but for future profits, after they shall have
induced settlement of their territory; and, furthermore, numerous
branch roads have been built as defensive measures to prevent
rivals from occupying territory; and in many cases earnings are used
in betterment of property instead of distributing it as dividends. In
all these cases the roads have value, although they are not paying
dividends.

Taking all these matters into account, it does not appear that the
railroad stocks of the country have, collectively, been watered to any
great extent, if by "watering" is meant expanding nominal values
above actual values.

Concerning dividends paid on stock, Mr. Adams presents a table


showing that 63.76 per cent of all stock paid no dividends; that but
6.47 per cent paid less than 4 per cent; that 25.26 per cent paid
from 4 to 8 per cent, the remainder paying above 8 per cent. It
appears that in the northeastern states much the highest dividends
were paid, while in the west, so far as dividends are concerned, the
stockholders have to wait for future developments.

The total passenger mileage for the year was 11,847,785,617, a


slight increase over the previous year. The total freight mileage was
76,207,047,298, an increase of nearly 10 per cent over that of the
previous year. The gross earnings of the year were $1,051,877,632,
and the operating expenses $692,093,971, leaving as the income
from operations $359,783,661. The income from other sources was
$126,767,064, and the total deductions from income were
$384,792,138, leaving as the net income $101,758,587, out of which
there was paid as dividends on stock $89,688,204.

The magnitude of the railway interests of the country is set forth in


the above enormous figures. It is still further emphasized by the fact
that nearly three-quarters of a million men are in the employ of this
industry. Assuming that each such employé supports two others
besides himself, it is seen that the railroad interest supports two and
a quarter millions, or more than one thirtieth of the inhabitants of
the country.

H. G.

INDEX.

ABBE, CLEVELAND, cited on isostaths, 43


—, Record of communication by, viii
— — — discussion by, viii

ABORIGINES of South America, 7

ACADEMY OF SCIENCES, Russian, Quotation from records of, 212

ADAMS, HENRY C., Review of report on railway operations by, 255


ADELUNG, J. C., Geographic work by, 211
—, Quotation from, on de l'Isle's map, 212, 213, 214

ADMIRALTY BAY, 56

AFRICA, Area of, 32


—, Conquest and division of, 31
—, Natural divisions of, 238
—, Population of, 238
— (The Heart of); E. C. Hore, 238

AGASSIZ GLACIER, Ascent of, 147


— — named, 73

AGE of St. Elias range, 175

ALASKA (An expedition to Mount St. Elias,); I. C. Russell, 53


—, Boundaries of, 237
—, Early works concerning, 206
—, Report of committee on exploration in, 248

ALLEN, JAMES, cited on isostaths, 44

ALPENSTOCKS, Necessity for, 165

ALPINE glaciers, 176, 180

ALTON, EDMUND, Contribution to exploration fund by, 75

ALVORD, H. E., Remarks by, at field meeting, x

AMAZON, Discovery of the, 11


—, Sketch of the, 4

AMENDMENT to by-laws proposed, xii


ANDES, General description of the, 1

ANEMOMETER formula devised by C. F. Marvin, 49

ANGOT, A., Reference to work of, 46

ANTIQUITIES of Peru, 8

ARCHANGELICA, Mention of, 89, 114

ARGENTINE REPUBLIC, Sketch of, 19

ASIA, Exploration in, 253

ATREVIDA, Mention of the, 63, 92, 105

AURIFEROUS sands from Yakutat bay, 196

AVALANCHES, 145, 155

BAIE DE MONTI, 56
— named by La Pérouse, 60

BAKER, MARCUS, cited on early eclipses, 220


— — — Mount St. Elias, 232
—, Explorations by, 70, 72
—, Reference to bibliography by, 58
—, Record of discussion by, viii, ix

BASE LINE, Measurement of, 86

BATES, H. W., Quotation from, on South America, 29

BEAR, Meeting with the, 94, 109


BELCHER, SIR EDWARD, Explorations by, 68, 69

BELL, A. GRAHAM, Contribution to exploration fund by, 75

BELL, CHARLES J., Contribution to exploration fund by, 75

BELLIN, S., Geographic work by, 207

BERING BAY, Mention of, 56

BERING'S first voyage (The cartography and observations of); A. W.


Greely, 205
— provisions, 219

BERING, VITUS, Explorations by, 58

BERG, M., cited on thunderstorms, 44

BIEN, MORRIS, Contribution to exploration fund by, 75

BIGELOW, F. H., Record of communication by, viii

BIRNIE, JR., ROGERS, Contribution to exploration fund by, 75

BLACK GLACIER, Brief account of, 101, 104

BLODGETT, J. H., Record of discussion by, vii, ix

BLOSSOM ISLAND, Description of, 113, 122

BOARD ON GEOGRAPHIC NAMES, Institution of the, 39

BONVALOT, G., Crossing of Tibet by, 253

BOURSIN, HENRY, Mention of, 79


BRAZIL, Revolution in, 36
—, Sketch of, 17

BROKA, GEORGE, Explorations by, 73, 74

BUACHE, PHILLIPE, Geographic work by, 208

BUCHAN, ALEX., Reference to work of, 44

BUCKLE, SIR HENRY, Quotation from, on tropical America, 29

BY-LAWS, Proposed amendment to the, xii

CAMP hands, 166

CARPENTER, Z. T., Contribution to exploration fund by, 75

CARTOGRAPHY, Discussion of, 251


— (The) and Observations of Bering's First Voyage; A. W. Greely,
205

CASCADE GLACIER named, 144

CENTURY COMPANY, Offer of coöperation by, 249

CHAIX HILLS named, 73

CHARIOT, THE, Mention of, 140

CHATHAM, Mention of, 66

CHERIKOF, ALEXEI, Explorations of, 58

CHINA, Exploration in, 253


CHRISTIE, J. H., Member of expedition, 76
—, Work of, 82, 83, 84, 96, 103, 112, 113, 123, 162

CLIMATE of South America, 6

CLOVER, RICHARDSON, Contribution to exploration fund by, 75

COAST AND GEODETIC SURVEY, Explorations by, 70, 72


—, Offer of coöperation by, 249

COLD WAVES, Prediction of, 51

COLLETT, M. J., Review of map described by, 250

COMMERCE of South America, 17, 19, 23

COOK, CAPTAIN JAMES, Explorations of, 58

CORDILLERAS of South America, 1

CORWIN CLIFFS, Mention of, 138

CORWIN (The) in Disenchantment bay, 100


— Return of the, 163

CREVASSES, 181, 182


— at Pinnacle pass, 130

CROSS SOUND, visited by Vancouver's expedition, 67

CRUMBACK, J. H., Member of expedition, 76


—, Work of, 96, 103, 122, 125, 129, 131, 135, 137

CURTIS, W. E., Record of communication by, xi

CYCLONES, Theory of, 42


DAGELET, M., Mention of, 60

DAHLGREN, ULRICA, Presentation of flag by, viii

DALL, W. H., cited on Bering's first voyage, 205


— — — — supplies, 219
— — — de l'Isle's map, 218
— — — early eclipses, 219
— — — Mount St. Elias, 231
—, Explorations by, 70, 72
—, Quotation from, on map by de l'Isle, 207
—, Record of discussion by, vii
—, Reference to bibliography by, 58

DALTON, JOHN, Glacier named for, 98


—, Mention of, 73

D'ANVILLE, M., cited on early eclipses, 229

DAVIS, W. M., Reference to meteorologic review by, 47

DEDEKEN, P., Crossing of Tibet by, 253

DEFINITION of formations in St. Elias region, 167

DEKALB, COURTENAY, Record of communication by, ix

DE L'ISLE, J. N., Authenticity of map by, 211, 213


—, Geographic work by, 206
—, Map by, 207
—, Quotation from, on eclipses, 220

DE MONTI BAY, Arrival at, 79


DESCUBIERTA (The), Mention of, 63

DESENGAÑO BAY, named by Malaspina, 63

DEVIL'S CLUB (Panax horridum), Mention of, 95, 115

DIGGES' SOUND, named by Vancouver, 68

DILLER, J. S., Contribution to exploration fund by, 75

DIP at Pinnacle pass, 140

DISCOVERY (The), Mention of, 66

DISENCHANTMENT BAY, Canoe trip in, 96, 103


—, Last view of, 163
—, Mention of, 56
—, visited by Malaspina, 63, 64

DIXON, CAPTAIN GEORGE, Explorations of, 60, 62

DOBBINS, J. W., Contribution to exploration fund by, 75

DOBBS, ARTHUR, Geographic work by, 210

DOME PASS named, 146

DONEY, L. S., Member of expedition, 76


—, Work of, 85, 158, 159, 160, 162

D'ORLEANS, PRINCE HENRI, Crossing of Tibet by, 253

DOUGLASS, E. M., Record of discussion by, xi

DOUGLASS, CAPTAIN, Explorations of, 62


DRY BAY, Mention of, 55

DU BOCAGE, BARBIC, Geographic work by, 211


—, Quotation from, on de l'Isle's map, 216

DU FOSSE, E., cited on early publications, 207

DU HALDE, PÈRE, Geographic work by, 206


—, Quotation from, on de l'Isle's map, 218

EARTHQUAKES, South American, 2

ECLIPSES, Early, observed in Kamshatka, 219, 229

EIFFEL TOWER, Use of, in meteorology, 46

EKHOLM, NILS, cited on isostaths, 43

ELDORADO, Early accounts of, 14

ELECTION of officers, xii

ESPERANZA, POINT, Mention of, 14, 85

EXPEDITION (An) to Mount St. Elias, Alaska; I. C. Russell, 53

EXPLORATION in Alaska, 248

FARENHOLT, LIEUTENANT COMMANDER O. F., of U. S. S. Pinta, 79

FAULTED pebble from Pinnacle pass, 171

FAULTS 83, 136


—, Thrust, in Hitchcock range, 118
FERREL, WILLIAM, cited on cyclones, 42
—, Reference to treatise by, 47

FINLEY, J. P., Reference to work of, 50

FLORAL HILLS, Brief account of, 105, 108

FLORAL PASS, Brief account of, 105, 108, 110

FORMATIONS of the St. Elias region, 167

FOSSILS at Pinnacle pass, 140


—, Description of, of Yakutat system, 172

FOSSIL PLANTS, Report on, by Lester F. Ward, 199, 200

FRANCE, Review of Staff Map of, 250

GABBRO on the Marvine glacier, 123

GALIANO, DON DIONISIO ALCALA, Mention of, 63

GALIANO GLACIER, Visit to, 89, 90

GANNETT, HENRY, Contribution to exploration fund by, 75


—, Instructions from, 194
—, Review of railway operations by, 255
— — — Staff Map of France, by, 250

GANNETT, S. S., Computation of height of Mount St. Elias, by, 235

GEOGRAPHIC names, Board of, 39

GEOGRAPHY of the Air; A. W. Greely, 41


— — — Land; H. G. Ogden, 31

GEOLOGICAL SURVEY, Acknowledgments to, 40


—, Instructions from, 192, 193, 194
—, Offer of coöperation by, 249

GEOLOGY of the St. Elias region, 167, 174, 190, 191

GILBERT, G. K., Instructions from, 192, 193


—, Record of discussion by, vii, ix, x
—, Remarks by, at field meeting, x
—, Report on exploration by, 250

GLACIAL currents, 187


— river, Example of, 183
— streams, 183, 184

GLACIER BAY, Mention of, 67

GLACIERS in Disenchantment bay in 1792, 64, 65, 97


— — — — observed by Malaspina, 64, 65
— — — — — — Puget, 67, 68
— of the St. Elias region, 176
— west of Icy bay, 187

GRACE, M. P., Financial operations by, 23

GREELY, A. W., Contribution to exploration fund by, 75


— cited on Mississippi floods, 38
—; Geography of the Air, 41
—, Note by, on polar regions, 252
— — — — the crossing of Tibet, 253
—, Record of communication by, vii, viii, xi
—; The Cartography and Observations of Bering's First Voyage, 205

GUIANA, Sketch of, 13

GUIDES, Use of, in ascending St. Elias, 166

GUYOT GLACIER named, 73

HAENKE, D. TADEO, Haenke island named for, 65

HAENKE ISLAND, Condition of, when seen by Malaspina, 63, 64, 65, 97
—, Visit to, 96, 103
HANN, JULIUS, cited on cyclones, 42

HAYDEN, DR. F. V., Glacier named for, 108

HAYDEN, EVERETT, Contributions to exploration fund by, 75


—, Record of discussion by, vii, viii, ix, xi
—, Report on exploration by, 250

HAYDEN GLACIER, Brief account of, 108, 110, 111

HAYS, J. W., Contribution to exploration fund by, 75

HAZEN, H. A., Reference to work of, 50

HEIGHT and position of St. Elias, 189, 190

HENDRIKSEN, REVEREND CARL J., Mention of, 80, 83

HILL, S. A., Reference to work of, 47

HILL, R. T., Record of communication by, xiii

HITCHCOCK, PROFESSOR EDWARD, Range named for, 112

HITCHCOCK RANGE, Brief account of, 112


— from Pinnacle pass, 133
—, Structure of, 118

HOOGEWERFF, J. A., Record of communication by, viii

HOOPER, CAPTAIN C. L., Navigation of Disenchantment bay, 56, 100


—, Offer of coöperation by, 249

HORE, E. C., Record of address by, vii


—; The Heart of Africa, 238
HOSMER, E. S., Contribution to exploration fund by, 75
—, Return of, 83
—, Volunteer assistant, 76

HOTCHKISS, JED., Record of communication by, ix, x


—, Testimonial to, x

HOVEY, H. C., Record of communication by, x


—, Remarks by, at field meeting, x

HOWELL, E. E., Record of communication by, xi

HUBBARD, GARDINER G., Contribution to exploration fund by, 75


—, Glacier named for, 99
—, Presentation of flag by, viii
—, Record of presidential address by, xiii
—; South America: Annual address by the President, 1

HUBBARD GLACIER, Brief description of, 99

HUC, L'ABBÉ, Route of, 255

HUGHES, T. MCKENNEY, Record of communication by, x

ICEBERGS, Formation of, 98, 99, 101, 102


— in Yakutat bay, Description of, 87

ICE tunnels, 184

INCAS of Peru, 8

INDIANS of South America, 7

INSTRUCTIONS from Geological Survey, 192, 193, 194


— — National Geographic Society, 194

IRVING, PROFESSOR R. D., Mountain named for, 144

JACKSON, SHELDON, Record of discussion by, ix

JOHNSON, J. B., Record of discussion by, xi

JOHNSON, WILLARD D., Contribution to exploration fund by, 75


—, Exploration planned by, 75
—, Record of discussion by, vii
—, Report on exploration by, 250

JUDD, J. G., Contribution to exploration fund by, 75

JUNGEN, ENSIGN C. W., Mention of, 81

KAMSHATKA, Cartography of, 217


—, Early eclipses in, 219, 229

KERR, MARK B., assigned as an assistant, 75


— cited on Mount St. Elias, 39
—, Report on topographic work by, 195

KHANTAAK ISLAND, Village on, 79, 80

KING, HARRY, Contribution to exploration fund by, 75

KNAPP, HON. LYMAN E., Mention of, 79

KNIGHT ISLAND, Scenery near, 83


— named by Puget, 68

KNOWLTON, F. H., Report on fossil plants, 199


LA BOUSSOLE, Mention of, 58

LAKE CASTANI named, 73

LAKELETS on the glaciers, 119, 120

LAKES, Abandoned beds of, near Blossom island, 116

LA PÉROUSE, J. F. S., Explorations of, 58, 60

LA PLATA river, Sketch of, 5

LASSA, recent attempt to reach, 253

L'ASTROLABE, Mention of, 58

LAURIDSEN, P., cited on early maps, 215


—, Quotation from, on de l'Isle's map, 217

LEACH, BOYNTON, Contribution to exploration fund by, 75

LEVÉE systems of the Mississippi, 37

LIBBEY, PROFESSOR WILLIAM, Explorations by, 72, 73

LINDENKOHL, A., Computation of position of Mount St. Elias by, 235

LINDSLEY, W. L., Member of expedition, 76


—, Work of, 122, 131, 134, 135, 139, 144, 149, 150, 153, 157, 158,
164

LITTLEHALES, G. W., Record of discussion by, vii

LITUYA BAY, Mention of, 55


Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like