• Teaching
    • Montessori Teacher Training 🔥
    • Yoga Teacher Training
  • Coding
    • Full Stack Development Course
    • Data Science Course
    • Python Programming Course
    • Software Testing Course
    • Architecting on AWS
  • Commerce
    • PwC Edge : Strategic Accounting and Finance Programme
    • ACCA Course
    • SAP Fico Course
    • Practical Accounting Course
    • SAP MM Course
    • HR Management Course in Kerala
  • Technical
    • Structural Design Course
    • Embedded Systems Software Engineering in Kerala
    • MEP Course
    • MEP QS Course
    • BIM Training Course
    • Quantity Survey Course
  • Finacademy
    • Forex Trading Course
    • Stock Market Course
    • Mutual Funds Course in Kerala
  • Digital Marketing
    • Digital Marketing Course
    • Performance Marketing Course
  • Language Learning
    • Spoken English Course
    • German Language Course
    • IELTS Exam Coaching
  • Exam Preparation
    • Kerala PSC Coaching
    • Kerala PSC LGS Coaching
    • KAS Coaching
    • Kerala PSC LDC Coaching
    • Kerala PSC LSGS Coaching
    • KPSC Industries Extension Officer Coaching
    • KPSC Technical Mechanical Coaching
    • KPSC Technical Electrical Coaching
    • Kerala PSC Technical Exam Preparation
    • KPSC Technical Civil Coaching
    • SBI PO Coaching
    • IBPS Clerk Coaching
    • IBPS PO Coaching
    • IBPS SO Coaching
    • Bank Exam Coaching
    • Lecturer in DIET Course
    • Kpsc HSA Coaching
    • KPSC LP UP Assistant Coaching
    • EMRS Coaching
    • KTET Coaching
    • SSC Coaching
    • SSC JE Coaching
    • SSC CGL Coaching
    • SSC CHSL Coaching
    • SSC MTS Coaching
    • UPSC Coaching
  • Health Care
    • DHA Course
    • OET Coaching
  • Other Exams
    • GATE Coaching
    • CAT Coaching
    • MAT Online Coaching
    • KMAT Online Coaching
