SQL in Python
โ1. ๐๏ธ Database and SQL
- A database is an organized collection of data. It helps us store, manage, search, update, and delete data easily. Example: A shop may store: - Products - Customers - Employees - Sales records Instead of storing all this information in many text files or Excel files, we can store it in a database.
- A relational database stores data in tables. A table contains rows and columns. In simple words: - Database โ Collection of tables - Table โ Collection of related data - Row โ One record - Column โ One field or attribute Example: Database: Retail Store Database Tables: - sales - employees - products - customers
- Imagine an Excel workbook. An Excel workbook can contain many sheets. Each sheet contains rows and columns. Database works in a similar way. Analogy: - Database โ Excel Workbook - Table โ Excel Sheet - Row โ One record - Column โ One field
1.1 What is a Database?
1.2 What is a Relational Database?
1.3 Database Analogy
Sample Employee Table
| id | name | salary | department |
|---|---|---|---|
| 1 | John Doe | 50000 | Sales |
| 2 | Jane Smith | 60000 | Marketing |
- Databases are useful because they provide: โ Better data organization โ Faster searching and filtering โ Better data integrity โ Better security โ Easier update and delete operations โ Ability to handle large data more efficiently Example: If we store employee information in a text file, searching and updating records can become difficult. But in a database, we can write a simple SQL query to find or update records.
- RDBMS stands for Relational Database Management System. An RDBMS is software used to manage relational databases. Common RDBMS examples: - SQLite - MySQL - PostgreSQL - Oracle - SQL Server
- SQL stands for Structured Query Language. SQL is used to communicate with databases.
We use SQL to:
- Create tables
- Insert data
- Read data
- Update data
- Delete data
Example:
SELECT * FROM employees;This query gets all records from the employees table. - DBeaver is a free database tool. It helps us connect to databases and write SQL queries. We can use DBeaver to work with databases like: - SQLite - MySQL - PostgreSQL - Oracle - SQL Server Click here to download DBeaver
1.4 Why Use Database Instead of Files?
1.5 What is RDBMS?
1.6 What is SQL?
1.7 What is DBeaver?
2. ๐งฑ Creating SQLite Database
- SQLite is a lightweight, file-based database. It stores the whole database inside a single file. SQLite is easy to set up and good for learning SQL. In this note, we will use SQLite.
Example database file:
database.db๐ SQLite is good for learning, small projects, desktop apps, and local data storage. - Steps:
1. Open your project folder.
2. Create a file named
database.db. 3. This file will store our SQLite database. Example:database.db๐ If the database file does not exist, SQLite can create it automatically when we connect to it. - Steps:
1. Open DBeaver.
2. Click the New Database Connection icon. Shortcut:
Ctrl + Shift + N3. Select SQLite. 4. Click Next. 5. Click Open. 6. Selectdatabase.dbfile. 7. Click Test Connection. 8. If this is the first time, DBeaver may download the required driver. 9. After successful connection, click Finish. 10. Right-click the database name. 11. Go to SQL Editor. 12. Click New SQL Script. 13. Write and run SQL queries in the SQL editor.
2.1 What is SQLite?
2.2 Creating SQLite Database File
2.3 Connecting SQLite Database in DBeaver
3. ๐งพ Sample Tables
3.1 Sales Table
Sample sales Table
| id | txn_date | customer_name | product_name | quantity | price |
|---|---|---|---|---|---|
| 1 | 2023-01-01 | Alice | Laptop | 1 | 999.99 |
| 2 | 2023-01-02 | Bob | Smartphone | 2 | 499.99 |
| 3 | 2023-01-03 | Charlie | Headphones | 3 | 199.99 |
3.2 Employees Table
Sample employees Table
| id | name | salary | department |
|---|---|---|---|
| 1 | John Doe | 50000.00 | Sales |
| 2 | Jane Smith | 60000.00 | Marketing |
| 3 | Bob Johnson | 55000.00 | IT |
4. ๐๏ธ Creating Tables
- CREATE TABLE is used to create a new table in a database.
Syntax:
CREATE TABLE table_name (column1 datatype,column2 datatype,column3 datatype); - Common SQLite data types:
INTEGER: Used for whole numbers.REAL: Used for decimal numbers.TEXT: Used for text/string values.BLOB: Used for binary data like files or images.NULL: Used when value is missing or unknown. - Example:
CREATE TABLE employees (id INTEGER,name TEXT,salary REAL,department TEXT); - Example:
CREATE TABLE sales (id INTEGER,txn_date TEXT,customer_name TEXT,product_name TEXT,quantity INTEGER,price REAL);
4.1 What is CREATE TABLE?
4.2 Common SQLite Data Types
4.3 Creating employees Table
4.4 Creating sales Table
5. โ Inserting Data
- INSERT INTO is used to add new records into a table.
Syntax:
INSERT INTO table_name (column1, column2, column3)VALUES (value1, value2, value3); - Example:
INSERT INTO employees (name, salary, department)VALUES ("Alice", 70000, "IT"); - Example:
INSERT INTO employees (name, salary, department)VALUES("Diana", 65000, "Finance"),("Charlie", 60000, "Sales"),("Bob", 55000, "Marketing"); - Example:
INSERT INTO sales (txn_date, customer_name, product_name, quantity, price)VALUES("2023-01-01", "Alice", "Laptop", 1, 999.99),("2023-01-02", "Bob", "Smartphone", 2, 499.99),("2023-01-03", "Charlie", "Headphones", 3, 199.99); - Example:
SELECT * FROM employees;Example:SELECT * FROM sales;
5.1 What is INSERT INTO?
5.2 Insert One Record
5.3 Insert Multiple Records
5.4 Insert Sales Records
5.5 Validate Inserted Data
6. ๐ Retrieving Data with SELECT
- SELECT is used to retrieve data from a table.
Syntax:
SELECT column1, column2FROM table_name; - Example:
SELECT * FROM employees;Here:*means all columns. - Example:
SELECT name, salaryFROM employees; - LIMIT is used to show only a fixed number of records.
Example:
SELECT * FROM employeesLIMIT 10; - ORDER BY is used to sort records.
Example:
SELECT name, salaryFROM employeesORDER BY salary DESC;Here:DESCmeans descending order.ASCmeans ascending order. - Example:
SELECT name, salaryFROM employeesORDER BY salary DESCLIMIT 5;This shows top 5 employees by salary.
6.1 What is SELECT?
6.2 Select All Columns
6.3 Select Specific Columns
6.4 LIMIT
6.5 ORDER BY
6.6 ORDER BY with LIMIT
7. ๐ Filtering Data with WHERE
- WHERE is used to filter records based on condition.
Syntax:
SELECT column1, column2FROM table_nameWHERE condition; - Common operators:
=Equal to!=Not equal to<Less than>Greater than<=Less than or equal to>=Greater than or equal toLIKEPattern matchingINMatch any value from a listBETWEENMatch value between two values - Example:
SELECT * FROM employeesWHERE salary > 60000;Example:SELECT * FROM employeesWHERE department != "HR"; - AND is used when all conditions must be true.
Example:
SELECT * FROM employeesWHERE salary >= 50000 AND salary < 80000; - BETWEEN is used to filter values between two values.
Example:
SELECT * FROM employeesWHERE salary BETWEEN 50000 AND 80000; - OR is used when at least one condition should be true.
Example:
SELECT * FROM employeesWHERE name = "Alice" OR name = "Bob"; - IN is used to match values from a list.
Example:
SELECT * FROM employeesWHERE name IN ("Alice", "Bob"); - LIKE is used for pattern matching.
Example:
SELECT * FROM employeesWHERE name LIKE "A%";This finds names starting with A. Example:SELECT * FROM employeesWHERE name LIKE "%e";This finds names ending with e. Example:SELECT * FROM employeesWHERE name LIKE "%li%";This finds names containing li.
7.1 What is WHERE?
7.2 Common WHERE Operators
7.3 Simple WHERE Examples
7.4 AND Condition
7.5 BETWEEN Condition
7.6 OR Condition
7.7 IN Condition
7.8 LIKE Condition
8. โ๏ธ Updating Data
- UPDATE is used to modify existing records in a table.
Syntax:
UPDATE table_nameSET column1 = value1, column2 = value2WHERE condition; - Example:
UPDATE employeesSET salary = 75000WHERE name = "Alice"; - Example:
UPDATE employeesSET salary = salary * 1.10;This increases salary of all employees by 10%. - ๐ Before running UPDATE, it is a good habit to run SELECT with the same WHERE condition to check which rows will be updated.
Without WHERE, all rows may be updated.
Example:
UPDATE employeesSET salary = 75000;This changes salary of every employee.
8.1 What is UPDATE?
8.2 Update Example
8.3 Increase Salary by Percentage
8.4 Important Note
9. ๐๏ธ Deleting Data
- DELETE is used to remove records from a table.
Syntax:
DELETE FROM table_nameWHERE condition; - ๐ Before running DELETE, it is a good habit to run SELECT with the same WHERE condition to check which rows will be deleted.
Example:
DELETE FROM employeesWHERE name = "Charlie"; - Always use WHERE when deleting specific records. Without WHERE, all rows may be deleted.
Example:
DELETE FROM employees;This deletes all records from employees table.
9.1 What is DELETE?
9.2 Delete Example
9.3 Important Note
10. ๐งฐ Useful SQL Functions
LOWER(): Converts text to lowercase. Example:SELECT LOWER(name) FROM employees;UPPER(): Converts text to uppercase. Example:SELECT UPPER(name) FROM employees;LENGTH(): Returns length of text. Example:SELECT name, LENGTH(name) FROM employees;TRIM(): Removes extra spaces from beginning and end. Example:SELECT TRIM(name) FROM employees;REPLACE(): Replaces text. Example:SELECT REPLACE(name, "a", "@") FROM employees;ROUND(): Rounds decimal number. Example:SELECT ROUND(price, 2) FROM sales;ABS(): Returns positive value. Example:SELECT ABS(-10);IFNULL(): Returns alternative value if value is NULL. Example:SELECT IFNULL(department, "Not Assigned") FROM employees;- Some SQL databases support
CONCAT(). SQLite usually uses||for string joining. Example:SELECT name || " - " || departmentFROM employees;
10.1 Text Functions
10.2 Number Functions
10.3 NULL Handling Function
10.4 Note about CONCAT
11. ๐ Reading SQL Table in Python
- Python has a built-in
sqlite3library. It allows us to connect Python with SQLite database. No installation is required. - Example:
import sqlite3db_path = "database.db"conn = sqlite3.connect(db_path)cursor = conn.cursor()cursor.execute("SELECT * FROM employees;")results = cursor.fetchall()print(results)cursor.close()conn.close() - Example:
import sqlite3db_path = "database.db"conn = sqlite3.connect(db_path)conn.row_factory = sqlite3.Rowcursor = conn.cursor()cursor.execute("SELECT * FROM employees;")results = cursor.fetchall()for row in results:print(row["name"], row["salary"])cursor.close()conn.close()
11.1 sqlite3 Library
11.2 Reading Data from SQLite
11.3 Reading Rows as Dictionary-like Objects
12. ๐ Writing SQL Table from Python
- Example:
import sqlite3conn = sqlite3.connect("database.db")cursor = conn.cursor()cursor.execute("""CREATE TABLE products (id INTEGER,name TEXT,price REAL);""")conn.commit()cursor.close()conn.close() - Example:
import sqlite3conn = sqlite3.connect("database.db")cursor = conn.cursor()data_to_add = [("Laptop", 999.99),("Smartphone", 499.99),("Headphones", 199.99)]cursor.executemany("INSERT INTO products (name, price) VALUES (?, ?);",data_to_add)conn.commit()cursor.close()conn.close() - In Python sqlite3, we should use
?placeholders when inserting values. Good:cursor.execute("INSERT INTO products (name, price) VALUES (?, ?);",("Mouse", 25.5))Avoid directly joining values into SQL strings. Placeholders help avoid errors and make queries safer.
12.1 Creating Table from Python
12.2 Inserting Data from Python
12.3 Why Use ? Placeholder?
Practice QuestionsNot started
1. Creating Tables, INSERT, UPDATE, DELETE
Question 1 of 3
- Create all tables shown in the lecture slide using appropriate data types.
- Insert records into respective tables as shown in the lecture slide.
- Update stock of Noodles in product table to 300.
- Increase salary of all employees by 10%.
- Delete record of Shyam from employee table.
- Delete records from product table where price is more than 30.
1.1 Using DBeaver:2. SELECT Queries
Question 2 of 3
- List FirstName, LastName, and Email from Customers table.
- List all fields from Customers table for customers living in Brazil.
- List InvoiceId, CustomerId, and Total from Invoices table where invoice total is over 10.
- Find records for 10 most expensive invoices from Invoices table.
- List customers from USA whose state is CA.
- Display the first 5 genres whose names start with letter R, ordered alphabetically.
- List records from Invoices table where invoice total is between 10 and 20.
2.1 Using DBeaver, load chinook.db and write SQL queries for the following:3. Integrating SQL in Python
Question 3 of 3
- Read CSV file
employee_info.csvand store it in a tableemployee_infoin database. - Run query to fetch all records from albums table and save it as
albums.csv. - Update mobile number of Ramesh Shrestha as 98172 in
employee_infotable. - Delete record of Rabindra Sapkota from
employee_infotable.
3.1 Practice integrating SQL with Python:- Read CSV file
