Random Column Name Fetcher from PostgreSQL

  • Share this:

Code introduction


This function randomly selects a column name from a PostgreSQL database table. It first executes an SQL query to retrieve all column names from the specified table, and then randomly selects one of them to return.


Technology Stack : psycopg2, PostgreSQL

Code Type : Database Query Function

Code Difficulty : Intermediate


                
                    
import psycopg2
import random

def fetch_random_column_name(cursor):
    """
    Fetch a random column name from a PostgreSQL database table.
    
    Args:
    cursor (psycopg2.cursor): A cursor object from psycopg2 to interact with the database.
    
    Returns:
    str: A random column name from the database.
    """
    cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name = 'your_table_name'")
    column_names = cursor.fetchall()
    return random.choice([column[0] for column in column_names])