Entri Blog
No Result
View All Result
Sunday, May 25, 2025
  • Kerala PSC
    • Kerala PSC General
      • Kerala PSC Exams
      • KAS Exam
      • Kerala PSC VEO Notification
      • Kerala Police SI
      • Kerala PSC LDC Notification
      • Kerala PSC Village Field Assistant Notification
      • Kerala PSC LD Typist Notification
      • Kerala PSC Food Safety Officer
      • Kerala PSC Excise Inspector Notification
      • Kerala PSC BDO Notification
      • Kerala PSC CPO Notification
      • Kerala PSC LGS Notification
      • Fire and Rescue Officer
      • Women Fire and Rescue Officer
    • Kerala PSC Teaching
      • Kerala PSC HSA
      • Kerala PSC HSST
      • KTET
      • LP/UP Assistant
      • KVS
      • Railway Teacher
    • Kerala PSC Technical
      • LSGD AE
      • Draftsman/Overseer
      • IEO
      • ATP
      • Polytechnic Lecturer
      • AE Electronics
      • Assistant Engineer
  • Banking
    • IBPS PO Notification
    • IBPS Clerk Notification
    • SBI PO Notification
    • SBI Clerk Notification
    • SBI SO Notification
    • SBI Apprentice Notification
    • Canara Bank PO Notification
    • Indian Bank PO Notification
    • RBI Assistant Notification
    • RBI Office Attendant Notification
    • IBPS RRB Notification
    • IBPS RRB Office Assistant Notification
  • Skilling
    • Coding
    • Spoken English
    • Stock Market
      • Share Market Today News
      • Share Market Analysis
    • Digital Marketing
    • Accounting Course
    • SAP
    • OET
    • German
    • IELTS
    • Quantity Survey
    • MEP
    • Structural Design
    • Montessori
    • Yoga Teaching
    • Oil and Gas
  • Courses
    • Data Science Course
      • Data Science Malayalam
      • Data Science Course in Tamil
      • Data Science Course in Telugu
      • Data Science Training in Kochi
      • Data Science Training in Trivandrum
      • Data Science Course in Calicut
      • Data Science Training in Thrissur
    • Data Analytics Course
      • Data Analytics Course in Malayalam
      • Data Analytics Course in Tamil
      • Data Analytics Course in Telugu
    • Technical Upskilling
      • Quantity Surveying Course
      • Structural Design Course
      • BIM Course in Kerala
      • MEP Course
      • Embedded System Course
      • MEP Quantity Surveying Course
      • MEP Course in Kochi
      • Quantity Surveyor Course in Tamil
      • Quantity Surveying Course in Telugu
      • Quantity Surveyor Course in Hyderabad
      • Quantity Surveying Course in Chennai
      • MEP Design Course in Kerala
      • HVAC Course
      • Steel Structure Design Course
      • RCC Design Course
    • Full Stack Developer Course
      • Full Stack Development Malayalam
      • Full Stack Development Hindi
      • Full Stack Development Tamil
      • Full Stack Development Telugu
      • Full Stack Development Kannada
    • Stock Market Course
      • Stock Market Course in Malayalam
      • Stock Market Course in Tamil
      • Stock Market Course in Kannada
      • Options Trading Course
    • Mutual Funds Course
    • Forex Trading Course
    • Spoken English Course
      • Spoken English Course in Malayalam
      • Spoken English Course in Hindi
      • Spoken English Course in Telugu
      • Spoken English Course in Tamil
      • Spoken English Course in Kannada
    • Python Programming Course
    • Software Testing Course
      • Software Testing Course in Malayalam
      • Software Testing Course in Tamil
      • Software Testing Course in Telugu
    • AWS Solutions Architect Associate Course
    • PwC Edge : Strategic Accounting and Finance Programme
    • Practical Accounting Course
      • Accounting Course in Malayalam
      • Accounting Course in Tamil
      • Tally Course
      • Taxation Course
      • UAE Accounting
      • GST Course
      • Zoho Books Training
      • GST Practitioner Course in Kerala
      • GCC VAT Course
    • ACCA Training Online
      • ACCA Course in Kerala
    • SAP Training Courses
      • SAP FICO Course
      • SAP MM Course
      • SAP SD Training
      • SAP FICO Course in Tamil
      • SAP MM Course in Tamil
    • HR Management Course
    • Performance Marketing Course
    • Mern Stack Developer Course
      • Full Stack Developer Course in Kochi
      • Full Stack Developer Course in Trivandrum
      • Full Stack Developer Course in Calicut
      • Full Stack Developer Course in Pune
      • Full Stack Developer Course in Bangalore
      • Full Stack Developer Course in Hyderabad
      • Full Stack Developer Course in Chennai
      • Full Stack Developer Course in Indore
      • Full Stack Developer Course in Jaipur
      • Full Stack Developer Course in Coimbatore
    • Digital Marketing Training
      • Digital Marketing Course in Kochi
      • Digital Marketing Course in Trivandrum
      • Digital Marketing Course in Calicut
      • Digital Marketing Course in Kollam
      • Digital Marketing Course in Thrissur
      • Digital Marketing Course in Kottayam
      • Digital Marketing Course in Kannur
    • Montessori Teacher Training
      • Montessori Teacher Training in Calicut
      • Montessori Teacher Training in Kochi, Ernakulam
      • Montessori Teacher Training in Trivandrum
      • Montessori Teacher Training in Kollam
      • Montessori Teacher Training in Malayalam
      • Montessori Teacher Training in Kannada
    • Other Courses
      • German Language Course
      • OET Coaching
        • OET for Pharmacist
        • OET for Nurses
      • DHA Course
      • MOH Exam Coaching
      • Nurses Recruitment Abroad
      • FMGE Coaching
      • ChatGPT Course
      • Forex Trading Course
      • Yoga Teacher Training Course
      • Diploma in Early Childhood Care and Education
      • Business Administration & Hospital Management Course
      • Hospital and Healthcare Administration
      • AI for Teachers Course
  • Others
    • Railway
      • RRB Technician Notification
      • RRB JE Notification
      • RRB ALP Notification
      • RRB NTPC Notification
      • RRB RPF Notification
      • RRB RPF SI Notification
      • RRB RPF Constable Notification
      • RRB Group D Notification
      • RRB RPSF SI Notification
      • RRB SSE Notification
    • SSC
      • SSC CPO Notification
      • SSC MTS Notification
      • SSC CGL Notification
      • SSC CHSL Notification
      • SSC GD Constable Notification
      • SSC Stenographer Notification
      • SSC JE Notification
      • SSC CAPF Notification
      • SSC JHT Notification
      • Delhi Police Constable Notification
      • Delhi Police SI Notification
    • GATE
    • MAT
    • KMAT
      • KMAT Kerala 2024
    • TET
      • APTET
      • CTET
      • DSSSB
      • Karnataka TET
      • Kerala TET
        • KTET Notification
      • KVS
      • MPTET
      • SUPER TET
      • TNTET
      • TSTET
      • UPTET
    • UPSC
      • UPSC CAPF Notification
      • UPSC CDS Notification
      • UPSC NDA Notification
      • UPSC Civil service Notification
  • Free Learn
    • Free Courses
      • Free Coding Courses
        • C Langauge Courses
        • Free Data Science Courses
        • Free Full Stack Developer Courses
        • Free Python Programming Courses
      • Free Accounting Courses
      • Free Digital Marketing Courses
        • Free SEO Courses
        • Web Development for Marketers
      • Engineering Upskilling Courses
      • Free Hospital Administration Courses
      • Free OET Training
      • Free SAP Courses
      • Free Teachers Training Courses
      • Free Trading Courses
        • Free Stock Market Courses in Malayalam
        • Free Options Trading Course Malayalam
        • Free Forex Trading Courses Malayalam
        • Free Personal Finance Courses Malayalam
    • Question Answer
    • Aptitude Questions
    • Webinars
  • Test Prep
    • Kerala PSC Coaching
      • KPSC Degree Level Exam Preparation
      • Kerala PSC 12th Level Exam Preparation
      • Kerala PSC 10th Level Exam Preparation
      • KAS Coaching
      • Kerala PSC LDC Coaching
      • Kerala PSC LD Typist Coaching
      • Kerala PSC Fireman Coaching
      • KSFE Assistant Exam Preparation
      • Secretariat Office Attendant Coaching
      • Secretariat Assistant Coaching
      • Kerala PSC SI Exam Coaching
      • Khadi Board LDC Exam Preparation
      • Devaswom Board LDC Coaching
      • University LGS Exam Preparation
      • University Assistant Exam Coaching
      • KPSC Scientific Officer Exam Coaching
      • KPSC Probation Officer Grade II
      • KPSC Food Safety Officer Coaching
      • KWA Sanitary Chemist Coaching
      • KPSC Diary Farm Instructor Exam Coaching
      • Kerala PSC KWA Lab Assistant Exam Coaching
      • Kerala PSC ICDS Supervisor Exam Coaching
      • KPSC Finger Print Searcher Coaching
      • Kerala PSC Welfare Officer Gr. II Exam Coaching
      • KPSC Assistant Dental Surgeon Coaching
    • KPSC Teaching Exams
      • HSA Exam Preparation
      • KPSC HSA Social Science Coaching
      • KPSC HSA Physical Science Coaching
      • KPSC HSA English Coaching
      • KPSC Junior Language Teacher Hindi
      • KTET Coaching
      • SET Coaching
      • LP/UP Assistant Exam Coaching
      • HSST Exam Preparation
      • HSST Commerce Exam Coaching
      • Kerala PSC Lecturer in Diet Coaching
      • KVS PGT/TGT Coaching
    • Kerala PSC Technical Exams Coaching
      • Assistant Engineer Electrical Exam Coaching
      • Assistant Engineer Electronics Coaching
      • Assistant Engineer Mechanical Coaching
      • Kerala PSC Industries Extension Officer Coaching
      • KPSC LSGD AE Exam Coaching
      • KPSC Civil Engineering Exam Coaching
      • KPSC Mechanical Engineering Exam Coaching
      • KPSC Electrical Engineering Exam Coaching
      • KPSC Electronics Engineering Exam Coaching
      • KPSC Technical Computer Science Coaching
      • KPSC Tradesman Turning Coaching
      • Kerala PSC Overseer Exam Coaching
      • KPSC Assistant Town Planner Coaching
      • Lecturer in Polytechnic Electronics Coaching
    • Teaching Exams Coaching
      • CSIR NET Exam Coaching
      • EMRS Coaching
      • CTET Exam Online Coaching
    • IELTS Training Online
    • Bank Exam Coaching Online
      • SEBI Grade A Coaching
      • IBPS SO Online Coaching
      • IBPSC PO Online Coaching
      • IBPSC Clerk Online Coaching
      • SBI PO Coaching
      • SBI Clerk Online Coaching
      • SBI Apprentice Class
      • SBI SO Online Coaching
      • RBI Grade B Coaching
      • RBI Assistant Coaching
      • CSEB Exam Coaching
      • IBPS RRB Coaching
      • IBPS RRB PO Coaching
      • Canara Bank Po Exam Coaching
      • Kerala Gramin Bank Coaching
      • Kerala Bank Exam Coaching
        • Kerala Bank Clerk Exam Coaching
        • Kerala Bank Office Attendant Exam Coaching
        • Kerala Bank Assistant Manager Exam Coaching
      • JCI Exam Coaching
      • NABARD Grade A Coaching
      • LIC AAO Coaching Online
    • UPSC Online Coaching
      • UPSC CAPF Online Coaching
    • SSC Online Coaching
      • SSC JE Online Coaching
      • SSC CGL Coaching
      • SSC CGL AAO Coaching
      • SSC CGL CBI Inspector Coaching
      • SSC CHSL Coaching
      • SSC MTS Coaching
      • SSC Stenographer Coaching
      • SSC GD Online Coaching
    • RRB Exams Coaching
      • RRB RPF Exam Coaching
      • RRB NTPC Exam Coaching
      • RRB JE Online Coaching
      • RRB JE Electronics Coaching
      • RRB ALP Exam Coaching
      • RRB Technician Exam Coaching
    • CAT Online Coaching
    • CMAT Online Coaching
    • XAT Exam Coaching
    • GATE Online Coaching
      • GATE CE Online Coaching
      • GATE ME Online Coaching
      • GATE EE Online Coaching
    • NMAT Exam Coaching
    • AAI ATC Jr Executive Coaching
    • Cochin Shipyard Executive Trainee Coaching
    • BEL Probationary Engineer Coaching
    • HPCL Junior Executive Coaching
