How to Pause the Execution of a Statement in PostgreSQL

PostgreSQL includes three functions that allow you to delay the execution of the server process. the execution of a statement.

In other words, you can run a statement and have it pause half way through, before continuing on its merry way.

The three functions are:

These are all very similar, but they work in slightly different ways.

Below are examples of each one.

Continue reading

Calculate the Age in Years in PostgreSQL

Postgres has the age() function that returns the age in years, months, and days based on two dates.

This works fine unless you only want to return the age in years.

For example, you simply want to return a person’s age based on their birthday. You want something like 32 instead of 32 years 4 mons 67 days, which is what age() is likely to return.

Fortunately there’s an easy way to do this in PostgreSQL.

Continue reading

Convert a Julian Day to a Date in PostgreSQL

Here are two ways to convert a given Julian day to its date value in PostgreSQL.

The first method directly inputs the Julian day into the date data type.

The second method uses the to_date() function to return the same result.

Julian day is the number of days since Monday, January 1, 4713 BC using the proleptic Julian calendar, which is November 24, 4714 BC, in the proleptic Gregorian calendar.

Continue reading

Dealing with Primary Key Conflicts when Inserting Data in SQLite

SQLite has a non-standard SQL extension clause called ON CONFLICT that enables us to specify how to deal with constraint conflicts.

In particular, the clause applies to UNIQUE, NOT NULL, CHECK, and PRIMARY KEY constraints.

This article provides examples of how this clause can be used to determine how to handle primary key constraint conflicts.

By “primary key constraint conflicts”, I mean when you try to insert a duplicate value into a primary key column. By default, when you try to do this, the operation will be aborted and SQLite will return an error.

But you can use the ON CONFLICT clause to change the way SQLite deals with these situations.

One option is to use this clause in the CREATE TABLE statement when creating the table. Doing that will determine how all INSERT operations are treated.

Another option is to use the clause on the INSERT statement whenever you try to insert data into the table. This allows you to take advantage of the clause even when the table wasn’t created with it. When you use this option, the syntax is different; you use OR instead of ON CONFLICT.

The examples on this page use the second option – I create the table without the ON CONFLICT clause, and I instead specify OR on the INSERT statement.

Continue reading