Skip to content
Exercises · Q3

Q.What is sqlalchemy?

Telangana TsbieTextbookSubjective· 2mImportance★★★★★est
43% · 23/53 Questions
✓ Free question

SQLAlchemy is a Python library that provides both an Object-Relational Mapper (ORM) and a SQL toolkit, letting you work with databases using Python objects or raw SQL with a consistent, database-agnostic interface.

What SQLAlchemy Is

When you write a Python application that needs to store or retrieve data from a database, you face a choice: write raw SQL strings and manage connections manually, or use a tool that bridges the gap between Python's object-oriented world and the relational database world. SQLAlchemy is that bridge.

It operates at two levels:

1. The Core (SQL Expression Language)

This is a toolkit for building SQL queries programmatically in Python. Instead of writing:

cursor.execute("SELECT * FROM students WHERE marks > 75")

you write:

stmt = select(students).where(students.c.marks > 75)
result = connection.execute(stmt)

The advantage? The query is constructed using Python objects and methods. SQLAlchemy translates it into the correct SQL dialect for your database (MySQL, PostgreSQL, SQLite, Oracle, etc.) automatically. You get type safety, composability, and protection from SQL injection.

2. The ORM (Object-Relational Mapper)

This lets you map database tables to Python classes. A row becomes an instance of a class; columns become attributes. You manipulate objects, and SQLAlchemy handles the SQL behind the scenes.

For example, instead of writing INSERT/UPDATE/DELETE statements, you do:

from sqlalchemy.orm import Session

# Define a model
class Student(Base):
    __tablename__ = 'students'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    marks = Column(Integer)

# Use it
session = Session(engine)
new_student = Student(name='Arjun', marks=88)
session.add(new_student)
session.commit()

The ORM translates that add() and commit() into the appropriate SQL INSERT.

Why SQLAlchemy Matters

Database independence: Write once, run on any supported database. Switching from SQLite (development) to PostgreSQL (production) requires changing only the connection string, not your queries.

Pythonic interface: You work with Python objects, not strings of SQL. This means better IDE support, compile-time checks, and less error-prone code.

Relationship handling: The ORM understands foreign keys and relationships. If a Student belongs to a Class, you can navigate student.class_obj.name without writing JOIN queries manually.

Migration and schema management: Tools like Alembic (built on SQLAlchemy) let you version-control your database schema and apply changes incrementally.

Watch out

The ORM adds a layer of abstraction. For simple scripts or performance-critical bulk operations, raw SQL (or the Core layer) is often faster and clearer. Use the ORM when you benefit from object modeling; use Core or raw SQL when you need fine control.

A Complete Example

Suppose you have a books table and want to find all books published after 2020 with a rating above 4.0.

Using raw SQL with a DB-API driver (e.g., sqlite3):

import sqlite3
conn = sqlite3.connect('library.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM books WHERE year > 2020 AND rating > 4.0")
rows = cursor.fetchall()
conn.close()

Using SQLAlchemy Core:

from sqlalchemy import create_engine, Table, MetaData, select

engine = create_engine('sqlite:///library.db')
metadata = MetaData()
books = Table('books', metadata, autoload_with=engine)

with engine.connect() as conn:
    stmt = select(books).where((books.c.year > 2020) & (books.c.rating > 4.0))
    result = conn.execute(stmt)
    for row in result:
        print(row)

Using SQLAlchemy ORM:

from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.orm import declarative_base, Session

Base = declarative_base()

class Book(Base):
    __tablename__ = 'books'
    id = Column(Integer, primary_key=True)
    title = Column(String)
    year = Column(Integer)
    rating = Column(Float)

engine = create_engine('sqlite:///library.db')
session = Session(engine)

books = session.query(Book).filter(Book.year > 2020, Book.rating > 4.0).all()
for book in books:
    print(book.title, book.year, book.rating)

All three produce the same result. The ORM version is the most Pythonic; the Core version gives you SQL-like control with Python syntax; the raw version is the most direct but least portable.

Tip

Start with the ORM for CRUD operations and typical application logic. Drop down to Core or raw SQL for complex analytics, bulk inserts, or when you need to optimize a specific query.

Key Components

ComponentPurpose
EngineManages the connection pool and dialect. Created with create_engine('dialect+driver://user:pass@host/db').
SessionThe ORM's "workspace" for objects. Tracks changes and flushes them to the database on commit().
BaseThe declarative base class. All ORM models inherit from it.
Column, Integer, String, etc.Define table schema in ORM models.
select(), insert(), update(), delete()Core functions to build SQL statements.
relationship()Defines associations between ORM models (one-to-many, many-to-many).
✓Final answer

SQLAlchemy is a Python library providing an ORM and SQL toolkit that lets you interact with relational databases using Python objects (ORM) or programmatic SQL expressions (Core), with automatic translation to the target database's SQL dialect.

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.