For these functions one can call SELECT function_name(...) or SELECT * FROM function_name(...).

FUNCTIONS THAT RETURN A SINGLE VALUEFunctions can return one value (one int, one decimal, one text etc.). For these functions one can call SELECT function_name(...) or SELECT * FROM function_name(...).

Another option to define a function's output is using OUT parameters. Here we do not use RETURNS but we list the order, names and types of output alongside the input arguments preceding each field with "OUT".

Notice that this is returning just one record when in fact the query would produce multiple rows of results.

FUNCTIONS THAT RETURN A SETOF VALUESFunctions can also return a set of values of the same type. That is, imagine it returning a column of decimals or a column of text. To specify this we use the SETOF modifier. Here is a function that returns the sales figures for each salesperson for January.

FUNCTIONS THAT RETURN A SETOF ROWS
There are 4 options to return a set of rows.1) RETURNS tablePostgreSQL functions (version 8.4 and later) can also return a table. That is, we define the fields of the SETOF rows that the function will return. Here is that last function but with the person's name as well as their sales:

Functions or stored procedures are a very powerful feature of PostgreSQL. Functions allow one to modularize code, create "units" that do useful tasks and hide the complexity of the underlying code, here a query. They also reduce the risk of making a mistake by typing the same query over and over again, such as running a daily or monthly report.

PostgreSQL supports a particularly large variety of programming languages. By using these procedural language extensions one can write functions in Java (PL/Java), Python (PL/Python), R (PL/R), Perl (PL/Perl) and many others to interact with a PostgreSQL database. In this and the next post, however, we are going to cover simple functions in SQL only. In later posts we will cover PL/pgSQL a more powerful and flexible procedural language that provides features such as control flow (such as IF...THEN...ELSE), local variables and multiple queries.

We'll start with a simple SQL function. In the next post, we will expand on this and detail some additional options and features that CREATE FUNCTION supports.

but if we know that are going to have to do this each month (and you are likely to forget the query next month) it might make sense to create a function called totalsalesformonth() that one can call and pass in the month of interest. Here is how we do that. Don't worry if this looks complicated for now. We will step through each part.

NAMEThe function name must be a single string. It cannot be "total sales for month" but it can be total_sales_for_month. Choose a sensible descriptive name for the function. You and any other users will thank you later.

PARAMETER LISTWe are specifying that it takes one argument or parameter (technically this is an IN parameter) called "month" and is of type varchar.
We can have more than one argument. These are specified as a comma-delimited list.

RETURN TYPEThe function is declared to return a single value of type decimal. We will discuss return types further in the next post.

FUNCTION BODYThe "$$" says to PostgreSQL that we are starting the code that constitutes the body of the function.
The function body should be a single statement, i.e. only one semicolon. PostgreSQL will allow multiple statements but it is only going to return the last. That is,

is valid and will return 3 when called.
The names of the parameters in the parameter list are completely ignored. Instead we use $1 in place of the first parameter, $2 for the second parameter etc. So, when we call

select totalsalesForMonth('jan');

PostgreSQL takes the value 'jan' and replaces $1 with this to produce

select sum(sales) from salesfigures where month='jan';

which is then executed.

Importantly, one cannot use a passed in parameter for the name of a field or the name of a table. For instance, this function will not compile:

PostgreSQL complains of a syntax error. Why is this?
PostgreSQL is strongly typed. That means it checks that the output of the query matches the types that the function should return. In this case, the parser cannot know if the tablename passed in has a sales field and if it does whether it is numeric. There are too many unknowns for PostgreSQL to be happy that this function will work as intended.If you do need to create dynamic queries such as this, one can achieve it with PL/pgSQL.

Although the names are ignored it is important to use good descriptive names for documentation purposes. I don't know about you but I can forget what I coded last week and appreciate the help of good documentation and besides, you might not be the only user of these functions. I would strongly discourage use of generic names such as "arg0", "arg1", "x", "y" unless there is good reason. (For instance, x and y might be the best choice for a function that processes a point in the Cartesian plane.)

Thursday, December 2, 2010

We encountered the default schema called "public" in an earlier post when exploring pgAdmin. Colloquially, when someone talks about a database's schema they typically mean the structure of the tables (that this table has these fields with these types). Here, a schema is a higher level of organization, a container or namespace within a database. A schema contains a set of tables, views, stored procedures and triggers and so on, all the usual components of a database. However, one can have multiple schema within a PostgreSQL database. To clarify this, let's start with a concrete example and consider the pros and cons of different ways of organizing the data.

Suppose we have a supermarket company, SuperFoods Inc., who have two stores, say Sausalito, CA and Petaluma, CA. (Clearly they have recovered from the bad economy and layoffs of this earlier post.) Each of the two stores has a set of information: employees and contact details, details about the physical store itself, replenishment orders and order history etc.

Imagine the data are stored in two separate databases. The CEO of SuperFoods asks one of his minions to produce a report on the sales history of the two stores. The problem here is that databases are independent silos. One cannot write a SQL query that will collate the data from the two stores. psql can only connect to one database at a time. We can use external tools, such as a JDBC driver in Java that will make a connection to each of the two databases and collect the data, but we cannot query the two databases simultaneously from the psql command line.

Imagine now that we take the two databases and put them inside a single SuperFoods database. We create a container, a schema, for each of the two original databases. Each schema has a unique name, "sausalito" and "petaluma", and this causes each of the tables in the schema to have a qualified name that includes the schema name.

That is, we have
sausalito.employees
sausalito.sales

petaluma.employees
petaluma.sales

