SQLite: How to Automatically Rename Columns from Same Table Join

sqlite

When I join two tables to avoid conflicts I use column aliases. But that is prone to errors if there a lot of columns. Also, some ORMS require to use hardcoded or dynamic prefixes to column names. Is there automatic way to rename columns in such a way that all columns from T22 start with "c_t22_" and all columns from T23 start with "c_t23_"?

select T1.id,
       T1.p1, T21.name as p1_name,
       T1.p2, T22.name as p2_name,
       T1.p3, T23.name as p3_name
from T1
join T2 as T21 on T1.p1 = T21.id,
join T2 as T22 on T1.p2 = T22.id,
join T2 as T23 on T1.p3 = T23.id

Best Answer

SQLite is designed as a small, embedded database to be accessed from a 'real' programming language, so it has no built-in mechanism for dynamic SQL.

You have to construct the SQL query from inside that other programming language; something like this:

cols = []
for tab in tables:
    for col in columns:
       cols.append("c_{}_{}".format(tab, col))
sql = "SELECT " + ", ".join(cols) + " ..."
execute(sql)