Free Courses
Entri Blog
  • HTML Tutorial
  • DSA Tutorials
  • Tutorials in Hindi
    • HTML Tutorial for Beginners in Hindi
    • Python Tutorial for Beginners in Hindi
    • GIT and GITHUB Tutorial for Beginners in Hindi
  • Tutorials in Tamil
    • JavaScript Tutorial in Tamil
  • Tutorials in Telugu
    • HTML Tutorial For Beginners in Telugu
    • CSS Tutorial for Beginners in Telugu
    • Bootstrap Tutorial for Beginner in Telugu
  • Tutorials in Kannada
    • HTML Tutorial For Beginners in Kannada
entri exclusive offers entri exclusive offers
Home Articles

How to Execute SQL Queries in Python and R Tutorial (Experts Guide)

by Juwairiya Mahin
February 26, 2024
in Articles, Python Programming
How to Execute SQL Queries in Python and R Tutorial (Experts Guide) (1)
Share on FacebookShare on WhatsAppShare on Telegram

Table of Contents

  • What is SQL?
  • Why use SQL with Python and R?
  • Python Tutorial
  • Creating a Database
  • Running a query
  • SQL with Pandas
  • R Tutorial
  • Creating Database
  • Running Queries

The world’s most popular code language for data analysis just got a little simpler. We have demonstrated simple and effective ways to run SQL queries in Python and R, especially for data analysis and database management.

What is SQL?

Structured Query Language (SQL) is the most commonly used language to perform various data analysis tasks. It is also used to maintain relational databases, e.g. adding tables, deleting values, and optimizing the database.

A simple relational database consists of several interconnected tables, and each table consists of rows and columns. The average technology company generates millions of data points every day. A powerful and efficient storage solution is needed to be able to use data to improve existing systems or launch new products. Relational databases such as MySQL, PostgreSQL, and SQLite solve these problems by providing powerful, secure, and high-performance database management capabilities.

Basic SQL functions

  • Create a new table in a database
  • Run a query on a database
  • Retrieve data from a database
  • Insert records into a database
  • Update a table records in database
  • Delete records from database
  • Optimize any database

SQL is a high-demand skill that will help you get any job in the tech industry. Companies like Meta, Google, and Netflix are always looking for data experts who can extract insights from SQL databases and come up with creative solutions. You can learn the basics of SQL by following the Introduction to SQL tutorial on DataCamp.

Why use SQL with Python and R?

1: Which of the following data types is immutable in Python?

2: What does the len() function do in Python?

3: Which keyword is used to define a function in Python?

4: What will print(type([1, 2, 3])) output?

