Random Column Value Fetcher in PostgreSQL

  • Share this:

Code introduction


This code defines a function that randomly selects a column and returns a random value from it in a specified database table. The function uses the psycopg2 library to interact with the database.


Technology Stack : psycopg2

Code Type : Function

Code Difficulty : Intermediate


                
                    
import psycopg2
import random

def fetch_random_column(cursor, table_name):
    """
    Fetch a random column value from a specified table in a PostgreSQL database.
    
    Args:
    cursor (psycopg2.cursor): A cursor object used to interact with the database.
    table_name (str): The name of the table from which to fetch the data.
    
    Returns:
    str: A random value from a random column in the specified table.
    """
    cursor.execute(f"SELECT * FROM {table_name} LIMIT 1;")
    columns = [desc[0] for desc in cursor.description]
    random_column = random.choice(columns)
    cursor.execute(f"SELECT {random_column} FROM {table_name} LIMIT 1;")
    return cursor.fetchone()[0]                
              
Tags: