How to Limit the Rows Returned by a SQL Query

When writing SQL queries, we’ll often use a WHERE clause or HAVING clause to narrow the results down to just those rows that we’re interested in.

But sometimes we might want to reduce the number of rows returned without adding extra filtering criteria. Sometimes we might just want to see a handful of rows, without hundreds, thousands or even millions of rows being returned.

Continue reading

How to Force a Guaranteed Minimum Value When Selecting a Column in SQL Server

Suppose you’re trying to query column, but you need to set a minimum value to be returned, even if the column contains values that are less than that minimum. For example, you want a minimum value of 50 to be returned, even if the column contains values that are less than 50.

We can use the GREATEST() function to build such a query.

Continue reading

Understanding the DISTINCT ON Option in PostgreSQL

Most major RDBMSs support the DISTINCT clause, which allows us to get unique – or “distinct” – rows from our SQL queries. But PostgreSQL’s implementation of this clause has an extra option that most other RDBMSs don’t include.

PostgreSQL allows us to include the ON() option when using DISTINCT. This enables us to specify exactly which columns should be evaluated by the DISTINCT modifier, while simultaneously allowing us to return columns that aren’t evaluated.

Continue reading

Understanding the OFFSET Clause in Oracle

In Oracle Database, we can use the OFFSET clause to make a SELECT statement skip a certain number of rows in its result set.

The OFFSET clause is defined as part of the FETCH row limiting clause, which allows us to limit the number of rows returned by a query.

We can therefore use both OFFSET and FETCH to limit the output to just the specified number or percentage of rows, at a specified offset.

Continue reading