5: Which statement is correct about Python indentation?

    Fill out the form to see the results



    Ever wondered how much you really know? It's time to put your brain to the test!

    SQL can help us discover business performance, understand customer behavior, and track marketing campaign success metrics. Most data analysts can perform the majority of business intelligence tasks by running SQL queries, so why do we need tools like PoweBI, Python, and R? Using SQL queries, you can know what happened in the past but you cannot predict future predictions. These tools help us better understand current performance and potential growth.

    Python and R are flexible languages ​​that enable professionals to run advanced statistical analysis, build machine learning models, build data APIs, and ultimately help businesses think beyond KPIs. In this tutorial, we will learn how to connect to a SQL database, populate the database, and run SQL queries using Python and R.

    Note: If you are new to SQL, follow the SQL Skills Path to understand the fundamentals of writing SQL queries.

    Unlock Your Coding Potential with Our Python Programming Course – Enroll Today

    🚀 Start Coding Today! Enroll Now with Easy EMI Options. 💳✨

    Gain expertise in Django and open doors to lucrative opportunities in web development.

    Start Learning With EMI Payment Options

    Python Tutorial

    Python Tutorial will cover the basics of connecting to various databases (MySQL and SQLite), creating tables, adding records, running queries, and learning functions Pandas read_sql.

    Configuration

    We can connect to the database using SQLAlchemy, but in this tutorial we will use Python’s built-in SQLite3 package to run queries against the database. SQLAlchemy supports all types of databases by providing a unified API. If you want to learn more about SQLAlchemy and how it works with other databases, check out the course Introduction to Databases in Python.

    MySQL is the world’s most popular database engine and is widely used by companies such as Youtube, Paypal, LinkedIn and GitHub.Here we will learn how to connect the database. The remaining steps to use MySQL are similar to the SQLite3 package.

    First install the mysql package using ‘!pip install mysql’, then create the local database engine by providing your username, password and database name.

    import mysql.connector as sql

    conn = sql.connect(
    host=”localhost”,
    user=”abid”,
    password=”12345″,
    database=”datacamp_python”
    )

    • This code imports the mysql.connector module and assigns it the alias sql.
    • It then establishes a connection to a MySQL database using the connect() method of the sql module.
    • The connect() method takes several parameters, including the host (the server where the database is located), user (the username to connect to the database), password (the password for the user), and database (the name of the database to connect to).
    • In this case, the code connects to a database named datacamp_python on the local machine using the username abid and password 12345.

    Similarly, we can create or load an SQLite database using the sqlite3.connect function. SQLite is a library that implements a serverless, standalone, zero-configuration database engine. It is compatible with DataCamp Workspace, so we will use it in our project to avoid local server errors.

    import sqlite3
    import pandas as pd

    conn= sqlite3.connect(“datacamp_python.db”)

    • This code imports the sqlite3 and pandas modules into Python.
    • It then creates a connection to the SQLite database named “datacamp_python.db” using the connect() method of the sqlite3 module.
    • The connection object is stored in the conn variable.
    • This connection object can be used to execute SQL queries and interact with the database.
    • The pandas module can also be used to read data from the database into a DataFrame for further analysis.

    Creating a Database

    In this section, we will learn how to load the COVID-19 Impact on Airport Traffic dataset, licensed under CC BY-NC-SA 4.0, into our SQLite database. We will also learn how to create a table from scratch.

    The airport traffic dataset includes the percentage of traffic volume for the reporting period from February 1, 2020 to March 15, 2020. We will load the CSV file using the Pandas read_csv function, then use the to_sql function to pass the data frame into a SQLite table. The to_sql function requires a table name (String) and connects to the SQLite engine.

    data = pd.read_csv(“data/covid_impact_on_airport_traffic.csv”)

    data.to_sql(
    ‘airport’, # Name of the sql table
    conn, # sqlite.Connection or sqlalchemy.engine.Engine
    if_exists=’replace’
    )

    Now we will test whether we were successful or not by running a quick SQL query. Before running the query, we need to create a cursor that helps us run the query as shown in the code block below.

    Unlock Your Coding Potential with Our Python Programming Course – Enroll Today

    You can have multiple cursors on the same database in one connection. In our case, the SQL query returns three columns and five rows from the Airports table. To display the first row, we will use cursor.fetchone().

    cursor = conn.cursor()
    cursor.execute(“””SELECT Date, AirportName, PercentOfBaseline
    FROM airport
    LIMIT 5″””)
    cursor.fetchone()

    >>> (‘2020-04-03’, ‘Kingsford Smith’, 64)

    To show the remaining of the records, we will use cursor.fetchall(). The airport dataset is loaded into the database with a few lines of code successfully.

    cursor.fetchall()

    [(‘2020-04-13’, ‘Kingsford Smith’, 29),
    (‘2020-07-10’, ‘Kingsford Smith’, 54),
    (‘2020-09-02’, ‘Kingsford Smith’, 18),

    (‘2020-10-31’, ‘Kingsford Smith’, 22)]

    Now learn how to create a table from scratch and populate it by adding sample values. We will create a student information table with id (integer, primary key, auto-increment), name (text), and subject (text).

    Note: The SQLite syntax is a bit different. You should review the SQLite cheat sheet to understand the SQL queries covered in this tutorial.

    cursor.execute(“””
    CREATE TABLE studentinfo
    (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    subject TEXT
    )
    “””)

    Let’s check how many tables we’ve added to the database by running a simple SQLite query.

    cursor.execute(“””
    SELECT name
    FROM sqlite_master
    WHERE type=’table’
    “””)
    cursor.fetchall()

    >>> [(‘airport’,), (‘studentinfo’,)]

    Running a query

    In this section we will add values ​​to the student information table and run simple SQL queries. Using INSERT INTO we can add a row to the student information table.

    To insert values, we need to provide the query and value arguments to the execute function. This function responds to “? ” items we provide.

    query = “””
    INSERT INTO studentinfo
    (name, subject)
    VALUES (?, ?)
    “””
    value = (“Marry”, “Math”)
    cursor.execute(query,value)

    Repeat the query on more records.

    query = “””
    INSERT INTO studentinfo
    (name, subject)
    VALUES (?, ?)
    “””
    values = [(“Abid”, “Stat”),
    (“Carry”, “Math”),
    (“Ali”,”Data Science”),
    (“Nisha”,”Data Science”),
    (“Matthew”,”Math”),
    (“Henry”,”Data Science”)]

    cursor.executemany(query,values)

    It’s time to check the file. To do this, we will run a simple SQL query that will return rows whose subject is Data Science.

    cursor.execute(“””
    SELECT *
    FROM studentinfo
    WHERE subject LIKE ‘Data Science’
    “””)
    cursor.fetchall()

    >>> [(4, ‘Ali’, ‘Data Science’),
    (5, ‘Nisha’, ‘Data Science’),
    (7, ‘Henry’, ‘Data Science’)]

    The DISTINCT subject command is used to display unique values ​​contained in subject columns. In our case, this is mathematics, statistics and data science.

    cursor.execute(“SELECT DISTINCT subject from studentinfo”)
    cursor.fetchall()

    >> [(‘Math’,), (‘Stat’,), (‘Data Science’,)]

    To save all the changes, we will use the commit() function. If not authenticated, data will be lost after restarting the device.

    conn.commit()

    🚀 Start Coding Today! Enroll Now with Easy EMI Options. 💳✨

    Gain expertise in Django and open doors to lucrative opportunities in web development.

    Start Learning With EMI Payment Options

    SQL with Pandas

    In this section, we will learn how to extract data from an SQLite database and convert it to a Pandas data frame using a single line of code. read_sql provides more than just executing SQL queries. We can use it to define index columns, parse date and time, add values, and filter column names. Learn more about importing data with Python by taking the short DataCamp course.

    read_sql requires two arguments: an SQL query and a connection to the SQLite engine. The output contains the first five rows of the airports table where PercentOfBaseline is greater than 20.

    data_sql_1 = pd.read_sql(“””
    SELECT Date,City,PercentOfBaseline
    FROM airport
    WHERE PercentOfBaseline > 20
    ORDER BY Date DESC
    “””,
    conn)
    print(data_sql_1.head())

    Date City PercentOfBaseline
    0 2020-12-02 Sydney 27
    1 2020-12-02 Santiago 48
    2 2020-12-02 Calgary 99
    3 2020-12-02 Leduc County 100
    4 2020-12-02 Richmond 86

    Unlock Your Coding Potential with Our Python Programming Course – Enroll Today

    Performing data analytics on relational databases has become easier with the Pandas integration. We can also use this data to predict values ​​and perform complex statistical analyses. The plot function allows you to visualize a histogram of the PercentOfBaseline column.

    data_sql_1.plot(y=”PercentOfBaseline”,kind=”hist”);

    Similarly, we can limit the values ​​to the first 20 values ​​and display a time series line chart.

    data_sql_2 = pd.read_sql(“””
    SELECT Date,City,PercentOfBaseline
    FROM airport
    WHERE PercentOfBaseline > 20
    ORDER BY Date DESC
    LIMIT 20
    “””,
    conn)

    data_sql_2.plot(x=”Date”,y=”PercentOfBaseline”,kind=”line”);

    Finally we will close the connection to free up resources. Most packages do this automatically, but it’s best to close the connection after the changes are complete.

    conn.close()

    R Tutorial

    We will copy all the tasks from the Python tutorial using R. The tutorial covers creating connections, writing tables, adding rows, running queries, and analyzing data using dplyr.

    Configuration

    The DBI package is used to connect to the most popular databases such as MariaDB, Postgres, Duckdb and SQLite. For example, install the RMySQL package and create a database by providing a username, password, database name, and server address.

    install.packages(“RMySQL”)
    library(RMySQL)
    conn = dbConnect(
    MySQL(),
    user = ‘abid’,
    password = ‘1234’,
    dbname = ‘datacamp_R’,
    host = ‘localhost’
    )

    In this tutorial, we will create an SQLite database by providing an SQLite name and function.

    library(RSQLite)
    library(DBI)
    library(tidyverse)

    conn = dbConnect(SQLite(), dbname = ‘datacamp_R.db’)

    Unlock Your Coding Potential with Our Python Programming Course – Enroll Today

    Creating Database

    By importing the Tidyverse library we will have access to the dplyr, ggplot and default datasets.

    The dbWriteTable function takes the data.frame and adds it to the SQL table. It takes three arguments: the connection to SQLite, the table name, and the data frame. With dbReadTable we can view the entire table. To display the first 6 lines we use head.

    dbWriteTable(conn, “cars”, mtcars)
    head(dbReadTable(conn, “cars”))

    mpg cyl disp hp drat wt qsec vs am gear carb
    1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
    2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
    3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
    4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
    5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
    6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

    dbExecute allows us to execute any SQLite query, so we will use it to create a table called idcard.

    To display table names in the database, we will use dbListTables.

    dbExecute(conn, ‘CREATE TABLE idcard (id int, name text)’)
    dbListTables(conn)

    >>> ‘cars”idcard’

    Let’s add a row to the idcard table and use dbGetQuery to display the results.

    Note: dbGetQuery executes the query and returns records while dbExecute executes the SQL query but returns no records.

    dbExecute(conn, “INSERT INTO idcard (id,name)\
    VALUES(1,’love’)”)
    dbGetQuery(conn,”SELECT * FROM idcard”)

    id name
    1 love

    Now we will add two more rows and display the results using dbReadTable.

    dbExecute(conn,”INSERT INTO idcard (id,name)\
    VALUES(2,’Kill’),(3,’Game’)
    “)
    dbReadTable(conn,’idcard’)

    id name
    1 love
    2 Kill
    3 Game

    dbCreateTable allows us to create tables easily. This requires three arguments; connection, table name, and character vector or data.frame. Character vector includes name (column name) and value (type). In our case, we will provide a default population data.frame to create the initial structure.

    dbCreateTable(conn,’population’,population)
    dbReadTable(conn,’population’)

    country year population

    Next, we will use dbAppendTable to add values ​​to the population table.

    dbAppendTable(conn,’population’,head(population))
    dbReadTable(conn,’population’)

    country year population
    Afghanistan 1995 17586073
    Afghanistan 1996 18415307
    Afghanistan 1997 19021226
    Afghanistan 1998 19496836
    Afghanistan 1999 19987071
    Afghanistan 2000 20595360

    Running Queries

    We will use dbGetQuery to perform all of our data analytics tasks. Let’s try to run a simple query and then learn more about other functions.

    dbGetQuery(conn,”SELECT * FROM idcard”)

    id name
    1 love
    2 Kill
    3 Game

    You can also run a complex SQL query to filter and display limited rows and columns.

    dbGetQuery(conn, “SELECT mpg,hp,gear\
    FROM cars\
    WHERE hp > 50\
    LIMIT 5”)

    mpg hp gear
    21.0 110 4
    21.0 110 4
    22.8 93 4
    21.4 110 3
    18.7 175 3

    To remove a table, use dbRemoveTable. As we can see now we have successfully removed the ID card table.

    dbRemoveTable(conn,’idcard’)
    dbListTables(conn)
    >>> ‘cars”population’

    To understand tables better, we will use dbListFields to display column names in a particular table.

    dbListFields(conn, “cars”)

    >>> ‘mpg”cyl”disp”hp”drat”wt”qsec”vs”am”gear”carb’

    SQL with dplyr

    In this section, we will use dplyr to read the table and then run queries using filter, select, and collect. If you don’t want to learn SQL syntax and want to do all the tasks in pure R, then this method is for you. We extract the cars table, filter by speed and mpg, then select three columns as shown below.

    cars_results <-
    tbl(conn, “cars”) %>%
    filter(gear %in% c(4, 3),
    mpg >= 14,
    mpg <= 21) %>%
    select(mpg, hp, gear) %>%
    collect()
    cars_results

    mpg hp gear
    21.0 110 4
    21.0 110 4
    18.7 175 3
    18.1 105 3
    14.3 245 3

    We can use a filtered data frame to display a box and whisker plot using ggplot.

    ggplot(cars_results,aes(fill=as.character(gear), y=mpg)) +
    geom_boxplot()

    Or we can display a facet point plot divided by the number of gears.

    ggplot(cars_results,
    aes(mpg, ..count.. ) ) +
    geom_point(stat = “count”, size = 4) +
    coord_flip()+
    facet_grid( as.character(gear) ~ . )

    Unlock Your Coding Potential with Our Python Programming Course – Enroll Today

    Conclusion

    In this tutorial, we learned the importance of running SQL queries with Python and R, creating databases, adding tables, and performing data analysis using SQL queries. We also learned how Pandas and dplyr help us run queries with just one line of code.

    SQL is an essential skill for any technology-related job. If you are starting your career as a Data Analyst, we recommend completing the Data Analyst with SQL Server career path within two months. This career path will teach you all about SQL queries, servers, and resource management.

     

     

     

    Share61SendShare

    Juwairiya Mahin

    Related Posts

    Benefits of Padmasana Lotus Pose
    Articles

    The Divine Benefits of Padmasana Lotus Pose

    May 24, 2025
    GoPro Marketing Strategy
    Articles

    GoPro Marketing Strategy

    May 24, 2025
    Mars marketing strategy
    Articles

    Mars marketing strategy

    May 24, 2025
    Next Post
    JavaScript Interview Questions in Tamil for 2024

    Top JavaScript Interview Questions and Answers in Tamil (2024)

    More to Explore

    1. Future of Python Developers
    2. Python Online Course with 100% Placement
    3. Steps To Code A Video Conferencing App Using Python
    4. Python Advanced Interview Questions and Answers
    5. Introduction to Data Visualization in Python
    6. Python developer – Skills, Courses, Job Roles
    7. Python Developer Salary in India
    8. Method Overloading in Python

    Practice Programs

    1. Program for Finding Factorial of a Number in Python
    2. Python Program to Convert Decimal to Binary Number
    3. Python Program for Fibonacci Series
    4. Prime Number Program in Python
    5. Python Program to Check Armstrong Number

    Python Training in Different Cities

    1. Python Training in Kochi
    2. Python Training in Trivandrum
    3. Python Training in Calicut

    Free Tutorials For You

    1. SQL Tutorial for Beginners PDF
    2. Python Tutorial for Beginners in Hindi
    3. GIT and GITHUB Tutorial for Beginners in Hindi
    4. HTML Exercises to Practice
    5. JavaScript Tutorial in Tamil
    6. DSA Practice Series
    7. Microsoft Excel Malayalam Tutorial
    8. Learn Bootstrap in Tamil
    9. Introduction to CSS in Malayalam
    10. Introduction to JavaScript in Malayalam
    11. Java Programming Notes PDF
    12. Introduction to HTML in Malayalam

    Courses

    • Data Science Course
    • Full Stack Developer Course
    • Software Testing Course
    • Data Science Course in Malayalam
    • Full Stack Developer Course in Malayalam
    • Full Stack Developer Course in Hindi
    • Full Stack Developer Course in Tamil
    • Full Stack Developer Course in Telugu
    • Full Stack Developer Course in Kannada
    • Python Programming Course
    • Practical Accounting Course
    • Structural Design Course
    • Quantity Surveying Course
    • Embedded Systems Course in Kerala
    • BIM Course
    • MEP Course
    • MEP QS Course
    • Stock Market Course
    • Stock Market Course in Malayalam
    • Stock Market Course in Tamil
    • Stock Market Course in Kannada
    • Forex Trading Course
    • Mutual Funds Course
    • PwC Edge : Strategic Accounting and Finance Programme
    • SAP FICO Training
    • SAP MM Training
    • SAP SD Training
    • ACCA Online Course
    • HR Management Course

    Company

    • Become a teacher
    • Login to Entri Web

    Spoken English Courses

    • Spoken English Course
    • Spoken English Course in Malayalam
    • Spoken English Course in Hindi
    • Spoken English Course in Tamil
    • Spoken English Course in Telugu
    • Spoken English Course in Kannada
    • Spoken English Course for Housewives
    • Spoken English Course for Working Professionals
    • Spoken English Course for School Students
    • Spoken English Course for College Students
    • Spoken English Course for Job Seekers
    • AI Powered Spoken English Course

    Quick Links

    • Explore Free Courses
    • Aptitude Questions
    • Articles
    • Videos
    • Entri Daily Quiz Practice
    • Current Affairs & GK
    • News Capsule – eBook
    • Preparation Tips
    • Kerala PSC Gold
    • Entri Skilling
    • Kerala PSC

    Other Courses

    • OET Coaching Classes
    • DHA Course
    • Nurse Recruitment Abroad
    • Montessori Teachers Training
    • Performance Marketing Course
    • German Language Course
    • Yoga Teacher Training Course
    • Digital Marketing Course
    • Options Trading Course
    • German Language A1 Course
    • German Language A2 Course
    • German Language B1 Course
    • German Language B2 Course
    • Diploma in Early Childhood Care and Education
    • Hospital and Healthcare Administration
    • Business Administration & Hospital Management
    • Hospital and Healthcare Administration

    Popular Exam

    • IBPS Exam
    • SBI Exam
    • Railway RRB Exam
    • Kerala PSC
    • Tamil Nadu PSC
    • Telangana PSC
    • Andhra Pradesh PSC
    • MPPSC
    • UPPSC
    • Karnataka PSC
    • Staff Selection Commission Exam
    • GATE

    © 2023 Entri.app - Privacy Policy | Terms of Service

    No Result
    View All Result
    • Kerala PSC
      • Kerala PSC General
        • Kerala PSC Exams
        • KAS Exam
        • Kerala PSC VEO Notification
        • Kerala Police SI
        • Kerala PSC LDC Notification
        • Kerala PSC Village Field Assistant Notification
        • Kerala PSC LD Typist Notification
        • Kerala PSC Food Safety Officer
        • Kerala PSC Excise Inspector Notification
        • Kerala PSC BDO Notification
        • Kerala PSC CPO Notification
        • Kerala PSC LGS Notification
        • Fire and Rescue Officer
        • Women Fire and Rescue Officer
      • Kerala PSC Teaching
        • Kerala PSC HSA
        • Kerala PSC HSST
        • KTET
        • LP/UP Assistant
        • KVS
        • Railway Teacher
      • Kerala PSC Technical
        • LSGD AE
        • Draftsman/Overseer
        • IEO
        • ATP
        • Polytechnic Lecturer
        • AE Electronics
        • Assistant Engineer
    • Banking
      • IBPS PO Notification
      • IBPS Clerk Notification
      • SBI PO Notification
      • SBI Clerk Notification
      • SBI SO Notification
      • SBI Apprentice Notification
      • Canara Bank PO Notification
      • Indian Bank PO Notification
      • RBI Assistant Notification
      • RBI Office Attendant Notification
      • IBPS RRB Notification
      • IBPS RRB Office Assistant Notification
    • Skilling
      • Coding
      • Spoken English
      • Stock Market
        • Share Market Today News
        • Share Market Analysis
      • Digital Marketing
      • Accounting Course
      • SAP
      • OET
      • German
      • IELTS
      • Quantity Survey
      • MEP
      • Structural Design
      • Montessori
      • Yoga Teaching
      • Oil and Gas
    • Courses
      • Data Science Course
        • Data Science Malayalam
        • Data Science Course in Tamil
        • Data Science Course in Telugu
        • Data Science Training in Kochi
        • Data Science Training in Trivandrum
        • Data Science Course in Calicut
        • Data Science Training in Thrissur
      • Data Analytics Course
        • Data Analytics Course in Malayalam
        • Data Analytics Course in Tamil
        • Data Analytics Course in Telugu
      • Technical Upskilling
        • Quantity Surveying Course
        • Structural Design Course
        • BIM Course in Kerala
        • MEP Course
        • Embedded System Course
        • MEP Quantity Surveying Course
        • MEP Course in Kochi
        • Quantity Surveyor Course in Tamil
        • Quantity Surveying Course in Telugu
        • Quantity Surveyor Course in Hyderabad
        • Quantity Surveying Course in Chennai
        • MEP Design Course in Kerala
        • HVAC Course
        • Steel Structure Design Course
        • RCC Design Course
      • Full Stack Developer Course
        • Full Stack Development Malayalam
        • Full Stack Development Hindi
        • Full Stack Development Tamil
        • Full Stack Development Telugu
        • Full Stack Development Kannada
      • Stock Market Course
        • Stock Market Course in Malayalam
        • Stock Market Course in Tamil
        • Stock Market Course in Kannada
        • Options Trading Course
      • Mutual Funds Course
      • Forex Trading Course
      • Spoken English Course
        • Spoken English Course in Malayalam
        • Spoken English Course in Hindi
        • Spoken English Course in Telugu
        • Spoken English Course in Tamil
        • Spoken English Course in Kannada
      • Python Programming Course
      • Software Testing Course
        • Software Testing Course in Malayalam
        • Software Testing Course in Tamil
        • Software Testing Course in Telugu
      • AWS Solutions Architect Associate Course
      • PwC Edge : Strategic Accounting and Finance Programme
      • Practical Accounting Course
        • Accounting Course in Malayalam
        • Accounting Course in Tamil
        • Tally Course
        • Taxation Course
        • UAE Accounting
        • GST Course
        • Zoho Books Training
        • GST Practitioner Course in Kerala
        • GCC VAT Course
      • ACCA Training Online
        • ACCA Course in Kerala
      • SAP Training Courses
        • SAP FICO Course
        • SAP MM Course
        • SAP SD Training
        • SAP FICO Course in Tamil
        • SAP MM Course in Tamil
      • HR Management Course
      • Performance Marketing Course
      • Mern Stack Developer Course
        • Full Stack Developer Course in Kochi
        • Full Stack Developer Course in Trivandrum
        • Full Stack Developer Course in Calicut
        • Full Stack Developer Course in Pune
        • Full Stack Developer Course in Bangalore
        • Full Stack Developer Course in Hyderabad
        • Full Stack Developer Course in Chennai
        • Full Stack Developer Course in Indore
        • Full Stack Developer Course in Jaipur
        • Full Stack Developer Course in Coimbatore
      • Digital Marketing Training
        • Digital Marketing Course in Kochi
        • Digital Marketing Course in Trivandrum
        • Digital Marketing Course in Calicut
        • Digital Marketing Course in Kollam
        • Digital Marketing Course in Thrissur
        • Digital Marketing Course in Kottayam
        • Digital Marketing Course in Kannur
      • Montessori Teacher Training
        • Montessori Teacher Training in Calicut
        • Montessori Teacher Training in Kochi, Ernakulam
        • Montessori Teacher Training in Trivandrum
        • Montessori Teacher Training in Kollam
        • Montessori Teacher Training in Malayalam
        • Montessori Teacher Training in Kannada
      • Other Courses
        • German Language Course
        • OET Coaching
        • DHA Course
        • MOH Exam Coaching
        • Nurses Recruitment Abroad
        • FMGE Coaching
        • ChatGPT Course
        • Forex Trading Course
        • Yoga Teacher Training Course
        • Diploma in Early Childhood Care and Education
        • Business Administration & Hospital Management Course
        • Hospital and Healthcare Administration
        • AI for Teachers Course
    • Others
      • Railway
        • RRB Technician Notification
        • RRB JE Notification
        • RRB ALP Notification
        • RRB NTPC Notification
        • RRB RPF Notification
        • RRB RPF SI Notification
        • RRB RPF Constable Notification
        • RRB Group D Notification
        • RRB RPSF SI Notification
        • RRB SSE Notification
      • SSC
        • SSC CPO Notification
        • SSC MTS Notification
        • SSC CGL Notification
        • SSC CHSL Notification
        • SSC GD Constable Notification
        • SSC Stenographer Notification
        • SSC JE Notification
        • SSC CAPF Notification
        • SSC JHT Notification
        • Delhi Police Constable Notification
        • Delhi Police SI Notification
      • GATE
      • MAT
      • KMAT
        • KMAT Kerala 2024
      • TET
        • APTET
        • CTET
        • DSSSB
        • Karnataka TET
        • Kerala TET
        • KVS
        • MPTET
        • SUPER TET
        • TNTET
        • TSTET
        • UPTET
      • UPSC
        • UPSC CAPF Notification
        • UPSC CDS Notification
        • UPSC NDA Notification
        • UPSC Civil service Notification
    • Free Learn
      • Free Courses
        • Free Coding Courses
        • Free Accounting Courses
        • Free Digital Marketing Courses
        • Engineering Upskilling Courses
        • Free Hospital Administration Courses
        • Free OET Training
        • Free SAP Courses
        • Free Teachers Training Courses
        • Free Trading Courses
      • Question Answer
      • Aptitude Questions
      • Webinars
    • Test Prep
      • Kerala PSC Coaching
        • KPSC Degree Level Exam Preparation
        • Kerala PSC 12th Level Exam Preparation
        • Kerala PSC 10th Level Exam Preparation
        • KAS Coaching
        • Kerala PSC LDC Coaching
        • Kerala PSC LD Typist Coaching
        • Kerala PSC Fireman Coaching
        • KSFE Assistant Exam Preparation
        • Secretariat Office Attendant Coaching
        • Secretariat Assistant Coaching
        • Kerala PSC SI Exam Coaching
        • Khadi Board LDC Exam Preparation
        • Devaswom Board LDC Coaching
        • University LGS Exam Preparation
        • University Assistant Exam Coaching
        • KPSC Scientific Officer Exam Coaching
        • KPSC Probation Officer Grade II
        • KPSC Food Safety Officer Coaching
        • KWA Sanitary Chemist Coaching
        • KPSC Diary Farm Instructor Exam Coaching
        • Kerala PSC KWA Lab Assistant Exam Coaching
        • Kerala PSC ICDS Supervisor Exam Coaching
        • KPSC Finger Print Searcher Coaching
        • Kerala PSC Welfare Officer Gr. II Exam Coaching
        • KPSC Assistant Dental Surgeon Coaching
      • KPSC Teaching Exams
        • HSA Exam Preparation
        • KPSC HSA Social Science Coaching
        • KPSC HSA Physical Science Coaching
        • KPSC HSA English Coaching
        • KPSC Junior Language Teacher Hindi
        • KTET Coaching
        • SET Coaching
        • LP/UP Assistant Exam Coaching
        • HSST Exam Preparation
        • HSST Commerce Exam Coaching
        • Kerala PSC Lecturer in Diet Coaching
        • KVS PGT/TGT Coaching
      • Kerala PSC Technical Exams Coaching
        • Assistant Engineer Electrical Exam Coaching
        • Assistant Engineer Electronics Coaching
        • Assistant Engineer Mechanical Coaching
        • Kerala PSC Industries Extension Officer Coaching
        • KPSC LSGD AE Exam Coaching
        • KPSC Civil Engineering Exam Coaching
        • KPSC Mechanical Engineering Exam Coaching
        • KPSC Electrical Engineering Exam Coaching
        • KPSC Electronics Engineering Exam Coaching
        • KPSC Technical Computer Science Coaching
        • KPSC Tradesman Turning Coaching
        • Kerala PSC Overseer Exam Coaching
        • KPSC Assistant Town Planner Coaching
        • Lecturer in Polytechnic Electronics Coaching
      • Teaching Exams Coaching
        • CSIR NET Exam Coaching
        • EMRS Coaching
        • CTET Exam Online Coaching
      • IELTS Training Online
      • Bank Exam Coaching Online
        • SEBI Grade A Coaching
        • IBPS SO Online Coaching
        • IBPSC PO Online Coaching
        • IBPSC Clerk Online Coaching
        • SBI PO Coaching
        • SBI Clerk Online Coaching
        • SBI Apprentice Class
        • SBI SO Online Coaching
        • RBI Grade B Coaching
        • RBI Assistant Coaching
        • CSEB Exam Coaching
        • IBPS RRB Coaching
        • IBPS RRB PO Coaching
        • Canara Bank Po Exam Coaching
        • Kerala Gramin Bank Coaching
        • Kerala Bank Exam Coaching
        • JCI Exam Coaching
        • NABARD Grade A Coaching
        • LIC AAO Coaching Online
      • UPSC Online Coaching
        • UPSC CAPF Online Coaching
      • SSC Online Coaching
        • SSC JE Online Coaching
        • SSC CGL Coaching
        • SSC CGL AAO Coaching
        • SSC CGL CBI Inspector Coaching
        • SSC CHSL Coaching
        • SSC MTS Coaching
        • SSC Stenographer Coaching
        • SSC GD Online Coaching
      • RRB Exams Coaching
        • RRB RPF Exam Coaching
        • RRB NTPC Exam Coaching
        • RRB JE Online Coaching
        • RRB JE Electronics Coaching
        • RRB ALP Exam Coaching
        • RRB Technician Exam Coaching
      • CAT Online Coaching
      • CMAT Online Coaching
      • XAT Exam Coaching
      • GATE Online Coaching
        • GATE CE Online Coaching
        • GATE ME Online Coaching
        • GATE EE Online Coaching
      • NMAT Exam Coaching
      • AAI ATC Jr Executive Coaching
      • Cochin Shipyard Executive Trainee Coaching
      • BEL Probationary Engineer Coaching
      • HPCL Junior Executive Coaching

    © 2023 Entri.app - Privacy Policy | Terms of Service

    Chat