Create a Generated Column in MySQL

This article contains an example of adding a generated column to a table in MySQL.

Also known as computed columns, generated columns usually contain values that are dependent on other factors (such as the values in other columns).

Creating (or adding) a generated column in MySQL is basically the same as creating a normal column, except that the definition of the generated column contains an expression that determines the column’s value.

Continue reading

SQL ISNULL() Explained

Some RDBMSs provide an ISNULL() function that can be used when dealing with potentially null values.

MySQL, MariaDB, and Oracle Database each have an ISNULL() function that returns 1 if its argument is null, and 0 if it’s not.

SQL Server also has an ISNULL() function, but it works differently. It works more like how the IFNULL() function works in some other RDBMSs.

Other RDBMSs, such as PostgreSQL and SQLite don’t include an ISNULL() function, but they do support the IS NULL predicate (as do the other RDBMSs).

Continue reading

MySQL CASE Statement

In MySQL, the CASE statement can be used in stored programs to perform a complex conditional construct. It compares a list of conditions and returns a different result depending on which condition (if any) is matched.

The CASE statement is different to the CASE operator, in that the CASE statement is specifically for use in stored programs. Also, there’s a slight difference in the syntax.

Continue reading

2 Ways to Delete Duplicate Rows in PostgreSQL (Ignoring the Primary Key)

Below are two options for removing duplicate rows from a table in PostgreSQL when those rows have a primary key or unique identifier column. The primary key is used in the query, but it’s ignored when comparing duplicates (due to the fact that primary keys prevent duplicate rows by definition).

The following examples delete duplicate rows but keep one. So in the case of say, three identical rows, it deletes two and keeps one.

Continue reading