Tips N’ Tricks – Running your queries from within Vim

I use VIM. For more or less everything. Including writing blogposts.

Usually, when I was working on blogpost about PostgreSQL, I would write an sql file, switch to another console with psql running, run \i, get output, and then copy/paste the results to my blogpost in another vim.

It worked, but wasn't really nice.

Today, I realized that I can do something much smarter.

I can just type in Vim, and then pass the data to psql, using simple “visual mapping":

:vmap R :!psql -e<enter>

How does it work? When I'm in Vim, and I select (visual) some text, I press shift-R, and the selected blob is sent to psql.

Of course – psql has to know which database to connect to, as which user, and so on, but this is handled by setting PG* environment variables before running Vim.

Thanks to “-e" option, I get all the queries printed back to me, so I don't lose them from my text file.

It works just great.

While I didn't show it in the ascii cast, I can of course also run in this way multiple queries, use transactions, and everything else. The only problem might be that every such run is executed in new psql, which means that you don't have single session.

But, that doesn't seem to be big problem (at least for me).

It would be nice to have vim as full blown sql client, and I think it's perfectly possible, but I just don't care enough to spend time writing necessary scripts.

Getting top-N rows per group

Yesterday on irc someone asked:

Hi, how do I get top 5 values from a column group by another column??

From further discussion, I learned that:

total rows in table is 2 million. It'll have unique words of less than 1 million.. (approx count)

I didn't have time yesterday, but decided to write a solution, or two, to the problem.

Continue reading Getting top-N rows per group