🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeTop 100 Python SQL & Database MCQs with Answers (2026)

Python database programming isn’t just about writing queries, it’s also about understanding the right tools. From sqlite3 to MySQL and PostgreSQL (via mysql-connector-python and psycopg2), and even NoSQL with pymongo, each plays an important role. You also need a basic understanding of SQLAlchemy and pandas.
In this article, I’ve combined all these concepts into a set of 100 Python SQL & Database MCQs, helping you prepare for your upcoming interviews or exams.
100 Python SQL & Database MCQs
Each of these 100 Python SQL & Database MCQs covers a key concept. Master them, and you’ll be interview-ready.
Q1. Which built-in Python module is commonly used to interact with SQLite databases?
A. pymysql
B. sqlite3
C. mongodb
D. sqlalchemy
Show Answer
Answer: B
The sqlite3 module is a standard library module in Python that provides a lightweight disk-based database without requiring a separate server process.
Q2. What is the primary role of a cursor object in Python database programming?
A. To establish a network connection
B. To execute SQL commands and traverse results
C. To close the database file
D. To encrypt the database
Show Answer
Answer: B
The cursor object allows Python code to execute SQL commands and fetch results from the database query.
Q3. Which method is used to save changes made to a database permanently in Python?
A. save()
B. execute()
C. commit()
D. update()
Show Answer
Answer: C
The commit() method is called on the connection object to commit the current transaction and save changes permanently.
Q4. In Python’s sqlite3 module, which placeholder is recommended for parameter substitution to prevent SQL injection?
A. %s
B. ?
C. :1
D. $
Show Answer
Answer: B
The sqlite3 module uses the question mark ? style as a placeholder for parameter substitution.
Q5. Which method is used to retrieve all rows from the result set of a query?
A. fetchone()
B. fetchmany()
C. fetchall()
D. getall()
Show Answer
Answer: C
The fetchall() method retrieves all rows of a query result set and returns them as a list of tuples.
Q6. What happens if you do not call commit() after executing an INSERT or UPDATE statement in a Python database script?
A. The database is automatically updated
B. An error is raised immediately
C. No changes are saved to the database
D. The script crashes
Show Answer
Answer: C
Without calling commit(), the transaction is rolled back upon closing the connection, and no changes are saved.
Q7. Which standard Python library feature acts as a generic interface for database API specifications?
A. DB-API 2.0
B. JDBC
C. ODBC
D. PEP 8
Show Answer
Answer: A
Python DB-API 2.0 (PEP 249) defines a standard interface for database access modules in Python.
Q8. To connect to a MySQL database using Python, which third-party library is most commonly installed?
A. mysql-connector-python
B. mysql-server
C. python-mysql
D. db-mysql
Show Answer
Answer: A
The mysql-connector-python is the official Oracle driver that allows Python to connect to MySQL databases.
Q9. What is the correct way to close a database connection object named conn?
A. conn.close()
B. close(conn)
C. conn.end()
D. conn.disconnect()
Show Answer
Answer: A
The close() method is called on the connection object to close the database connection properly.
Q10. Which exception is raised for database errors defined by the Python DB-API?
A. DatabaseError
B. SQLError
C. ConnectionError
D. DataError
Show Answer
Answer: ADatabaseError is the base exception class for errors related to the database in the DB-API specification.
Q11. Which method retrieves only the next row from the result set?
A. fetchall()
B. fetchone()
C. fetchrow()
D. nextrow()
Show Answer
Answer: Bfetchone() retrieves the next row of a query result set, returning a single tuple or None if no more rows are available.
Q12. In the context of SQL injection attacks, what is the safest way to construct SQL queries in Python?
A. String concatenation
B. Using f-strings
C. Using parameter substitution
D. Using format()
Show Answer
Answer: C
Parameter substitution allows the database driver to handle escaping of special characters, preventing SQL injection.
Q13. Which method is used to execute a SQL command that modifies the database schema, like CREATE TABLE?
A. commit()
B. execute()
C. run()
D. modify()
Show Answer
Answer: B
The execute() method is used to execute any SQL statement, including DDL commands like CREATE TABLE.
Q14. What does the rowcount attribute of a cursor object return?
A. The total number of rows in the table
B. The number of rows affected by the last SQL statement
C. The number of columns in the result
D. The current row index
Show Answer
Answer: B
The rowcount attribute returns the number of rows affected by an UPDATE, INSERT, or DELETE statement.
Q15. Which of the following is NOT a valid standard DB-API exception?
A. IntegrityError
B. OperationalError
C. SyntaxError
D. ProgrammingError
Show Answer
Answer: CSyntaxError is a standard Python exception, while the others are specific database exceptions defined in DB-API.
Q16. When using the psycopg2 library for PostgreSQL, which placeholder style is commonly used?
A. ?
B. %s
C. :var
D. @param
Show Answer
Answer: B
Psycopg2 uses the Python extended format codes, specifically %s, for variable binding.
Q17. How can you create an in-memory SQLite database that exists only for the duration of the script?
A. sqlite3.connect(“temp.db”)
B. sqlite3.connect(“:memory:”)
C. sqlite3.connect(“ram.db”)
D. sqlite3.memory_connect()
Show Answer
Answer: B
Passing the string ":memory:" to the connect function creates an in-memory database.
Q18. Which method executes the same SQL command multiple times with different parameters?
A. execute()
B. executemany()
C. executescript()
D. executeall()
Show Answer
Answer: B
The executemany() method is efficient for bulk operations like inserting multiple rows.
Q19. In SQLAlchemy, which class represents the core structure for database interaction without using ORM?
A. Session
B. Engine
C. Model
D. Schema
Show Answer
Answer: B
The Engine class is the starting point for SQLAlchemy, managing the connection pool and dialect.
Q20. What is the purpose of the lastrowid attribute in a cursor object?
A. Returns the ID of the last deleted row
B. Returns the ID of the last inserted row
C. Returns the ID of the last updated row
D. Returns the total count of rows
Show Answer
Answer: B
The lastrowid attribute provides the row ID of the last inserted row (useful for auto-increment fields).
Q21. Which Python library is widely used for interacting with MongoDB?
A. pymongo
B. mysqlclient
C. sqlite3
D. psycopg2
Show Answer
Answer: APyMongo is the recommended driver for connecting Python applications to MongoDB databases.
Q22. In SQLite, which method allows executing multiple SQL statements separated by semicolons at once?
A. execute()
B. executescript()
C. executemany()
D. batch()
Show Answer
Answer: Bexecutescript() executes a script of multiple SQL statements issued as a single string.
Q23. What is SQL Injection?
A. A method to insert data faster
B. A security vulnerability allowing malicious SQL code execution
C. A database backup technique
D. A Python library for SQL
Show Answer
Answer: B
SQL Injection occurs when untrusted user data is sent to an interpreter as part of a command or query.
Q24. Which of the following correctly describes the behavior of the ‘with’ statement when opening a database connection?
A. It automatically closes the connection
B. It automatically commits the transaction
C. It automatically creates a table
D. It disables error handling
Show Answer
Answer: A
The context manager ensures that resources like database connections are closed properly after execution.
Q25. In MySQL Connector Python, which argument in the connect() method specifies the database name?
A. db
B. schema
C. database
D. name
Show Answer
Answer: C
The database parameter is used to specify the name of the database to connect to.
Q26. Which method on a connection object is used to cancel a transaction?
A. commit()
B. rollback()
C. cancel()
D. undo()
Show Answer
Answer: B
The rollback() method reverts the database to the state before the transaction began.
Q27. What does the description attribute of a cursor object return?
A. The SQL query string
B. Metadata about the columns in the result set
C. The number of rows
D. The database name
Show Answer
Answer: B
The description attribute returns a tuple of column information tuples, describing the result columns.
Q28. Which exception indicates a violation of a database constraint, like a primary key conflict?
A. ProgrammingError
B. IntegrityError
C. OperationalError
D. InterfaceError
Show Answer
Answer: BIntegrityError is raised when the relational integrity of the database is affected (e.g., duplicate key).
Q29. In PyMongo, what does the find() method return?
A. A list of dictionaries
B. A single document
C. A Cursor object
D. A tuple
Show Answer
Answer: C
The find() method returns a Cursor instance which can be iterated over to access documents.
Q30. Which Python function allows you to read SQL results directly into a Pandas DataFrame?
A. pd.read_table()
B. pd.read_sql()
C. pd.import_sql()
D. pd.load_db()
Show Answer
Answer: Bpd.read_sql() is a Pandas function that executes a SQL query and loads the result into a DataFrame.
Q31. What is the correct syntax to create a cursor object from a connection object conn?
A. conn.create_cursor()
B. cursor = conn.cursor()
C. cursor(conn)
D. conn.new_cursor()
Show Answer
Answer: B
The standard DB-API method to create a cursor is calling .cursor() on the active connection object.
Q32. Which library is an ORM (Object Relational Mapper) for Python?
A. sqlite3
B. SQLAlchemy
C. psycopg2
D. PyMongo
Show Answer
Answer: B
SQLAlchemy provides a full suite of well-known enterprise-level persistence patterns and ORM capabilities.
Q33. In SQLite, which data type is used to store floating-point numbers?
A. INTEGER
B. TEXT
C. REAL
D. FLOAT
Show Answer
Answer: C
SQLite uses the REAL data type to store floating-point values.
Q34. Which exception is raised when a SQL statement has a syntax error?
A. DatabaseError
B. ProgrammingError
C. SyntaxError
D. DataError
Show Answer
Answer: BProgrammingError is raised for errors caused by programming errors like incorrect SQL syntax.
Q35. How do you install the MySQL connector for Python using pip?
A. pip install mysql
B. pip install mysql-connector
C. pip install mysql-connector-python
D. pip install mysqlclient
Show Answer
Answer: C
The official connector package name is mysql-connector-python.
Q36. Which dictionary-style placeholder does SQLite support for named parameters?
A. :name
B. %(name)s
C. $name
D. @name
Show Answer
Answer: A
SQLite supports named placeholders using a colon followed by the name, like :name.
Q37. In Pandas, what does the chunksize argument in read_sql() do?
A. Limits the total rows read
B. Returns an iterator for reading data in chunks
C. Skips rows
D. Sets the memory limit
Show Answer
Answer: B
The chunksize argument returns an iterator that yields DataFrames of the specified size.
Q38. What is the default isolation level for a connection in sqlite3?
A. None
B. SERIALIZABLE
C. READ COMMITTED
D. AUTOCOMMIT
Show Answer
Answer: B
By default, sqlite3 uses SERIALIZABLE isolation, ensuring the highest level of isolation.
Q39. Which method is used to convert a SQL result row into a dictionary instead of a tuple in sqlite3?
A. cursor.set_factory(dict)
B. conn.row_factory = sqlite3.Row
C. cursor.as_dict(True)
D. fetchdict()
Show Answer
Answer: B
Setting row_factory to sqlite3.Row allows accessing columns by name.
Q40. What is the function of the executemany() method in Python DB-API?
A. Executes multiple different SQL queries
B. Executes a SQL query against multiple parameter sequences
C. Executes a script
D. Manages multiple database connections
Show Answer
Answer: B
It prepares a database operation and executes it against all parameter sequences found in the sequence.
Q41. Which of the following represents a connection string URI for SQLite?
A. sqlite:///filename.db
B. sqlite:filename.db
C. file:sqlite://filename.db
D. db:sqlite://filename.db
Show Answer
Answer: A
The standard URI format for SQLite often uses three slashes for relative paths (e.g., sqlite:///example.db).
Q42. What is the correct way to insert a document into a MongoDB collection using PyMongo?
A. collection.add()
B. collection.insert()
C. collection.insert_one()
D. collection.save()
Show Answer
Answer: C
In newer versions of PyMongo, insert_one() is used to insert a single document.
Q43. Which of the following is a valid argument for the sqlite3.connect() function?
A. timeout
B. user
C. password
D. port
Show Answer
Answer: Atimeout specifies how long the connection should wait for a lock to go away.
Q44. Which method allows you to write a Pandas DataFrame to a SQL database?
A. df.to_sql()
B. df.write_sql()
C. df.export_sql()
D. df.save_sql()
Show Answer
Answer: A
The to_sql() method writes records stored in a DataFrame to a SQL database.
Q45. What exception is raised when the connection to the database fails?
A. ConnectionError
B. OperationalError
C. InterfaceError
D. DatabaseError
Show Answer
Answer: BOperationalError covers errors related to the database operation, such as connection failures.
Q46. Which method is used to delete records from a MongoDB collection?
A. collection.discard()
B. collection.remove()
C. collection.delete_one()
D. collection.erase()
Show Answer
Answer: Cdelete_one() deletes a single document matching the filter criteria.
Q47. In SQLAlchemy, what is the role of the Session class?
A. To create tables
B. To manage the database connection and transactions
C. To define models
D. To generate SQL strings
Show Answer
Answer: B
The Session is the ORM’s handle to the database, managing transactions and object states.
Q48. What is the purpose of the isolation_level parameter in sqlite3.connect()?
A. To set the database encryption level
B. To control the transaction locking behavior
C. To limit user access
D. To set the file permissions
Show Answer
Answer: B
The isolation_level parameter controls how transactions are handled (e.g., None for autocommit).
Q49. How can you handle database errors in Python gracefully?
A. Using if statements
B. Using try…except blocks
C. Using assertions
D. Using debug mode
Show Answer
Answer: B
Wrap database code in try...except blocks to catch specific database exceptions.
Q50. Which method is used to check if a table exists in an SQLite database?
A. sqlite3.table_exists()
B. Querying sqlite_master table
C. conn.check_table()
D. cursor.table_list()
Show Answer
Answer: B
You can query the sqlite_master system table to check if a table name exists.
Q51. What does the ‘autocommit’ feature in a database connection imply?
A. Automatic rollback on error
B. Every SQL statement is a transaction and committed immediately
C. Automatic connection closing
D. Batch processing of queries
Show Answer
Answer: B
In autocommit mode, each SQL statement is treated as a transaction and is committed immediately.
Q52. Which function is used to retrieve the ID of the last inserted row in SQLite?
A. cursor.last_row_id()
B. conn.insert_id()
C. cursor.lastrowid
D. db.get_id()
Show Answer
Answer: C
The attribute cursor.lastrowid stores the row ID of the last successfully inserted row.
Q53. In PyMongo, how do you select only specific fields from a document?
A. Using the filter parameter
B. Using the projection parameter
C. Using the fields parameter
D. Using the select parameter
Show Answer
Answer: B
The projection parameter (a dictionary) in find() specifies which fields to include or exclude.
Q54. Which DB-API exception is raised for errors due to division by zero or value out of range?
A. DataError
B. DatabaseError
C. ProgrammingError
D. OperationalError
Show Answer
Answer: ADataError handles errors related to data processing, such as numeric overflow or division by zero.
Q55. What is the first argument passed to the sqlite3.connect() function?
A. Host address
B. File path of the database
C. User name
D. Port number
Show Answer
Answer: B
For SQLite, the first argument is the path to the database file (or :memory:).
Q56. Which of the following is a primary advantage of using an ORM like SQLAlchemy?
A. Direct SQL execution
B. Database abstraction and portability
C. Slower performance
D. Manual transaction handling
Show Answer
Answer: B
ORMs allow developers to work with Python objects, abstracting away the underlying SQL and database specifics.
Q57. How do you filter results in a MongoDB query using PyMongo?
A. Passing a WHERE clause string
B. Passing a dictionary to find()
C. Using filter() method
D. Using query strings
Show Answer
Answer: B
You pass a query dictionary to the find() method to filter documents.
Q58. In Pandas to_sql(), what does the parameter if_exists=’replace’ do?
A. Replaces rows with same ID
B. Drops the table before inserting new values
C. Raises a ValueError
D. Appends data
Show Answer
Answer: B
It drops the existing table and creates a new one before inserting the DataFrame data.
Q59. What is the output type of cursor.fetchone() if no rows are available?
A. []
B. ()
C. None
D. False
Show Answer
Answer: C
If no more rows are available, fetchone() returns None.
Q60. Which exception is raised when the database encounters an internal error?
A. InternalError
B. DatabaseError
C. SystemError
D. OperationalError
Show Answer
Answer: AInternalError is raised when the database encounters an internal error (e.g., cursor not valid).
Q61. Which of the following correctly explains the concept of ‘Connection Pooling’?
A. Keeping connections open for reuse to improve performance
B. Storing data in memory
C. Closing connections immediately after use
D. Encrypting database connections
Show Answer
Answer: A
Connection pooling maintains a cache of database connections to reduce overhead of creating new connections.
Q62. How do you connect to a PostgreSQL database using Python?
A. import postgres
B. import psycopg2
C. import pgsql
D. import postgresql
Show Answer
Answer: Bpsycopg2 is the most popular PostgreSQL adapter for Python.
Q63. Which method is used to rename a column in SQLite?
A. ALTER TABLE … RENAME COLUMN
B. CHANGE COLUMN
C. MODIFY COLUMN
D. RENAME COLUMN
Show Answer
Answer: A
The SQL syntax ALTER TABLE table_name RENAME COLUMN old TO new is used in SQLite.
Q64. What is the return value of cursor.execute() for a SELECT statement?
A. List of rows
B. The cursor object itself
C. Number of rows
D. True/False
Show Answer
Answer: B
The execute() method returns the cursor object, allowing method chaining, though results are fetched separately.
Q65. Which SQLAlchemy function is used to establish a connection to the database?
A. sqlalchemy.connect()
B. sqlalchemy.create_engine()
C. sqlalchemy.start()
D. sqlalchemy.open()
Show Answer
Answer: Bcreate_engine() produces an Engine object based on a URL, which handles connections.
Q66. In PyMongo, what is the difference between insert_one() and insert_many()?
A. insert_one is faster
B. insert_many inserts a list of documents
C. insert_one creates a collection
D. insert_many creates a database
Show Answer
Answer: Binsert_many() accepts a list of documents and inserts them in a single operation.
Q67. Which parameter in Pandas read_sql() prevents SQL injection by passing parameters safely?
A. safe_query
B. params
C. injection_safe
D. security
Show Answer
Answer: B
The params parameter passes arguments safely to the underlying database driver.
Q68. What does the ‘detect_types’ parameter in sqlite3.connect() do?
A. Detects primary keys
B. Detects data types of columns automatically
C. Detects table names
D. Detects foreign keys
Show Answer
Answer: B
It controls how types are converted when fetching data, e.g., parsing date/timestamp strings.
Q69. Which module is typically used to connect Python to Oracle databases?
A. oradb
B. cx_Oracle
C. oracle-python
D. pyoracle
Show Answer
Answer: Bcx_Oracle (now evolving into python-oracledb) is the standard module for Oracle Database connectivity.
Q70. Which Python method executes an SQL script stored in a file?
A. run_script()
B. executescript()
C. load_sql()
D. batch_execute()
Show Answer
Answer: Bexecutescript() is used to execute multiple SQL statements at once in SQLite.
Q71. What is the primary key constraint violation categorized as in Python DB-API?
A. ProgrammingError
B. DataError
C. IntegrityError
D. InternalError
Show Answer
Answer: C
Integrity constraints like unique or primary key violations raise IntegrityError.
Q72. How can you convert a SQLite row result to a standard Python dictionary?
A. dict(row)
B. row.to_dict()
C. cursor.dict_fetch()
D. No direct method
Show Answer
Answer: A
If the row_factory is set to sqlite3.Row, dict(row) converts it to a dictionary.
Q73. In MongoDB, what function sorts the result documents?
A. order_by()
B. sort()
C. sort_by()
D. arrange()
Show Answer
Answer: B
In PyMongo, the sort() method is called on a cursor to sort documents.
Q74. What does the ‘check_same_thread’ argument do in sqlite3.connect()?
A. Checks for thread safety
B. Restricts connection usage to the creating thread
C. Allows multi-threading
D. Checks for duplicate threads
Show Answer
Answer: B
By default, SQLite checks that the connection is used in the same thread that created it.
Q75. Which library component is essential for defining database schema in SQLAlchemy ORM?
A. declarative_base
B. schema_builder
C. database_model
D. table_def
Show Answer
Answer: Adeclarative_base() creates a base class for declarative class definitions.
Q76. What type of object does the Pandas read_sql_query() function return?
A. SQLCursor
B. DataFrame
C. List of tuples
D. Dictionary
Show Answer
Answer: B
It reads the result of a SQL query directly into a Pandas DataFrame.
Q77. Which exception is raised for errors related to the database interface rather than the database itself?
A. DatabaseError
B. InterfaceError
C. OperationalError
D. ProgrammingError
Show Answer
Answer: BInterfaceError is raised for errors related to the database module interface, not the database engine.
Q78. How do you limit the number of rows returned in a MongoDB query?
A. limit()
B. take()
C. top()
D. max_rows()
Show Answer
Answer: A
The limit() method on a cursor restricts the number of documents returned.
Q79. What is the syntax to update data in a SQLite table using Python?
A. table.update()
B. cursor.execute(“UPDATE …”)
C. conn.update()
D. db.modify()
Show Answer
Answer: B
Standard SQL UPDATE statements are executed via the cursor’s execute() method.
Q80. Which Python module provides support for DB-API 2.0?
A. All database connectors (sqlite3, psycopg2, etc.)
B. Only sqlite3
C. The dbapi module
D. The sys module
Show Answer
Answer: A
Most standard Python database connectors adhere to the DB-API 2.0 specification (PEP 249).
Q81. Which function is used to determine the number of rows modified?
A. cursor.rowcount
B. cursor.rownumber
C. conn.affected_rows
D. len(cursor)
Show Answer
Answer: Acursor.rowcount returns the number of rows affected by the last execute.
Q82. What happens if you try to fetch data after closing the cursor?
A. Returns empty list
B. Returns None
C. Raises ProgrammingError or InterfaceError
D. Creates a new connection
Show Answer
Answer: C
Attempting to operate on a closed cursor raises an error because the resource is no longer available.
Q83. In SQLAlchemy, what is ‘MetaData’ used for?
A. Storing user data
B. Managing database schema information
C. Handling connections
D. Query optimization
Show Answer
Answer: B
MetaData is a registry that stores information about tables, columns, and schema definitions.
Q84. Which method is used to group data in MongoDB aggregation?
A. group()
B. aggregate()
C. collect()
D. combine()
Show Answer
Answer: B
Aggregation operations are performed using the aggregate() method on a collection.
Q85. Which of the following is a ‘NoSQL’ database?
A. MySQL
B. PostgreSQL
C. MongoDB
D. SQLite
Show Answer
Answer: C
MongoDB is a document-oriented NoSQL database, while others listed are relational SQL databases.
Q86. How do you select specific columns using Pandas read_sql?
A. Use the columns parameter
B. Use SQL SELECT statement in the query
C. Use the filter parameter
D. Set projection=True
Show Answer
Answer: B
The SQL query string passed to read_sql determines which columns are returned.
Q87. What is the function of conn.commit() inside a try block?
A. To start a transaction
B. To save successful changes
C. To handle errors
D. To create a backup
Show Answer
Answer: B
It commits the transaction if the code executes successfully without raising exceptions.
Q88. Which argument is required to connect to a remote MySQL server?
A. file path
B. host
C. memory
D. driver
Show Answer
Answer: B
The host argument (IP address or hostname) specifies the location of the remote database server.
Q89. What is the correct way to pass multiple parameters to cursor.execute()?
A. execute(query, param1, param2)
B. execute(query, (param1, param2))
C. execute(query, [param1, param2])
D. execute(query + params)
Show Answer
Answer: B
Parameters must be passed as a sequence (tuple or list) in the second argument.
Q90. In SQLAlchemy, which method is used to add an object to the session?
A. session.insert()
B. session.add()
C. session.save()
D. session.attach()
Show Answer
Answer: B
The session.add() method places an object into the session to be persisted.
Q91. Which method efficiently handles bulk inserts in Pandas DataFrames?
A. df.to_sql(method=’multi’)
B. df.to_sql(fast=True)
C. df.to_sql(batch=True)
D. df.to_sql(quick=True)
Show Answer
Answer: A
The method='multi' argument passes multiple values in a single INSERT statement.
Q92. What is the purpose of the ‘factory’ parameter in sqlite3.connect?
A. To create connections
B. To specify a custom Connection class
C. To create tables
D. To generate keys
Show Answer
Answer: B
The factory parameter allows you to provide a subclass of Connection.
Q93. How is the ‘LIKE’ operator used in a parameterized query in Python?
A. LIKE ? with % in the parameter
B. LIKE %?%
C. LIKE ‘%?%’
D. LIKE {param}
Show Answer
Answer: A
The wildcard characters % should be part of the parameter value, not the query string.
Q94. Which exception is raised when a table referenced in a query does not exist?
A. TableNotFoundError
B. OperationalError
C. SchemaError
D. LookupError
Show Answer
Answer: B
Errors like “no such table” usually result in an OperationalError in sqlite3.
Q95. In PyMongo, what does _id represent in a document?
A. A random string
B. The primary key field
C. A foreign key
D. The document size
Show Answer
Answer: B
The _id field serves as the unique identifier (primary key) for documents in a collection.
Q96. Which Python feature is commonly used to manage database resources automatically?
A. Garbage Collection
B. Context Managers (with statement)
C. Decorators
D. Generators
Show Answer
Answer: B
Context managers ensure that connections or cursors are closed even if errors occur.
Q97. What is the role of the ‘backups’ module in Python SQL interaction?
A. It is a standard module for database backups
B. It does not exist in the standard library
C. It creates database links
D. It handles encryption
Show Answer
Answer: B
There is no standard ‘backups’ module; backup logic is usually handled by specific database tools or custom scripts.
Q98. Which of the following is true regarding cursor.arraysize?
A. Specifies the number of rows to fetch at a time
B. Specifies the number of columns
C. Specifies the data type
D. Specifies the connection speed
Show Answer
Answer: A
The arraysize attribute suggests the number of rows to fetch with fetchmany().
Q99. What command is used to remove a table from an SQLite database?
A. REMOVE TABLE
B. DROP TABLE
C. DELETE TABLE
D. TRUNCATE TABLE
Show Answer
Answer: B
The SQL standard DROP TABLE table_name command removes the table structure.
Q100. Why is it recommended to use ‘finally’ block in database operations?
A. To execute code regardless of exceptions
B. To raise errors
C. To print variables
D. To start transactions
Show Answer
Answer: A
The finally block ensures resources like database connections are closed even if an error occurs.
Conclusion
Congratulations, you made it this far! I hope you went through all 100 Python SQL & Database MCQs and were able to solve most of them. If not, or if some questions are difficult, that’s okay, all you need is a little revision, and you’ll be ready to go.
If you are completely new to SQL in Python, check out this beginner-friendly guide: SQL in Python
You can also explore these helpful tutorials to strengthen your understanding: Flask + MySQL Database Connection, Flask PostgreSQL with SQLAlchemy, Python MySQL Complete Guide, Django MySQL Setup, and Django PostgreSQL Setup. These will give you practical knowledge of working with databases in real-world applications.
At last, make sure to bookmark this page for later revision. Just press Ctrl + D on Windows or Cmd + D on Mac so you can easily revisit these Python SQL & Database MCQs anytime you need.


