MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • SQL & NoSQL Databases
  • 1. Relational Database Fundamentals
  • 2. SQL: Basic Data Manipulation (DML)
  • 3. SQL: Filtering and Sorting
  • 4. SQL: Aggregation and Relations
  • 5. SQL: Schema Management (DDL)
  • 6. Python and SQL
    • Using the sqlite3 package
    • Accessing Metainformation
  • 7. NoSQL Databases
  • References
  • Part 1 Slides: Relational & SQL
  • Part 2 Slides: SQLite & NoSQL

Metainformation: sqlite_master

SQLite has a special table called sqlite_master that holds information about the "real" tables in the database. You can query this table to get information about the schema.

Example:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()

# Create a couple of tables
c.execute('''CREATE TABLE Customers (id, name, email, credit_limit)''')
c.execute('''CREATE TABLE Orders (order_id, customer_id, order_date, amount)''')

# Query sqlite_master to see the tables
for row in c.execute("SELECT * FROM sqlite_master WHERE type='table'"):
    print(row)

conn.close()

This will output information about the Customers and Orders tables, including the SQL used to create them.

Retrieving Column Names

The description attribute of the cursor object contains the column names of the last query.

c.execute('SELECT * from Customers')
names = [description[0] for description in c.description]
print(names)
# Output: ['id', 'name', 'email', 'credit_limit']

This is especially useful in tandem with the sqlite_master table when exploring a new database.

Privacy Policy | Terms & Conditions