HomeInterview QuestionsLet me give an SQL query; write code for it.

Let me give an SQL query; write code for it.

🟡 Medium Coding Junior level
1Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

To execute an arbitrary SQL query from code, you typically need a database driver that can connect to your DBMS, send the query, and fetch results. Below is a concise Python example using the built‑in sqlite3 module, which works similarly for other drivers like psycopg2 (PostgreSQL) or mysql-connector-python (MySQL). 1. Import the driver and establish a connection. 2. Create a cursor object. 3. Execute the query string. 4. Commit if the query modifies data. 5. Fetch results if it’s a SELECT. 6. Close the cursor and connection.

python
import sqlite3

def run_query(db_path, sql_query):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    try:
        cursor.execute(sql_query)
        if sql_query.strip().lower().startswith('select'):
            rows = cursor.fetchall()
            return rows
        else:
            conn.commit()
            return cursor.rowcount
    except sqlite3.Error as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()

Replace sqlite3 with the appropriate driver for your database. The function returns rows for SELECT statements or the number of affected rows for DML. Complexity is O(1) for connection setup and O(n) for fetching results, where n is the number of rows returned. This pattern is portable across most relational databases and demonstrates how to embed an arbitrary SQL query in application code.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500