EXPLAIN EXTENDED

How to create fast database queries

My latest article on SQL in general: Happy New Year!. You're welcome to read and comment on it.

Archive for the ‘PostgreSQL’ Category

GROUP_CONCAT in PostgreSQL without aggregate functions

In one of the previous articles:

Aggregate concatenation

, I described an aggregate function to concatenate strings in PostgreSQL, similar to GROUP_CONCAT in MySQL.

It’s very useful if you have a complex GROUP BY query with multiple conditions.

But for some simple queries it’s possible to emulate GROUP_CONCAT with pure SQL, avoiding custom functions at all.

Let’s create a table to demonstrate our task:
Read the rest of this entry »

Written by Quassnoi

May 2nd, 2009 at 11:00 pm

Posted in PostgreSQL

Selecting N records for each group: PostgreSQL

In one of the previous articles:

Advanced row sampling

, I described how to select a certain number of records for each group in a MySQL table.

This is trivial in SQL Server and Oracle, since an analytic function ROW_NUMBER() can be used to do this.

Now, I’ll describe how to do it in PostgreSQL.

We are assuming that the records from the table should be grouped by a field called grouper, and for each grouper, N first records should be selected, ordered first by ts, then by id.

Let’s create a sample table:
Read the rest of this entry »

Written by Quassnoi

April 29th, 2009 at 11:00 pm

Posted in PostgreSQL

Counting missing rows: PostgreSQL

This is the 5th of 5 articles covering implementation of NOT IN predicate in several RDBMS‘es:

Finally let’s look how PostgreSQL copes with this predicate.

Let’s create sample tables:
Read the rest of this entry »

Written by Quassnoi

April 22nd, 2009 at 11:00 pm

Posted in PostgreSQL

Aggregate concatenation

Aggregate concatenation functions help creating a concatenated list out of a recordset. Useful for reports, hierarchical trees, etc.

MySQL supplies GROUP_CONCAT for this purpose. SYS_CONNECT_BY PATH and FOR XML can be used in Oracle and MS SQL.

In PostgreSQL, we cannot use these tricks, but we can create our own aggregate function. And this function will also accept two more extremely useful parameters: DELIMITER and IS_DISTINCT.
Read the rest of this entry »

Written by Quassnoi

March 4th, 2009 at 9:00 pm

Posted in PostgreSQL