101 SQL with Python Code Tutorial | Towards Data Science

SQL is the world’s most loved (or at least most used) data storage/querying language — and Python the most popular programming language in the world. Both together can produce some spectacular results.
We will run through the basics of getting set up with a local, open-source SQL server (MySQL). And connecting to that server and executing SQL queries via Python. We will cover:
> Setting Up MySQL  - Running a MySQL Server> MySQL For Python  - Setup> Databases and Tables  - The Database  - Creating a Table    1. The SQL Way    2. The Pandas Way> Quick Queries  - Reading Data  - Filtering  - Or Anything Else
First, we need to install MySQL. You can find the MS installation over here (make sure to download the full version — not web).
Once the installer opens, we select Developer Default and continue through the next few steps to install MySQL.
After installation, there will be a few more configuration steps. Follow these and use all of the default settings (unless you need to change them). You will also be able to set up the password for the root user — don’t forget this.
Once installed, our MySQL Server should be running over on port 3306. If it doesn’t seem to be running, we can instantiate it by opening a command prompt window (CMD, Bash, etc.) and typing mysqld.
If the command is not found, navigate to your MySQL Server /bin directory before running mysqld. For me, on Windows, the path is:
C:\Program Files\MySQL\MySQL Server 8.0\bin
Next, we need to install a MySQL connection package for Python called mysql.connector. We do this by opening CMD/Anaconda Prompt/Bash/etc. and typing:
pip install mysql-connector-python
Simple! Let’s switch over to Python and check that everything is working properly:
import mysql.connector# connect to our local MySQL instance using connection stringmydb = mysql.connector.connect(  host="localhost",  user="root",  password="<PASSWORD>")
We should then be able to print our mydb like so:
The hierarchy of objects in SQL includes our server at the very top. Inside the server are the databases, and inside the databases are the SQL tables themselves.
Our data is stored within these tables. So, let’s go ahead and create our first database and table.
Back in Python, we can execute SQL statements using the execute method, like so:
Of course, we don’t have any databases to show yet. To create a database in SQL, we write CREATE DATABASE dbname — using Python, we write:
mycursor.execute("CREATE DATABASE dbname")
We can then connect to our new database using another connection string that specifies our database database="dbname":
Next up, we create our table, which will contain all of our data. We can do this in two ways.
1.After connecting to our new database, we can execute a CREATE TABLE query:
Now we have a table called dbtable! It contains just three columns:
user_id — an eight-character string
location — an up to 32 character string
number_of — an integer
We can then populate the table like we usually would in SQL:
The final line mydb.commit() is an extra step required when using Python. Typically, SQL commands auto-commit to a database. But, this is not the case when using a Python connection.
So, after every modification — we must commit it for the change to persist. We can check our changes like so:
2.We can take some data from a Pandas DataFrame to create our new data table.
I will use the Titanic dataset (train.csv) in this example — but feel free to use any dataset you like.
When adding data from a Pandas Dataframe, we actually need to switch to another framework and create a ‘SQLAlchemy’ connection. First, install sqlalchemy:
pip install sqlalchemy
Once installed, we can import this module and create our new connection like so:
And now we’re ready to create our new SQL table using a Pandas DataFrame. All we need is the to_sql method:
Now we’re done, we’ve uploaded the Titanic dataset to MySQL. We can head over to MySQL Workbench to see our new table too:
Let’s practice with some queries using our new titanic table.
First, let’s read our data. We can get the equivalent of a dataframe head in SQL using SELECT TOP(5) * FROM titanic:
Alternatively, we can extract our query results directly to a Pandas dataframe:
Of course, we can couple this up with any usual SQL query. We can filter on a specific condition using a WHERE statement:
We can perform any query that we usually would in SQL. Quickly putting together SQL code to analyze our data:
That’s all for this introduction to MySQL with Python! We’ve covered:
Installing and setting up MySQL
Setting up MySQL in Python
SQL databases and tables
Creating both from Python
Uploading dataframes to MySQL
Querying our data!
Fortunately, it’s remarkably straightforward to get up and running with Python and MySQL — and using both can really optimize data analytics/science workflows or serve as a great data management system.
I hope you enjoyed this article. If you’re interested in seeing more content, I post tutorials to YouTube here! Or, if you have any questions or ideas, let me know via Twitter or in the comments below.
Thanks for reading!
🤖 70% Discount on the NLP With Transformers Course
*All images are by the author except where stated otherwise