Today I Learned

hashrocket A Hashrocket project

Use Argument Indexes

In Postgres, each of the arguments you specify in a select statement has a 1-based index tied to it. You can use these indexes in the order by and group by parts of the statement.

Instead of writing

select id, updated_at from posts order by updated_at;

you can write

select id, updated_at from posts order by 2;

If you want to group by a table's type and then order by the counts from highest to lowest, you can do the following

select type, count(*) from transaction group by 1 order by 2 desc;
See More #sql TILs
Looking for help? Hashrocket developers believe that data quality is as important as code quality. We enjoy all the challenges of relational databases, from finding the fastest index, to structuring data to fit the needs of an application. We're eager to share our experiences; check out PG Casts, our series of free PostgreSQL screencasts.