I have a postgresql database and I am querying it using psycopg2
and I need to get the data in the correct order as in table I have found different ways to get the column names from table and column types of the table with 2 different queries.
cur = con.cursor()
cur.execute(
"SELECT * FROM first"
)
column_names = [desc[0] for desc in cur.description]
print(column_names)
This gives me a list of column names IN THE CORRECT ORDER but I don't have column types, like this
['Region', 'Country', 'Item_Type', 'Sales_Channel', 'Order_Priority', 'Order_ID', 'Units_Sold', 'Units_Price', 'Unit_Cost', 'Total_Revenue', 'Total_Cost', 'Total_Profit', 'Order_Date', 'Ship_Date']
The second method is to do the following
cur.execute(
"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'first';"
)
ans = cur.fetchall()
print(ans)
This give me the column names and column types as a list of tuples BUT NOT IN THE CORRECT ORDER
[('Ship_Date', 'date'), ('Unit_Cost', 'numeric'), ('Total_Revenue', 'numeric'), ('Total_Cost', 'numeric'), ('Total_Profit', 'numeric'), ('Order_Date', 'date'), ('Order_ID', 'bigint'), ('Units_Sold', 'integer'), ('Units_Price', 'numeric'), ('Country', 'text'), ('Item_Type', 'text'), ('Sales_Channel', 'text'), ('Order_Priority', 'text'), ('Region', 'text')]
I am aware that I can run these 2 queries separately and then join the results with python to get the desired output but is there a way to do it with just one query
Is there any way to get both column name and column type in the correct order without doing 2 queries?
It would be great if there is a way to get data types from first method as I can get column name, column type and data from just one query
Thanks
order by
or listing column names instead of*
in theselect
list). And why do you care about the order anyway?