In this tutorial we will se how to enter SQL commands in Jupyter Notebooks by using Magic commands.
Magic commands
In order to be able to run SQL commands in a Jupyter notebook cell, we need to use what are known as Magic Commands.
There are two types of magic commands:
- Line magic: applies to a particular line (starts with %)
- Cell magic: applies to the entire cell (starts with %%)
To run a SQL command by using Magic commands, we have to enter %sql or %%sql, for example:
#applies to only that line
%sql select * from table;
#applies to the entire cell
%%sql
select *
from table
;
How can we start to use SQL with magic commands?
We need to install ipythonSQL extension with the next command
!pip install ipython-sql
Then, we have to load this extension with the next command
%load_ext sql
Now it is time to connect to the database you are going to use. For example, to connect to IBM Database the next structure is followed
%sql ibm_db_sa://my-username:my-password@hostname:port/BLUDB?security=SSL
After connecting to the database, you are free to use SQL commands in your Jupyter Notebook!