2 Ways to List CHECK Constraints in MySQL

Ever since the release of MySQL 8.0.16, we’ve had the ability to create CHECK constraints in MySQL. At some point, we may want to return a list of CHECK constraints that have been created in a database or against a given table.

Fortunately, we can use the information_schema.check_constraints view to do just that.

We can alternatively use the information_schema.table_constraints view to get the same info.

Continue reading

Using the RANK() Function to Add a “Rank” Column in PostgreSQL

PostgreSQL has a window function called rank() that returns the rank of the current row, with gaps.

“With gaps” means that it returns the same rank for any ties (i.e. two or more rows with the same value), but then subsequent ranks jump forward to account for the ties.

This means that there’s the potential for noncontiguous rank values. For example it could go 1, 2, 5, etc if several rows are ranked at 2. If there are no ties, then the rank values will be contiguous.

Continue reading

Add a Column of Row Numbers in PostgreSQL: The ROW_NUMBER() Function

In PostgreSQL, we can use the row_number() function to get each row’s number within its partition. This allows us to create a column with incrementing row numbers that reset with each new partition.

The row_number() function is a window function that’s specifically designed to return the number of the current row within its partition, starting at 1 and incrementing sequentially.

Continue reading

Fix ERROR 3581 “A window which depends on another cannot define partitioning” in MySQL

If you’re getting error 3581 in MySQL, which reads “A window which depends on another cannot define partitioning“, it’s probably because you’re using the PARTITION BY clause in a window function that refers to a named window.

To fix this issue, don’t use the PARTITION BY clause when referring to a named window.

Continue reading

Overview of the WINDOW Clause in SQL

The WINDOW clause is an optional clause that we can use in our SQL queries to create a named window. The named window can then be used as part of a window function.

When creating a window function, a SQL developer will often define it directly in the OVER clause. But that’s not the only way to do it. We can alternatively use the WINDOW clause to define it in a named window, and then refer to that named window in the OVER clause.

Continue reading