Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose SQL as default cell magics for Jupyter Notebook

I'm writing a Jupyter notebook for a database course; most cells will contain SQL code, for which I use the IPython SQL magic. Currently I have to prepend each cell with %%sql. Is there a way to avoid typing %%sql before each cell, by making it the default?

I found a related question at How do I set up default cell magics for every ipython notebook cell?. However, I couldn't find a SQL kernel for Jupyter.

like image 530
rodrigorgs Avatar asked Dec 22 '15 11:12

rodrigorgs


People also ask

Can SQL be used in Jupyter notebook?

In this post you will learn two easy ways to use Python and SQL from the Jupyter notebooks interface and create SQL queries with a few lines of code. These two methods are almost database-agnostic, so you can use them for any SQL database of your choice: MySQL, Postgres, Snowflake, MariaDB, Azure, etc.

How do I use magic SQL in Python?

To be able to use Python magic with sql and execute sql queries from a Python IDE we need to install ipython-sql library first. ipython-sql is the library that allows sql magic. You can simply installing it running this code from Anaconda Command Prompt or another command console you are using.


1 Answers

The Jupyter docs tell you how you can edit the CodeMirror settings. CodeMirror has an option called value that determines the default value of a CodeMirror cell (doc link).

So, in ~/.jupyter/nbconfig/notebook.json paste in the following code:

{
    "CodeCell": {
        "cm_config": {
            "value": "%%sql"
        }
    }
}

and now every new cell will have %%sql in it. Obviously this solution applies to any cell magic or indeed any default value you may want your code cells to have.

like image 117
Louise Davies Avatar answered Sep 24 '22 20:09

Louise Davies