Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python SQLite getting names of the tables that contain columns with specific name

There’s a database with multiple tables. Is there a way to print out table names that contain columns related to customers, for example: customer_ID?

What I need to do is:
There’re two tables named "payment" and "customer" that have columns "customer_ID", so names of tables "payment" and "customer" have to be printed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use exists with a subquery:

select m.name from sqlite_master m where m.type = 'table' and exists 
    (select 1 from pragma_table_info(m.name) m1 where m1.name = 'customer_ID')

import sqlite3
conn = sqlite3.connect('test_db.db')
r = list(conn.cursor().execute('''select m.name from sqlite_master m where m.type = 'table' and exists 
       (select 1 from pragma_table_info(m.name) m1 where m1.name = 'customer_ID')'''))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading