Assignment 15: MySQL - Utkarsh Gaikwad
Assignment pdf link
Question 1
Question 1: What is a database? Differentiate between SQL and NoSQL
databases.
Answer:
A database is a collection of organized data that is stored and managed on a computer system. It allows for
efficient storage, retrieval, and manipulation of large amounts of data. A database system typically consists of
software that manages the data, a database server that stores the data, and one or more applications that
access the data.
SQL (Structured Query Language) and NoSQL (Not only SQL) are two different types of database management
systems that use different methods for storing and retrieving data. Here are some key differences between the
two:
Feature SQL databases NoSQL databases
Data model Relational data model Flexible data model
Query language SQL Database-specific query language
Scalability Vertically scalable Horizontally scalable
May offer weaker consistency
Consistency Strong consistency
models
Usage Complex queries and transactions Fast and flexible data processing
Here are some examples of each databases:
1. SQL Databases:
mySQL
Oracle
PostgreSQL
Microsoft SQL Server
SQLite
2. NoSQL Databases:
MongoDB (document-oriented)
Cassandra (column-family)
Redis (key-value)
Neo4j (graph)
Amazon DynamoDB (document-oriented)
It's worth noting that there are many different types of NoSQL databases, each with their own strengths and
weaknesses. For example, document-oriented databases like MongoDB are great for storing unstructured data
such as JSON documents, while graph databases like Neo4j are ideal for modeling complex relationships
between data points.
Similarly, there are many different types of SQL databases, each with their own features and benefits. For
example, MySQL is a popular choice for web applications due to its fast performance and scalability, while
PostgreSQL is often used for data warehousing and business intelligence applications due to its advanced query
optimization capabilities.
Ultimately, the choice between SQL and NoSQL databases will depend on the specific requirements of your
application and the type of data you need to store and process.
Question 2
Question 2: What is DDL? Explain why CREATE, DROP, ALTER, and
TRUNCATE are used with an example.
Answer : DDL stands for Data Definition Language, which is a subset of
SQL used to create, modify, and delete database objects such as tables,
indexes, and views.
Establishing Connection with SQLite3
Dependencies required : sqlalchemy==1.3.9 , ipython-sql
Using !pip install to install above package through this jupyter notebook
In [1]:
!pip install sqlalchemy==1.3.9 ipython-sql
Requirement already satisfied: sqlalchemy==1.3.9 in e:\pwskills assignments\venv\lib\site
-packages (1.3.9)
Requirement already satisfied: ipython-sql in e:\pwskills assignments\venv\lib\site-packa
ges (0.4.1)
Requirement already satisfied: prettytable<1 in e:\pwskills assignments\venv\lib\site-pac
kages (from ipython-sql) (0.7.2)
Requirement already satisfied: ipython>=1.0 in e:\pwskills assignments\venv\lib\site-pack
ages (from ipython-sql) (8.9.0)
Requirement already satisfied: ipython-genutils>=0.1.0 in e:\pwskills assignments\venv\li
b\site-packages (from ipython-sql) (0.2.0)
Requirement already satisfied: sqlparse in e:\pwskills assignments\venv\lib\site-packages
(from ipython-sql) (0.4.3)
Requirement already satisfied: six in e:\pwskills assignments\venv\lib\site-packages (fro
m ipython-sql) (1.16.0)
Requirement already satisfied: pickleshare in e:\pwskills assignments\venv\lib\site-packa
ges (from ipython>=1.0->ipython-sql) (0.7.5)
Requirement already satisfied: pygments>=2.4.0 in e:\pwskills assignments\venv\lib\site-p
ackages (from ipython>=1.0->ipython-sql) (2.14.0)
Requirement already satisfied: colorama in e:\pwskills assignments\venv\lib\site-packages
(from ipython>=1.0->ipython-sql) (0.4.6)
Requirement already satisfied: matplotlib-inline in e:\pwskills assignments\venv\lib\site
-packages (from ipython>=1.0->ipython-sql) (0.1.6)
Requirement already satisfied: traitlets>=5 in e:\pwskills assignments\venv\lib\site-pack
ages (from ipython>=1.0->ipython-sql) (5.9.0)
Requirement already satisfied: prompt-toolkit<3.1.0,>=3.0.30 in e:\pwskills assignments\v
env\lib\site-packages (from ipython>=1.0->ipython-sql) (3.0.36)
Requirement already satisfied: backcall in e:\pwskills assignments\venv\lib\site-packages
Requirement already satisfied: backcall in e:\pwskills assignments\venv\lib\site-packages
(from ipython>=1.0->ipython-sql) (0.2.0)
Requirement already satisfied: jedi>=0.16 in e:\pwskills assignments\venv\lib\site-packag
es (from ipython>=1.0->ipython-sql) (0.18.2)
Requirement already satisfied: stack-data in e:\pwskills assignments\venv\lib\site-packag
es (from ipython>=1.0->ipython-sql) (0.6.2)
Requirement already satisfied: decorator in e:\pwskills assignments\venv\lib\site-package
s (from ipython>=1.0->ipython-sql) (5.1.1)
Requirement already satisfied: parso<0.9.0,>=0.8.0 in e:\pwskills assignments\venv\lib\si
te-packages (from jedi>=0.16->ipython>=1.0->ipython-sql) (0.8.3)
Requirement already satisfied: wcwidth in e:\pwskills assignments\venv\lib\site-packages
(from prompt-toolkit<3.1.0,>=3.0.30->ipython>=1.0->ipython-sql) (0.2.6)
Requirement already satisfied: executing>=1.2.0 in e:\pwskills assignments\venv\lib\site-
packages (from stack-data->ipython>=1.0->ipython-sql) (1.2.0)
Requirement already satisfied: pure-eval in e:\pwskills assignments\venv\lib\site-package
s (from stack-data->ipython>=1.0->ipython-sql) (0.2.2)
Requirement already satisfied: asttokens>=2.1.0 in e:\pwskills assignments\venv\lib\site-
packages (from stack-data->ipython>=1.0->ipython-sql) (2.2.1)
In [2]:
%load_ext sql
In [3]:
import csv, sqlite3
con = sqlite3.connect("test.db")
cur = con.cursor()
In [4]:
%sql sqlite:///test.db
With above a connection is now established to test.db and we can directly write a query
with %%sql magic command using above
Note: The %%sql command is a Jupyter Notebook magic command that allows you to execute SQL queries
directly in a notebook cell. Provided that database connection is established
Below are DDL Commands executed with %%sql magic command
1. CREATE: The CREATE command is used to create a new database object, such as a table, index, or view.
For example, to create a new table called "users" with columns for a user's name, email, and password, you
would use the following SQL statement:
In [5]:
%%sql
CREATE TABLE if not exists users
(id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL);
* sqlite:///test.db
Done.
Out[5]:
[]
In [6]:
# Viewing Above table
%sql SELECT * FROM users;
* sqlite:///test.db
Done.
Done.
Out[6]:
id name email password
1. DROP: The DROP command is used to delete an existing database object. For example, to delete the
"users" table created in the previous example, you would use the following SQL statement:
In [7]:
# DROP example to delete tables
%sql DROP TABLE users;
* sqlite:///test.db
Done.
Out[7]:
[]
In [8]:
%sql SELECT * FROM users
#Below output shows that users table is deleted (no such table: users)
* sqlite:///test.db
(sqlite3.OperationalError) no such table: users
[SQL: SELECT * FROM users]
(Background on this error at: http://sqlalche.me/e/e3q8)
1. ALTER: The ALTER command is used to modify an existing database object, such as a table, index, or view.
For example, to add a new column to the "users" table to track a user's login status.
In [9]:
%%sql
CREATE TABLE if not exists users
(id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL);
* sqlite:///test.db
Done.
Out[9]:
[]
In [10]:
%sql SELECT * FROM users;
* sqlite:///test.db
Done.
Out[10]:
id name email password
In [11]:
# ALTER Example to change column name and schema
%sql ALTER TABLE users ADD COLUMN login_status BOOLEAN;
* sqlite:///test.db
Done.
Out[11]:
[]
[]
In [12]:
%sql SELECT * FROM users;
* sqlite:///test.db
Done.
Out[12]:
id name email password login_status
1. TRUNCATE: The TRUNCATE command is used to delete all the rows in a table, while keeping the table
structure intact. For example, to delete all the data in the "users" table but keep the table structure, you
would use the following SQL statement:
Please note that SQLite has command : DELETE FROM table_name instead of TRUNCATE from mySQL
Command in my SQL is as below:
TRUNCATE TABLE table_name
In [13]:
%sql select * from users;
* sqlite:///test.db
Done.
Out[13]:
id name email password login_status
In [14]:
%%sql
INSERT INTO users VALUES (1,'John Doe','test@test.com','123#413s',False);
INSERT INTO users VALUES (2, 'Jane Doe','test@jane.com','21wdds2',True);
* sqlite:///test.db
1 rows affected.
1 rows affected.
Out[14]:
[]
In [15]:
%sql SELECT * FROM users;
* sqlite:///test.db
Done.
Out[15]:
id name email password login_status
1 John Doe test@test.com 123#413s 0
2 Jane Doe test@jane.com 21wdds2 1
In [16]:
# Truncate Example SQLITE Has DELETE command instead of TRUNCATE
%sql DELETE FROM users;
* sqlite:///test.db
2 rows affected.
Out[16]:
[]
In [17]:
%sql SELECT * FROM users;
* sqlite:///test.db
Done.
Out[17]:
id name email password login_status
Question 3
Question 3: What is DML? Explain INSERT, UPDATE, and DELETE with an
example.
Answer : DML stands for "Data Manipulation Language," and it is a
subset of SQL (Structured Query Language) that is used to manipulate
data within a database. The three main commands in DML are INSERT,
UPDATE, and DELETE.
Creating a Blank Table first with student information grades
In [18]:
%%sql
CREATE TABLE if not exists students
(name VARCHAR(50) ,
age INT ,
grade VARCHAR(2));
* sqlite:///test.db
Done.
Out[18]:
[]
In [19]:
# Viewing the students table
%sql SELECT * FROM students
* sqlite:///test.db
Done.
Out[19]:
name age grade
1. INSERT - The INSERT command is used to add new data to a database table.
In [20]:
#INSERT Command
%sql INSERT INTO students VALUES ('Utkarsh Gaikwad', 28, 'B');
* sqlite:///test.db
1 rows affected.
Out[20]:
[]
In [21]:
# Viewing the table now
%sql SELECT * FROM students
* sqlite:///test.db
Done.
Out[21]:
name age grade
Utkarsh Gaikwad 28 B
1. UPDATE: The UPDATE command is used to modify existing data in a database table
In [22]:
# UPDATE example
%sql UPDATE students SET grade = 'A+' WHERE name = 'Utkarsh Gaikwad';
* sqlite:///test.db
1 rows affected.
Out[22]:
[]
In [23]:
#View Updated table
%sql SELECT * FROM students;
* sqlite:///test.db
Done.
Out[23]:
name age grade
Utkarsh Gaikwad 28 A+
1. DELETE: The DELETE command is used to remove data from a database table.
In [24]:
%sql DELETE FROM students WHERE name='Utkarsh Gaikwad';
* sqlite:///test.db
1 rows affected.
Out[24]:
[]
In [25]:
%sql SELECT * FROM students;
* sqlite:///test.db
Done.
Out[25]:
name age grade
Question 4
Question 4: What is DQL? Explain SELECT with an example.
Answer : DQL stands for "Data Query Language," and it is a subset of
SQL (Structured Query Language) that is used to retrieve data from a
database. The main command in DQL is SELECT.
In [26]:
#Checking students table
In [27]:
%sql SELECt * FROM students
* sqlite:///test.db
Done.
Out[27]:
name age grade
Inserting various students using INSERT command
In [28]:
%%sql
INSERT INTO students VALUES ('Utkarsh', 28, 'A');
INSERT INTO students VALUES ('John', 35, 'B');
INSERT INTO students VALUES ('Krish', 40, 'A');
INSERT INTO students VALUES ('Sudh', 35, 'A');
INSERT INTO students VALUES ('Jane', 24, 'C');
INSERT INTO students VALUES ('Aditi', 22, 'B');
INSERT INTO students VALUES ('Kritika', 38, 'C')
* sqlite:///test.db
1 rows affected.
1 rows affected.
1 rows affected.
1 rows affected.
1 rows affected.
1 rows affected.
1 rows affected.
Out[28]:
[]
In [29]:
# Selecting Entire students table
%sql SELECT * from students;
* sqlite:///test.db
Done.
Out[29]:
name age grade
Utkarsh 28 A
John 35 B
Krish 40 A
Sudh 35 A
Jane 24 C
Aditi 22 B
Kritika 38 C
In [30]:
# Example 2 : Show only name and age of students
%sql SELECT name, age FROM students;
* sqlite:///test.db
Done.
Out[30]:
name age
Utkarsh 28
John 35
Krish 40
Sudh 35
Jane 24
Aditi 22
Kritika 38
In [32]:
# Example 3: Selecting student with A Grade
%sql SELECT * FROM students WHERE grade='A';
* sqlite:///test.db
Done.
Out[32]:
name age grade
Utkarsh 28 A
Krish 40 A
Sudh 35 A
Question 5
Question 5: Explain Primary Key and Foreign Key.
Answer:
1. Primary Key: In a database table, a primary key is a column or a set of columns that uniquely identifies each
row in the table. The primary key is used to ensure that each row in the table is unique, and it is often used
row in the table. The primary key is used to ensure that each row in the table is unique, and it is often used
as a reference by other tables. The primary key is also used to enforce data integrity, which means that it
ensures that there are no duplicate or null values in the key column(s).
Creating a table named "customers" with columns "customer_id", "first_name", "last_name", and "email". The
"customer_id" column is defined as the primary key.
In [33]:
%%sql
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100));
* sqlite:///test.db
Done.
Out[33]:
[]
In [34]:
%sql SELECT * FROM customers
* sqlite:///test.db
Done.
Out[34]:
customer_id first_name last_name email
1. Foreign Key: A foreign key is a column or a set of columns in a table that refers to the primary key of another
table. The foreign key is used to establish a relationship between two tables, and it ensures that the data in
the foreign key column(s) of one table matches the data in the primary key column(s) of the other table.
Creating a table named "orders" with columns "order_id", "order_date", "customer_id", and "total_amount". The
"order_id" column is defined as the primary key, and the "customer_id" column is defined as a foreign key that
references the "customer_id" column of the "customers" table. This establishes a relationship between the
"orders" table and the "customers" table. The "total_amount" column is used to store the total amount of the
order.
In [35]:
%%sql
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
total_amount DECIMAL(10,2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id));
* sqlite:///test.db
Done.
Out[35]:
[]
In [36]:
%sql SELECT * FROM orders
* sqlite:///test.db
Done.
Out[36]:
order_id order_date customer_id total_amount
Closing SQLite datbase connection
In [42]:
con.close()
Question 6
Question 6: Write a python code to connect MySQL to python. Explain
the cursor() and execute() method
Answer:
Installing mySQL connector first
In [37]:
!pip install mysql-connector-python
Collecting mysql-connector-python
Downloading mysql_connector_python-8.0.32-cp310-cp310-win_amd64.whl (7.9 MB)
---------------------------------------- 0.0/7.9 MB ? eta -:--:--
---------------------------------------- 0.0/7.9 MB 960.0 kB/s eta 0:00:09
--------------------------------------- 0.1/7.9 MB 1.3 MB/s eta 0:00:06
- -------------------------------------- 0.2/7.9 MB 1.8 MB/s eta 0:00:05
-- ------------------------------------- 0.5/7.9 MB 2.9 MB/s eta 0:00:03
----- ---------------------------------- 1.0/7.9 MB 4.6 MB/s eta 0:00:02
--------- ------------------------------ 1.8/7.9 MB 6.4 MB/s eta 0:00:01
------------- -------------------------- 2.6/7.9 MB 8.0 MB/s eta 0:00:01
------------------ --------------------- 3.7/7.9 MB 9.9 MB/s eta 0:00:01
-------------------------- ------------- 5.3/7.9 MB 13.1 MB/s eta 0:00:01
------------------------------ --------- 6.1/7.9 MB 13.4 MB/s eta 0:00:01
--------------------------------- ------ 6.7/7.9 MB 13.0 MB/s eta 0:00:01
---------------------------------- ----- 6.7/7.9 MB 12.3 MB/s eta 0:00:01
------------------------------------ --- 7.3/7.9 MB 12.6 MB/s eta 0:00:01
--------------------------------------- 7.7/7.9 MB 12.0 MB/s eta 0:00:01
---------------------------------------- 7.9/7.9 MB 12.0 MB/s eta 0:00:00
Collecting protobuf<=3.20.3,>=3.11.0
Using cached protobuf-3.20.3-cp310-cp310-win_amd64.whl (904 kB)
Installing collected packages: protobuf, mysql-connector-python
Successfully installed mysql-connector-python-8.0.32 protobuf-3.20.3
In [41]:
import mysql.connector
# import mysql.connector
#create user 'user'@'%' identified by 'password'
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="Secure@1994"
)
print(mydb)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
mydb.close()
<mysql.connector.connection_cext.CMySQLConnection object at 0x000002626623FEE0>
('information_schema',)
('mysql',)
('performance_schema',)
('sys',)
1. In above code, we first establish a connection to a MySQL database using the mysql.connector.connect()
method, which takes the host, user, password as arguments.
2. Next, we create a cursor object using the cursor() method of the connection object. The cursor object allows
us to execute queries and fetch results.
3. We then execute a SQL query using the execute() method of the cursor object, which takes the SQL query as
an argument.
Question 7
Question 7: Give the order of execution of SQL clauses in an SQL
query.
Answer: In an SQL query, the clauses are executed in the following
order:
1. FROM clause: Specifies the table or tables from which to retrieve data.
2. JOIN clause: Specifies how to join multiple tables together, if needed.
3. WHERE clause: Specifies which rows to retrieve based on a set of conditions.
4. GROUP BY clause: Specifies how to group rows based on one or more columns.
5. HAVING clause: Specifies which groups to retrieve based on a set of conditions.
6. SELECT clause: Specifies which columns to retrieve.
7. DISTINCT clause: Specifies to retrieve only distinct values of the specified columns.
8. ORDER BY clause: Specifies how to sort the retrieved rows based on one or more columns.
9. LIMIT clause: Specifies the maximum number of rows to retrieve.