Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
PostgreSQL Development Essentials
PostgreSQL Development Essentials

PostgreSQL Development Essentials: Advanced querying, data modeling and performance tuning

eBook
$31.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

PostgreSQL Development Essentials

Chapter 1.  Advanced SQL

This book is all about an open source software product, a relational database called PostgreSQL. PostgreSQL is an advanced SQL database server, available on a wide range of platforms. The purpose of this book is to teach database developers the fundamental practices and techniques to program database applications with PostgreSQL.

In this chapter, we will discuss the following advanced SQL topics:

  • Creating views
  • Understanding materialized views
  • Creating cursors
  • Using the GROUP BY clause
  • Using the HAVING clause
  • Understanding complex topics such as subqueries and joins

Creating views

A view is a virtual table based on the result set of an SQL statement. Just like a real table, a view consist of rows and columns. The fields in a view are from one or more real tables in the database. Generally speaking, a table has a set of definitions that physically stores data. A view also has a set of definitions built on top of table(s) or other view(s) that does not physically store data. The purpose of creating views is to make sure that the user does not have access to all the data and is being restricted through a view. Also, it's better to create a view if we have a query based on multiple tables so that we can use it straightaway rather than writing a whole PSQL again and again.

Database views are created using the CREATE VIEW statement. Views can be created from a single table or multiple tables, or another view.

The basic CREATE VIEW syntax is as follows:

CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE [condition];

Let's take a look at each of these commands:

  • CREATE VIEW: This command helps create the database's view.
  • SELECT: This command helps you select the physical and virtual columns that you want as part of the view.
  • FROM: This command gives the table names with an alias from where we can fetch the columns. This may include one or more table names, considering you have to create a view at the top of multiple tables.
  • WHERE: This command provides a condition that will restrict the data for a view. Also, if you include multiple tables in the FROM clause, you can provide the joining condition under the WHERE clause.

You can then query this view as though it were a table. (In PostgreSQL, at the time of writing, views are read-only by default.) You can SELECT data from a view just as you would from a table and join it to other tables; you can also use WHERE clauses. Each time you execute a SELECT query using the view, the data is rebuilt, so it is always up-to-date. It is not a frozen copy stored at the time the view was created.

Let's create a view on supplier and order tables. But, before that, let's see what the structure of the suppliers and orders table is:

CREATE TABLE suppliers
(supplier_id number primary key,
Supplier_name varchar(30),
Phone_number number);
CREATE TABLE orders
(order_number number primary key,
Supplier_id  number references suppliers(supplier_id),
Quanity number,
Is_active varchar(10),
Price number);
CREATE VIEW active_supplier_orders AS 
SELECT suppliers.supplier_id, suppliers.supplier_name  orders.quantity, orders.price 
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_name = 'XYZ COMPANY'
And orders.active='TRUE';

The preceding example will create a virtual table based on the result set of the SELECT statement. You can now query the PostgreSQL VIEW as follows:

SELECT * FROM active_supplier_orders;

Deleting and replacing views

To delete a view, simply use the DROP VIEW statement with view_name. The basic DROP VIEW syntax is as follows:

DROP VIEW IF EXISTS view_name;

If you want to replace an existing view with one that has the same name and returns the same set of columns, you can use a CREATE OR REPLACE command.

The following is the syntax to modify an existing view:

CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name(s)
WHERE condition;

Let's take a look at each of these commands:

  • CREATE OR REPLACE VIEW: This command helps modify the existing view.
  • SELECT: This command selects the columns that you want as part of the view.
  • FROM: This command gives the table name from where we can fetch the columns. This may include one or more table names, since you have to create a view at the top of multiple tables.
  • WHERE: This command provides the condition to restrict the data for a view. Also, if you include multiple tables in the FROM clause, you can provide the joining condition under the WHERE clause.

Let's modify a view, supplier_orders, by adding some more columns in the view. The view was originally based on supplier and order tables having supplier_id, supplier_name, quantity, and price. Let's also add order_number in the view.

CREATE OR REPLACE VIEW active_supplier_orders AS 
SELECT suppliers.supplier_id, suppliers.supplier_name  orders.quantity, orders.price,order. order_number 
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_name = 'XYZ COMPANY'
And orders.active='TRUE';;
Left arrow icon Right arrow icon

