Random Column Name Selection from Database Table

  • Share this:

Code introduction


This function selects random column names from a specified database table. It first connects to the database, then queries the `information_schema.columns` system table to get all column names, and finally returns a random selection of these column names.


Technology Stack : psycopg2, psycopg2.extensions

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def get_random_column_names(connection, table_name):
    import psycopg2
    import random
    cursor = connection.cursor()
    cursor.execute(f"SELECT column_name FROM information_schema.columns WHERE table_name='{table_name}'")
    columns = cursor.fetchall()
    random_columns = random.sample(columns, random.randint(1, len(columns)))
    return [col[0] for col in random_columns]