Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Top SQL Queries in Python Every Python Developer Should Know

Updated on 30 November, 2022

6.94K+ views
6 min read

SQL stands for Structured Query language that helps in managing, manipulating, and storing relational databases. A Relational database comprises collections of tables that are correlated in one or another form. Multiple tables allow us in segregating different entities of the target information and avoiding hundreds of columns being clubbed in one table that could make it difficult to manage the database.

It is a query language and not the database itself. These queries can be performed on any relational database management system like Oracle, Microsoft SQL Server, but there is a pythonic approach to create and execute SQL queries.

SQLite3 

This is the Python built-in library that allows us to create a lightweight database without the need of running an actual client-server model. It can be used internally by the applications to store data and execute SQL commands. The package is easy to use and allows to replicate the same schema in any production-based database like Postgresql. Let’s see how to set up the database.

  • Standard import statement:

import sqlite3 as sq

The library is imported as an alias “sq”.

  • Now, we need to create a connection to the database. The connection object will serve this purpose:

connection = sq.connect(“example.db”)

If this file is not created before, then it will be created as soon as this command is executed.

  • To access and fetch information from the database, a cursor object needs to be created.

cursor = connection.cursor()

Now that the basic setup has been done, we can push the data into the database by creating the respective tables, but before that, let’s revise some SQL commands.

Basic Commands in SQL

SQL is excellent in terms of English readable commands. These are usually typed in upper case and there is no restriction about this. This is usually practiced so that the query keywords are highlighted, and they become distinguishable from table attributes. But as now we have powerful IDEs that highlight them in a different color, any method would work.

1. Create Table

This allows you to create the data holding objects, tables in your database. A database can have many tables with one or many relations. The tables have headers for every column that describes the value it holds. While creating the table, you need to specify the column name, type of data it will hold, and size. You can add other attributes such as if the column is a primary key, can have null values, and so on.

A basic table can be created as:

CREATE TABLE company_data (

id int,

name varchar (24),

no_of_employee int

);

2. SELECT and FROM

As the name suggests, it is used to select and fetch the data from the tables. It is the foremost step that would allow you to have a look at the data. It is similar to the Pandas head or tail function.

A simple query using these commands would look like this:

SELECT <column_name(s)>

FROM <table_name>;

To fetch all the columns from the table, you can put the star (*) instead of all the column names. The LIMIT keyword helps in defining the maximum number of rows. Consider this query:

SELECT *

FROM example_table

LIMIT 5;

Our learners also read: Learn Python Online for Free

3. Where

The where clause is used to specify the additional conditions over the query. You can include the range for columns, any specific comparison, or negations.

For example:

SELECT client_name, company_name

FROM company_data

WHERE company_name = ‘upGrad’;

4. Insert

This clause is used to add the values to the data tables. The values are inserted in the same order as the column names are added into the table in the create table command. One can insert multiple rows or one at a time.

For instance, the query below inserts 3 records into a table:

INSERT INTO company_data (id, name, no_of_employees)

VALUES

(1, ‘companyz_A’, 100),

(2, ‘company_B’, 200),

(3, ‘company_C’, 500);

Executing via Python

Now that you are aware of the commands, it’s time to execute them in the code. So far we are connected to the database and created a cursor object. This object will help in executing the commands on the database:

cursor.execute(‘‘‘ <QUERY> ’’’)

The query is passed as a string and in the triple quotes. This change will be not be reflected in the database until you commit this change. Closing the connection to the database at the end ensures that no new executions will be made after this point.

Look at this simple code:

import sqlite3 as sq

connection = sq.connect(“example.db”)

cursor = connection.cursor()

cursor.execute(”’

CREATE TABLE table1 (

id int,

name varchar (24)

)

”’)

cursor.execute(”’

INSERT INTO table1 (id, name)

VALUES

(1, ‘upgrad’),

(2, ‘blogs’)

”’)

cursor.execute(”’

SELECT *

FROM table1

”’)

connection.commit()

connection.close()

Important Tips

1. As the queries are passed as strings, modifying them using f-string may seem like a good option to make the program dynamic and user-controlled, but it can cause some security issues such as SQL injection attacks. To avoid these, use the placeholder “?” wherever you want to replace some values in the query. For instance:

cursor.execute(‘“SELECT ? FROM ?’’’, col_name, table_name)

You can ask the user to provide the column name and that value will be replaced here.

2. Use functions such as fetchone() and fetchall() to iterate over the results. Fetchone returns the next row in the query and fetchall returns all the rows fetched by the cursor. The results are returned as tuple so they cannot be modified by external functions in the program.

upGrad’s Exclusive Data Science Webinar for you –

How upGrad helps for your Data Science Career?

 

 

3. If you want to add bulk values to the database, then you can use the executemany() function and pass the list of tuples containing the values to be added. For example:

to_add = [(1, ‘hello’) , (2, ‘World’)]

cursor.executemany(‘INSERT INTO table VALUES (?, ?)’, to_add)

Also Read: Python Project Ideas & Topics

Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

SQL is the most preferred database language and easy to understand. Most beginners in Data Science are advised to practice SQL as it improves the data retrieval process and gives a glimpse of how Data Engineering is carried out. It is the standard language for any database manipulation and offers faster access to the database.

If you are curious to learn about data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What do you know about constraints in SQL?

Constraints determine what type of data will be entered in the table. They are specified during the creation of the table and can be applied to a single field or multiple fields. The constraints in SQL are:
NOT NULL- Prevents NULL value to be entered in a field.
CHECK- Checks if all the values in a field satisfy the given condition.
DEFAULT- Assigns a default value to a field automatically if no value has been entered.
UNIQUE- Allows only unique values to be entered in a field.
INDEX- Indexes a field providing faster retrieval of records.
PRIMARY KEY- Uniquely identifies each record in a table.
FOREIGN KEY- Restraints actions that could harm the links between tables.

2. Explain an index and its types?

An index or a database index can be referred to as a special lookup table that makes the data retrieval operation much faster. It consumes more memory and additional writes in order to search the data faster. An index can be of 4 types:
1. Unique Index
2. Non-Unique Index
3. Clustered Index

3. What is a relationship in SQL and what are its types?

A relation between multiple entities or multiple tangible and intangible objects that have something to do with each other is known as a relationship. There are 4 types of relationships in SQL:
1. One-to-One
2. One-to-Many/Many-to-One
3. Many-to-Many
4. Self-referencing relationships.