Key benefits

  • Write complex SQL queries and design a robust database design that fits your application's need
  • Improve database performance by indexing, partitioning tables, and query optimizing
  • A comprehensive guide covering the advanced PostgreSQL concepts without any hassle

Description

PostgreSQL is the most advanced open source database in the world. It is easy to install, configure, and maintain by following the documentation; however, it’s difficult to develop applications using programming languages and design databases accordingly. This book is what you need to get the most out of PostgreSQL You will begin with advanced SQL topics such as views, materialized views, and cursors, and learn about performing data type conversions. You will then perform trigger operations and use trigger functions in PostgreSQL. Next we walk through data modeling, normalization concepts, and the effect of transactions and locking on the database. The next half of the book covers the types of indexes, constrains, and the concepts of table partitioning, as well as the different mechanisms and approaches available to write efficient queries or code. Later, we explore PostgreSQL Extensions and Large Object Support in PostgreSQL. Finally, you will perform database operations in PostgreSQL using PHP and Java. By the end of this book, you will have mastered all the aspects of PostgreSQL development. You will be able to build efficient enterprise-grade applications with PostgreSQL by making use of these concepts

Who is this book for?

If you are a PostgreSQL developer with a basic knowledge of PostgreSQL development and you’re want deeper knowledge to develop applications, then this book is for you. As this book does not cover basic installation and configurations, you should have PostgreSQL installed on your machine as a prerequisite.

What you will learn

  • Write more complex queries with advanced SQL queries
  • Design a database that works with the application exactly the way you want
  • Make the database work in extreme conditions by tuning, optimizing, partitioning, and indexing
  • Develop applications in other programming languages such as Java and PHP
  • Use extensions to get extra benefits in terms of functionality and performance
  • Build an application that does not get locked by data manipulation
  • Explore in-built db functions and data type conversions
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 26, 2016
Length: 210 pages
Edition : 1st
Language : English
ISBN-13 : 9781783989003
Category :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Sep 26, 2016
Length: 210 pages
Edition : 1st
Language : English
ISBN-13 : 9781783989003
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 165.97
PostgreSQL High Availability Cookbook
$60.99
PostgreSQL Development Essentials
$43.99
Learning PostgreSQL
$60.99
Total $ 165.97 Stars icon

Table of Contents

