SQL in Python

Database and SQL

  • Relational Database: Organized collection of tables.
  • Table: Collection of related data organized in rows(record) and columns(field).
  • Analogy: Table => Excel Sheet, Database => Excel Workbook.
  • Better performance, data integrity and security as compared to storing in files.
  • RDBMS: Software that manages relational databases.
  • Common RDBMS: MySQL, PostgreSQL, SQLite, Oracle, SQL Server (MS-SQL).
  • SQL => Structured Query Language
  • SQL: Code for searching, adding, modifying and removing data stored in table.
  • DBeaver: Free tool that is used to Query various databases. Download from here and install.

Creating Database

  • We will be using SQLite database.
  • SQLite is a lightweight, file-based database that is easy to set up and use.
  • It is a good choice for small to medium-sized applications and for learning SQL.
  • Create a file database.db in your project folder. This will be our SQLite database file.
  • Connecting Database in DBeaver
    1. Click on socket like icon just below File. (Shortcut: ctrl + shift + N).
    2. Click SQLite and click Next.
    3. Cick on Open... and select database.db file created in previous step.
    4. Click Test Connection. Note: For First Time Driver will be downloaded.
    5. Once connection is successful, click Finish to connect to database.
    6. Right click ondatabase name => SQL Editor => New SQL Script
    7. This opens SQL editor where we can write SQL queries.

Sample Table for Mart

  • Sample table sales and employees for a retail store:
idtxn_datecustomer_nameproduct_namequantityprice
12023-01-01AliceLaptop1999.99
22023-01-02BobSmartphone2499.99
32023-01-03CharlieHeadphones3199.99
Sample Sales Table for Retail Store
idnamesalarydepartment
1John Doe50000.00Sales
2Jane Smith60000.00Marketing
3Bob Johnson55000.00IT
Sample Employees Table for Organization

Creating Tables

    Syntax:
    1. CREATE TABLE table_name ( column1 datatype, column2 datatype, ... );
  • Common DataTypes: INTEGER, REAL, TEXT, BLOB.
  • Example:
    1. CREATE TABLE employees ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, salary REAL );

Inserting Data

  • Data is added in table with INSERT INTO statement.
  • Syntax: INSERT INTO table_name (column1, column2, ...) VALUES (value_1_1, value_1_2, ...), (value_2_1, value_2_2, ...), ... (value_n_1, value_n_2, ...);
  • Example:
    1. INSERT INTO employees (name, salary) VALUES ("Alice", 70000), ("Charlie", 60000);
  • Validate: SELECT * FROM employees;

Updating and Deleting Data

    UPDATE
    1. Used to modify existing records in a table.
    2. Syntax: UPDATE table_name SET col_1 = val_1, col_2 = val_2, ... , column_n = val_n WHERE condition;
    3. Example: UPDATE employees SET salary = 75000 WHERE name = "Alice";
    DELETE
    1. Used to remove records from a table.
    2. Syntax: DELETE FROM table_name WHERE condition;
    3. Example: DELETE FROM employees WHERE name = "Charlie";

Retrieving Data with SELECT

  • Data is retrieved from table with SELECT statement.
  • Syntax: SELECT column1, column2, ... FROM table_name WHERE condition ORDER BY column ASC|DESC LIMIT number;
  • Example:
    1. SELECT * FROM employees;
    2. SELECT name, salary FROM employees;
    3. SELECT * FROM employees LIMIT 10;
    4. SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 5;

Filter Conditions with WHERE Clause

  • WHERE clause is used to filter records based on specified conditions.
  • Operators: =, !=, <, >, <=, >=, LIKE, IN, BETWEEN.
  • Example:
    1. SELECT * FROM employees WHERE salary > 60000;
    2. SELECT * FROM employees WHERE department != "HR";
    3. SELECT * FROM employees WHERE salary >= 50000 AND salary < 80000;
    4. SELECT * FROM employees WHERE salary BETWEEN 50000 AND 80000;
    5. SELECT * FROM employees WHERE name = "Alice" OR name = "Bob";
    6. SELECT * FROM employees WHERE name IN ("Alice", "Bob");
    7. SELECT * FROM employees WHERE name LIKE "A%";
    8. SELECT * FROM employees WHERE name LIKE "%e";
  • NOTE: Functions like LOWER, UPPER, LENGTH, ROUND, REPLACE, ABS, TRIM, CONCAT, IFNULL etc. are available in SQL.

Read SQL table in Python

  • We can use sqlite3 library to connect and query SQLite database in Python.
  • In-built library, no need to install.
  • Example:
    1. import sqlite3 db_path = r"path_to_your_db.db" conn = sqlite3.connect(db_path) # conn.row_factory = sqlite3.Row (for dict) cursor = conn.cursor() cursor.execute("SELECT * FROM employees;") results = cursor.fetchall() print(results) cursor.close() conn.close()

Write SQL table from Python

    Example:
    1. import sqlite3 con=sqlite3.connect(r"path_to_your_db.db") cursor=con.cursor() # Create table cursor.execute("CREATE TABLE IF NOT EXISTS products (name TEXT, price REAL);") # Insert data data_to_add = [("Laptop", 999.99), ("Smartphone", 499.99), ("Headphones", 199.99)] cursor.executemany("INSERT INTO products (name, price) VALUES (?, ?);", data_to_add) con.commit() cursor.close() con.close()