PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.10 USD)

More information
Related Books
SQL Pocket Guide (Pocket References)

SQL Pocket Guide (Pocket References)

SQL is the language of databases. It's used to create and maintain database objects, place data...

PostgreSQL (2nd Edition) (Developer's Library)

PostgreSQL (2nd Edition) (Developer's Library)

The second edition of the best-selling PostgreSQL has been updated to completely cover new...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

Understanding Transactions And Locking In PostgreSQL

Getting Started: A Real World Example

Consider an accounting system; you have debits, credits and will need functions to determine if the user has a positive balance left.

Consider the schema:

Listing 1 listing-1.sql
create table accounting (
    transaction_id  serial primary key not null,
    account_id      varchar(255) not null,
    debit           numeric(22,9),
    credit          numeric(22,9)
);
 
insert into accounting (account_id, credit) values ('someuser', 100);
insert into accounting (account_id, debit) values ('someuser', 1);

This user should now have a positive account balance of 99.

Listing 2 listing-2.sql
SELECT (SUM(COALESCE(credit,0)) - SUM(COALESCE(debit,0))) AS balance
    FROM accounting
    WHERE account_id = 'someuser';

The above statement will return the user’s account balance (99).

Note: The coalesce() function returns the first non-null value. In this case if debit or credit are null values, 0 is returned.

In This Article


Tagged in