Formatting SQL Query Inside an IPython/Jupyter Notebook
Asked Answered
S

4

19

I want to show some SQL queries inside a notebook. I neither need nor want them to run. I'd just like them to be well formatted. At the very least I want them to be indented properly with new lines, though keyword highlighting would be nice too. Does a solution for this exist already?

Snobbery answered 8/12, 2016 at 19:3 Comment(0)
G
22

If you set the cell as Markdown one you can write the sql query as code specifying the language (e.g. mysql)

``` mysql
SELECT *
FROM table_a AS a
LIMIT 10; 
```

This produces:

sql in notebook

It highlights the keywords. Unfortunately, it doesn't seem to deal with indentation which seems to be the main issue you are trying to deal with but maybe this helps.

Granicus answered 2/3, 2017 at 12:24 Comment(0)
W
5

If you - like me - find yourself here because you want to highlight (and run) the %%sql magic, you're best of with the technique of this answer. Posting it here cause it took me quite some time before I found the correct keywords to my answer :)

require(['notebook/js/codecell'], function(codecell) {
  codecell.CodeCell.options_default.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
  Jupyter.notebook.events.one('kernel_ready.Kernel', function(){
  Jupyter.notebook.get_cells().map(function(cell){
      if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
  });
});
Wrecker answered 20/2, 2019 at 8:46 Comment(0)
W
1

I found that this fixed the issue I was having.

``` sql

Produced styled code in edit mode but not when the cell was run.

``` mysql

Produced correct styling

Western answered 17/1, 2018 at 23:0 Comment(0)
M
0

You can format SQL cells with jupysql-plugin: enter image description here

Documentation

Musick answered 6/6, 2023 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.