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

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 t_student (id, name, field, birth_year)''')
c.execute('''CREATE TABLE t_thesis (thesis_id, phd_title, phd_year)''')

# 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 t_student and t_thesis 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 t_student')
names = [description[0] for description in c.description]
print(names)
# Output: ['id', 'name', 'field', 'birth_year']

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

Privacy Policy | Terms & Conditions