11 Chapters
1. Advanced SQL Chevron down icon Chevron up icon
2. Data Manipulation Chevron down icon Chevron up icon
3. Triggers Chevron down icon Chevron up icon
4. Understanding Database Design Concepts Chevron down icon Chevron up icon
5. Transactions and Locking Chevron down icon Chevron up icon
6. Indexes and Constraints Chevron down icon Chevron up icon
7. Table Partitioning Chevron down icon Chevron up icon
8. Query Tuning and Optimization Chevron down icon Chevron up icon
9. PostgreSQL Extensions and Large Object Support Chevron down icon Chevron up icon
10. Using PHP in PostgreSQL Chevron down icon Chevron up icon
11. Using Java in PostgreSQL Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Half star icon Empty star icon Empty star icon Empty star icon 1.5
(2 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 50%
1 star 50%
D. Sauer Aug 29, 2023
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
While I'm not going to completely disagree with PK's review, I'm also going to point out that it doesn't know the story of this book. I'm one of the technical reviewers listed in the foreword of the book. There are three things one needs to know about this specific book. First, there are two authors instead of one because the first author just disappeared from Earth after writing a few chapters from the outline. I was asked to complete the book, but for reasons unknown (I suspect "cost of labor"), someone else did it instead. Fine, I'm not holding a grudge over that at all; anyone can self-publish if they want. Second, the critique of grammar in the book is fair, but oh man if you had seen the first drafts... The grammatical editors at Pakt are truly amazing. Unfortunately, they sometimes also change the meaning of the sentences while they're fixing the original grammar. Seriously, the grammatical editors rewrote an easy 80% of this book. And that brings me to the third point - the process. The way this works is: the author writes up a draft, the draft goes to the reviewers, the reviewers add comments, the author integrates those comments at their discretion, then that integrated result goes to the publisher's editors to clean up and arrange. So the reviewers listed in the front of the book, like me, can theoretically be amazing (not that I'm necessarily "amazing", but I do have sufficient competence to manage these simple examples). That doesn't mean their input is necessarily getting to the published book unless 1) the author integrates the feedback *and* 2) the editors later don't mangle things to make the examples appear incorrect.I can assure anyone who's reading this that the examples *all* were verified as working properly and fit the way I interpreted the author when I handed my notes back. Don't send all of the names from the book down with the ship; some of us only got paid in the form of a free book for our time (which was significant on this one), and had no control of the final content. :D
Amazon Verified review Amazon
PK Jan 18, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This book consists of a random selection of semi-literate re-hashes of the user manual and Wikipedia pages, along with a few code examples, most of which are broken.The authors jump from one topic to the next, never explaining anything in any real detail. For example, chapter one flits aimlessly from creating views, to creating cursors, to the GROUP BY clause to ‘complex’ topics such as subqueries and joins. This must be the only book on any database in which cursors are mentioned in the first few pages.Here are a few examples of how wretched the text is. For example, the section on cursors says:“It then uses a FETCH statement with the NEXT keyword to select the fifth row, and then another FETCHstatement with the PRIOR keyword to again select the fourth retrieved row.’To illustrate this, the authors provide the following:FETCH 4 FROM order_cur;Clearly, some code has been missed out, and nobody has noticed.In the section on JSON, several lines have again been missed out and/or replaced with the wrong code:“Let's create a normal table and insert data into it:CREATE TABLE product_info (id serial, product_name text, product_categorytext, price int);INSERT INTO product_info (product_name ,product_category , price)VALUES ('Chair', 'Furniture', 200);Now, since we have inserted the record in a normal way, we will change this to the JSONformat. We will use the row_to_json function:row_to_json-----------------------------------------------{"f1":"Chair","f2":"Furniture","f3":200}(1 row)”I have no idea if the authors actually believe that typing ‘row_to_json’ would produce the result they claim: it obviously doesn’t. Nor does it work like this inside the obviously needed select statement. The next few lines are even more bizarre:“Similarly, we can output the array values as JSON with the help of the array_to_json function:CREATE TABLE product_info(id serial, product_category text, producttext[]);INSERT INTO product_info (product_category , product) VALUES('Stationary', '{"Pen","Pencil"}');”Nothing is being output as JSON: instead, a new table is being created using JSON instead of text.Here’s another strange explanation:SELECT product, SUM(sale) AS "Total sales"FROM order_detailsGROUP BY product;‘In the select statement, we have sales where we applied the SUM function and the other fieldproduct is not part of SUM, we must use in the GROUP BY clause.’The authors are attempting to say “we must group on a field other than the one which we are aggregating: we use ‘group by’ on the product field and use the aggregate sum() function on the ‘sale’ field’”.Here’s yet another example where the explanation is incomprehensible:“The HAVING clause is used to specify which individual group(s) is to be displayed, or in simple language we use theHAVING clause in order to filter the groups on the basis of an aggregate function condition.”Compare this drivel with the clear explanation in the (free) user manual:“WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed.”The section on transactions fails to explain either how isolation levels work or which ones PostgreSQL implements. The explanation of serializable isolation is particularly inadequate:‘As you saw in the preceding table, moving from the Read Uncommitted to Serializable level, the phenomena behavior is reducing.’In those cases where there isn’t a Wikipedia page as a source, the text descends into meaningless waffle. For example:“In a largely built database, there are cases where performance may not be up to the desiredexpectations. And, achieving more practical goals may spoil the purity of the design. Thesteps for the optimized design should be considered with the utmost priority before youeven consider any optimization.”Clearly, neither of the authors has a proper grasp of English, and neither has enough experience of PostgreSQL to be able to write a useful book on the subject. Unbelievably, this garbage has been checked by over a dozen people. The book boasts a copy editor, two reviewers, a proof-reader, a technical editor, a content development editor, a production coordinator, a commissioning editor, an acquisition editor and a production coordinator. All of these people must be even more inept at their job than the authors or else asleep.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela