A Quick Look at the FACTORIAL() Function in PostgreSQL

In PostgreSQL, factorial() is a mathematical function that returns the factorial of a given integer. We pass the integer (it accepts bigint), and it returns the factorial as a numeric value.

In mathematics, the factorial is the product of all positive integers less than or equal to a given positive integer. It’s denoted by that integer and an exclamation point.

Continue reading

How to Update an Array in PostgreSQL

PostgreSQL allows us to create arrays and store them in the database as an array type. We can then go back later and update those arrays as required.

We can either replace the whole array, append or prepend elements, or update individual elements within the array. When we update individual elements, we can update one element or a whole slice. Below are examples of updating an array in PostgreSQL.

Continue reading

How to DROP Tables with Foreign Key Relationships in PostgreSQL

Nothing pulls me out of the “zone” quicker than attempting to drop a table, only to be told “Nope, that table has a dependency!”.

Granted, this usually only happens in my development environments, as I rarely have any need to drop tables in a production environment.

And that’s probably why it “pulls me out of the zone”. I suddenly have to stop and start thinking about what tables contain foreign keys to the one I’m trying to drop. In dev environments, we’re often trying things out and so it’s not out of the question that we might inadvertently try to drop a table without realising it has dependent objects.

Fortunately, when we’re working with PostgreSQL, we have a quick and easy method to overcome this barrier.

Continue reading

How to Specify your own Subscript Range when Creating an Array in PostgreSQL

By default, PostgreSQL arrays are one-based. This means that we need to use 1 if we want to reference the first element in the array, 2 for the second, and so on.

But we also have the option of specifying our own subscript range for an an array. For example we could create a zero-based array, a ten-based array, or even a negative value such as a negative ten-based array.

We can do this by using subscripted assignment to specify the actual subscript range for the array. Basically, we prefix the array with the subscript range, enclosed in square brackets, and an equals sign (=) between it and the array.

Continue reading