(Technically, it would include the database name too and be "SuperFoods".sausalito.employees etc. under the hood but the user doesn't see this or need to see it.)

Importantly, when we connect to the SuperFoods database we can now access the sales report tables from both stores. We cannot do
select * from sales;

because PostgreSQL is going to complain. There is an abmiguity here. There are multiple sales tables. Which do you mean? Thus, one has to qualify it with the schema name:
select * from sausalito.sales;

to specify the Sausalito sales and
select * from petaluma.sales;

to access the Petaluma sales.

We can now combine those queries with operators such as UNION and UNION ALL (covered in this post) to get something closer to what the CEO wants:
select 'sausalito', sum(sales) from sausalito.sales where year=2010
UNION ALL
select 'petaluma', sum(sales) from petaluma.sales where year=2010;

Great. Goal achieved.

OK, now consider this structure from the perspective of a human resources person at the Sausalito store. She needs to update the employees table for her store and she isn't interested in the Petaluma tables. Writing 'sausalito.' before each table in the queries is a bit of a nuisance. PostgreSQL helps us out with the notion of the search path. The search path says where to look, similar to classpaths in most programming languages.

Let's connect to a database, set the search path and create a new table.
psql -d SuperFoods

How do we create a schema? That is a synch:
testdb=# create schema sausalito;
CREATE SCHEMA
testdb=# create schema petaluma;
CREATE SCHEMA

Further, you can dump data from a single schema from the operating system command line
localhost:~ postgresuser$ pg_dump --schema sausalito testdb > sausalito.sql

We can see that using schema gives us all the tools that exist for single databases but we can collect related tables together, in SuperFoods by store, and yet compare data mong those different collections. Now we understand more about schema we can refine our notion about them. They are a namespace or rather a namespace within a database. PostgreSQL only sees one database here: SuperFoods.

Schema can be very powerful and useful way of partitioning data. However, they are typically used for more complex sets of tables, more complex than those typically needed for beginner exercises. For simpler cases, an additional field that defines the subset of data might suffice. Imagine that we include an additional 'store' field in the sales table. A single table could then be queried for Sausalito sales, Petaluma sales or both.

Also, imagine that SuperFoods assigns a regional manager to the two stores. That manager is effectively an employee at both stores. We want to avoid replication of data in databases and so would not want to include his personal details in both schema. In this case a single, more unified database structure might be more appropriate. Given those, schema are a valuable addition to PostgreSQL and worth considering when designing one's database.

Wednesday, December 1, 2010

PostgreSQL supports a number of different aggregate functions (a tutorial appears here). These are functions that perform some mathematical or statistical calculations on a set of values. Common examples are sum, min, max and count. The values are often numeric but they can be boolean, string, or XML too and count accepts anything.

Let's start with a simple example. Suppose we have the following table of sales per month for different sales people

Notice that sum is a function that we can specify in the select list (the part before the FROM) and it takes one argument. We are supplying it the values in the sales column. It adds 34 + 23 + 18 + 30 to get 105. Easy.

Filtering by WHEREAs the aggregate gets computed after any WHERE clause is applied we can easily apply filters on the data that is supplied to the aggregate. For instance, to get the sales for January

GOTCHA
If we wanted to know who had the most sales in any month we might be tempted to query

select name from salesfigures where sales=max(sales);WRONG!

We could imagine this as computing the maximum value in the sales column and the selecting the one or more names that matched this value. This will not work. If one runs this query, PostgreSQL complains

aggs=# select name from salesfigures where sales=max(sales);
ERROR: aggregates not allowed in WHERE clause
LINE 1: select name from salesfigures where sales=max(sales);
^
aggs=#

This is a typical beginner mistake. I've done it. You'll probably do it too. As the error message says, aggregates are not allowed in the WHERE clause. This is because the WHERE clause is used to generate the set of rows to be passed to the select list and any aggregates. What we have here is a circular relationship: max depends on which rows it is given and that is determined by WHERE, which depends on max... What you have to do is obtain the maximum value as one query and then pass that into another query.

aggs=# select name from salesfigures where sales=(select max(sales) from salesfigures);
name
------
joe
(1 row)

(select max(sales) from salesfigures) is called a subquery, something we will cover in more detail in a later post. For now, just know that it computes this subquery first to obtain a value, which will be 34. We then effectively have a simple query

select name from salesfigures where sales=34;

which is OK as the circularity has been eliminated.

Filtering by HAVINGOK, so we cannot have aggregates in WHERE clause. However, we can have them in a HAVING clause. If you recall our earlier post, WHERE can be accompanied by an optional HAVING clause that can be used to filter rows after the WHERE clause is performed.

Who is underperforming? Which salesperson(s) have had less than 20 sales in any one month?

aggs=# select name from salesfigures group by name having min(sales)<20;
name
------
bob
(1 row)

This query groups first to get a set of virtual tables, then applies the min aggregate to get the minumum per person. It then filters in those with a minumum less than 20. Finally, we asked for SELECT name so it returns the one name left, that for Bob.

COUNTCOUNT is commonly used aggregate. SELECT count(*) from tablename returns the number of rows. The * just means "everything", every column in this context. If we ran SELECT count(*) from salesfigures it would return 4, as there are four rows, as would SELECT count(sales) from salesfigures. Count counts the rows not the values. Don't confuse this with sum!

Unfortunately, COUNT is fairly slow in PostgreSQL. It can take seconds or sometime tens of seconds in really large tables. The reason is that when a row is deleted from a table, it is not really deleted, just flagged as not being needed any more. (This is the same in some operating system when one deletes a file.) Also, the rows for a table may be scattered through memory. Count has to scan through each row of the table sequentially, work out which rows are "dead" in order to return the total row count. Other databases can do this more efficiently and is a frequent complaint about PostgreSQL performance. However, it does excel in many other respects over other databases.

This lists the various aggregates that PostgreSQL provides. As well as count, min, max and sum mentioned above other commonly used aggregates are avg (average) and stddev (standard deviation, a statistical measure of variability). Unfortunately, median is not provided.

Let's end with a non numeric example. The EVERY aggregate checks whether each and every row is true

Saturday, November 27, 2010

Last time we covered INNER JOINs including a couple of special cases CROSS JOIN and self joins. In INNER JOINS the result set returns only the set of rows that match the join criteria (if any). IN OUTER JOINS, the results might contain both matched and unmatched rows. It is for this reason that beginners might find such JOINS a little more confusing. However, the logic is really quite straightforward.

There are three types of outer joins: LEFT, RIGHT, and FULL. Let's start with a LEFT OUTER JOIN.

In a left join when joining table t1 with table t2 PostgreSQL first does a "normal" inner join. It then looks to see if there are any rows from t1 that are not in the result set. If so, it adds in those rows placing NULLs for all the fields of t2. Thus, this guarantees that each row of t1 will appear at least once in the results.

Left joins are implicitly OUTER JOINs but we can add that keyword in explicitly

select * from clients left outer join orders on clients.id=orders.id;

We can obtain the same result set if we use the USING syntax: select * from clients left join orders using(id);

That's it. Simple isn't it?

Why might we want something like this? Suppose we have a list of clients and we have purchase data from the last month. We might want a report of the sales for all our clients, even those that didn't buy anything in that month. This sort of report might be useful for the sales staff to target those clients.

OK, if a LEFT JOIN does an inner join and adds in any additonal "missing" rows from t1, what do you think a RIGHT JOIN does? Exactly. Do an INNER JOIN and add in any missing rows from t2.

Finally, in this and the last post we only joined two tables. We can in fact join as many tables as we wish in a single query. For outer joins you will need to use parentheses and nest the joins. For inner joins, however, one can do

Friday, November 26, 2010

Understanding how table joins work is one of the key skills of a database beginner. In an earlier post, we normalized our ceos table into two tables, one table to list the set of unique people and a second table to associate a person with a term as CEO. What we didn't cover then was how to combine those tables now those data had been broken into separate tables. This is the work of join queries. When we join tables we take two or more tables and combine them using zero, one or more join criteria to create a set of resulting rows.

The first two columns are all the fields of the first of our tables listed in the query, clients (shown in red), followed by all the fields of the second table, orders. We can see that it takes the clients table and combines all its rows with the first row of orders, then it takes the clients table again and combines with the second row of orders and finally does the same for the third row of orders to produce 3 * 3 rows.

We could have produced the same set of results using the more explicit CROSS JOIN terminology:

This says output only the rows where there is a matching ID for both clients and orders so we only obtain 2 rows. (0,'joe') of clients doesn't have a match so that is not output. Similarly for (3,'val3') for orders. These criteria are boolean criteria. They must return true or false for each row combination. This is called an INNER JOIN and we can supply that keyword explicitly. This query produces the same results as the last query: select * from clients inner join orders on clients.id=orders.id;.

It is not unusual to have a large number of join criteria. It can be tedious to keep writing out the table names for all these criteria so we can shorten the criteria text by the use of an alias. This is a short, temporary "nickname" we can give to each table. Let's give client an alias of t1 and orders t2.
We assign the name by putting the alias after each of our tables in the from section of our query. We can then use them in the later part of the query:

NATURAL JOIN
Often we give fields the same fieldname for the same entity types across different tables. That is, if we have a person field in different tables we might use the same "person_id" name in those different tables. Such conventions is an aspect of good database design and can avoid some confusion when designing queries. We can ask PostgreSQL to make use of this convention in a NATURAL join which is a special type of INNER join. This is a join where we ask PostgreSQL to match up on all columns that have the same name. In the following query

PostgreSQL works out that we have an id column in each table and implicitly does an INNER JOIN on that column.

SELF JOINThe tables we are joining don't have to be different tables. We can join a table with itself. This is called a self join. In this case we have to use aliases for the table otherwise PostgreSQL will not know which id column of which table instance we mean

Sunday, November 21, 2010

In this post we shall examine the very useful PostgreSQL operators UNION, EXCEPT and INTERSECT, each of which can be followed by ALL.

A hot startup is holding a special event and wants to send out invites to some of their best clients and also to some VIPs. Some of the VIPs are actually very supportive of the site and are clients too. What query will provide the complete set of people to invite avoiding duplicate records? For this, we want UNION. UNION is an OR operator for multiple result sets. Here is our data

The head party planner sees the list of 6 invites and says "No, no, no. We need to send out two sets of invites, one set to the VIPs that will get them into the VIP tent and then ordinary invites for everyone else". Clearly, select * from vips will return the names for the VIP invite list. However, what will get us the list for the remaining invites? We want everyone on the clients list EXCEPT those on the VIP list. Unsurprisingly, we use EXCEPT

The latter query is saying find matching pairs of rows. Stephen Fry appears in both tables twice so we find two matching pairs for him and hence two rows appears in the results.

In all these three operators the columns of the two select statements must match. We cannot have the first select statement returning 3 fields and the second returning two. We can demonstrate that with our ceos table:

This is OK because both statements are returning * which as they refer to the same table means the same set of fields.

This, however, is not acceptable

apple=# select * from ceos where year between 1970 and 1979 union select name from ceos where year=1977;
ERROR: each UNION query must have the same number of columns
LINE 1: ...os where year between 1970 and 1979 union select name from ...

because the first statement returns all fields wheareas the second returns one field only.