2

I'd like to use vim to write SQL queries, but haven't figured out how to get two key features that I use all the time in programs like SQL Yog.

I usually start an instance of Yog in the background, cut-and-paste my SQL into it, hit F12 which auto-formats the whole thing. All the SQL keywords are automatically capitalized as soon as the text is pasted. I then copy it back into whatever other tool I'm using (often SQL Query Browser at work) and go from there. The benefits of these two features are worth the extra effort.

Does anyone know how I can set up vim to do this? I still may need to cut and paste back into Query Browser, which is acceptable to me, but I'd like to stick with vim for all my editing.

1
  • The SQLUtilities vim script can format SQL quite nicely for you.
    – ngm
    Commented Jul 11, 2011 at 10:30

2 Answers 2

1

You could put some autocmds for SQL files in your .vimrc that execute a bunch of :ab commands to auto-replace common keywords with their capitalized variants.

Going further, you could also write your own indentation script and attach it to indentexpr.

If you need to do this inline in another file type (i.e., you're writing SQL queries in strings in, say, PHP), you'll probably have to do this in a scratch buffer anyway, or modify your language's ftplugin to use your indentexpr in an "SQL mode."

2
  • To be honest, I don't see the need for capitalization. A judiciously formatted multi-line string with syntax highlighting has always been sufficient for me.
    – greyfade
    Commented Apr 19, 2011 at 15:55
  • I agree on capitalization. I prefer all lowercase for SQL, and I think the convention to use all caps is rather horrible. Lowercase is much more readable, and easier to type.
    – user82096
    Commented Apr 20, 2017 at 7:03
2

I just put this map in my .vimrc:

" prettify sql:
vnoremap <Leader>rp :s/\<update\>\\|\<select\>\\|\<from\>\\|\<where>\\|\<left join\>\\|\<inner join\>\\|\<group by\>\\|\<order by\>/\r\U&/ge<cr><esc>

I've mapped it rp - but choose what you want. (rp = run prettify)

The way to use it is visually select your query (eg*emphasized text* with

vip 

or whatever, then press J to join your query into one line, then run this map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.