Random Column Value Query from SQLite Table

  • Share this:

Code introduction


This function connects to a SQLite database, randomly selects a column from a specified table, and then executes a query to retrieve all rows from the table where the selected column matches a random value from the column.


Technology Stack : Python, sqlite3

Code Type : Database query

Code Difficulty : Intermediate


                
                    
import sqlite3
import random

def random_select_and_query(db_path, table_name):
    """
    This function connects to a SQLite database, selects a random column from a specified table,
    and then executes a query to retrieve all rows from the table where the selected column matches
    a random value from the table.
    """
    # Connect to the SQLite database
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # Get the list of columns in the specified table
    cursor.execute(f"PRAGMA table_info({table_name});")
    columns_info = cursor.fetchall()

    # Select a random column from the table
    random_column_index = random.randint(0, len(columns_info) - 1)
    random_column_name = columns_info[random_column_index][1]

    # Construct the query to find a random value in the selected column
    cursor.execute(f"SELECT MIN({random_column_name}) FROM {table_name};")
    min_value = cursor.fetchone()[0]

    # Construct the final query
    query = f"SELECT * FROM {table_name} WHERE {random_column_name} = ?;"

    # Execute the query with the random value
    cursor.execute(query, (min_value,))
    rows = cursor.fetchall()

    # Close the database connection
    conn.close()

    return rows

# Example usage:
# result = random_select_and_query('example.db', 'users')
# print(result)                
              
Tags: