SlideShare a Scribd company logo
1 of 41
SQLAlchemy

The Python SQL Toolkit and Object
Relational Mapper
SQLAlchemy

Muhammet S. AYDIN
Python Developer @ Metglobal
@mengukagan
SQLAlchemy
No ORM Required
● Mature
● High Performing
● Non-opinionated
● Unit of Work
● Function based query construction
● Modular
●
SQLAlchemy

Seperation of mapping & classes
● Eager loading & caching related
objects
● Inheritance mapping
● Raw SQL
●
SQLAlchemy
Drivers:
PostgreSQL
MySQL
MSSQL
SQLite
Sybase
Drizzle
Firebird
Oracle
SQLAlchemy
Core
Engine
Connection
Dialect
MetaData
Table
Column
SQLAlchemy
Core
Engine
Starting point for SQLAlchemy app.
Home base for the database and it's
API.
SQLAlchemy
Core
Connection
Provides functionality for a wrapped
DB-API connection.
Executes SQL statements.
Not thread-safe.
SQLAlchemy
Core
Dialect
Defines the behavior of a specific
database and DB-API combination.
Query generation, execution, result
handling, anything that differs from
other dbs is handled in Dialect.
SQLAlchemy
Core
MetaData
Binds to an Engine or Connection.
Holds the Table and Column metadata
in itself.
SQLAlchemy
Core
Table
Represents a table in the database.
Stored in the MetaData.
SQLAlchemy
Core
Column
Represents a column in a database
table.
SQLAlchemy
Core
Creating an engine:
SQLAlchemy
Core
Creating tables
Register the Table with MetaData.
Define your columns.
Call metadata.create_all(engine)
or
table.create(engine)
SQLAlchemy
Core
Creating tables
SQLAlchemy
Core

More on Columns
Columns have some important
parameters.
index=bool, nullable=bool,
unique=bool, primary_key=bool,
default=callable/scalar,
onupdate=callable/scalar,
autoincrement=bool
SQLAlchemy
Core
Column Types
Integer, BigInteger, String, Unicode,
UnicodeText, Date, DateTime, Boolean,
Text, Time
and
All of the SQL std types.
SQLAlchemy
Core
Insert
insert =
countries_table.insert().values(
code='TR', name='Turkey')
conn.execute(insert)
SQLAlchemy
Core
Select
select([countries_table])
select([ct.c.code, ct.c.name])
select([ct.c.code.label('c')])
SQLAlchemy
Core
Select
select([ct]).where(ct.c.region ==
'Europe & Central Asia')
select([ct]).where(or_(ct.c.region.il
ike('%europe%',
ct.c.region.ilike('%asia%')))
SQLAlchemy
Core
Select A Little Bit Fancy
select([func.count(ct.c.id).label('co
unt'),
ct.c.region]).group_by(ct.c.region).o
rder_by('count DESC')
SELECT count(countries.id) AS count,
countries.region
FROM countries GROUP BY
countries.region ORDER BY count DESC
SQLAlchemy
Core
Update
ct.update().where(ct.c.id ==
1).values(name='Turkey', code='TUR')
SQLAlchemy
Core
Cooler Update
case_list = [(pt.c.id == photo_id,
index+1) for index, photo_id in
enumerate(order_list)]
pt.update().values(photo_order=case(case_l
ist))
UPDATE photos SET photo_order=CASE WHEN
(photos.id = :id_1) THEN :param_1 WHEN
(photos.id = :id_2) THEN :param_2 END
SQLAlchemy
Core
Delete
ct.delete().where(ct.c.id_in([60,71,8
0,97]))
SQLAlchemy

Core
Joins
select([ct.c.name,
dt.c.data]).select_from(ct.join(dt)).
where(ct.c.code == 'TRY')
SQLAlchemy
Core
Joins
select([ct.c.name,
dt.c.data]).select_from(join(ct, dt,
ct.c.id ==
dt.c.country_id)).where(ct.c.code ==
'TRY')
SQLAlchemy
Core
Func
A SQL function generator with
attribute access.
simply put:
func.count() becomes COUNT().
SQLAlchemy
Core
Func
select([func.concat_ws(“ -> “,
ct.c.name, ct.c.code)])
SELECT concat_ws(%(concat_ws_2)s,
countries.name, countries.code) AS
concat_ws_1
FROM countries
SQLAlchemy
ORM
- Built on top of the core
- Applied usage of the Expression
Language
- Class declaration
- Table definition is nested in the
class
SQLAlchemy
ORM
Definition
SQLAlchemy
ORM
Session
Basically it establishes all
connections to the db.
All objects are kept on it through
their lifespan.
Entry point for Query.
SQLAlchemy
ORM
Master / Slave Connection?
master_session =
sessionmaker(bind=engine1)
slave_session =
sessionmaker(bind=engine2)
Session = master_session()
SlaveSession = slave_session()
SQLAlchemy
ORM
Querying
Session.query(Country).filter(Country
.name.startswith('Tur')).all()
Session.query(func.count(Country.id))
.one()
Session.query(Country.name,
Data.data).join(Data).all()
SQLAlchemy
ORM
Querying
Session.query(Country).filter_by(id=1
).update({“name”: “USA”})
Session.query(Country).filter(~Countr
y.region.in_('Europe & Central
Asia')).delete()
SQLAlchemy
ORM
Relationships: One To Many
SQLAlchemy
ORM
Relationships: One To One
SQLAlchemy
ORM
Relationships: Many To Many
SQLAlchemy
ORM
Relationships: Many To Many
SQLAlchemy
ORM
Relationship Loading
SQLAlchemy
ORM
Relationship Loading
SQLAlchemy
ORM
More?
http://sqlalchemy.org
http://github.com/zzzeek/sqlalchemy
irc.freenode.net #sqlalchemy

More Related Content

What's hot (20)

Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java String
Java String Java String
Java String
 
javathreads
javathreadsjavathreads
javathreads
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Java I/O
Java I/OJava I/O
Java I/O
 
Html 5 geolocation api
Html 5 geolocation api Html 5 geolocation api
Html 5 geolocation api
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in Java
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenMichael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 

Similar to An introduction to SQLAlchemy

JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integrationwebhostingguy
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
SQL Server - CLR integration
SQL Server - CLR integrationSQL Server - CLR integration
SQL Server - CLR integrationPeter Gfader
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesKellyn Pot'Vin-Gorman
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guidelineSidney Chen
 
Write Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfWrite Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfEric Xiao
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012Eduardo Castro
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancementsinfusiondev
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Alex Zaballa
 
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020Geir Høydalsvik
 
Wcf data services
Wcf data servicesWcf data services
Wcf data servicesEyal Vardi
 

Similar to An introduction to SQLAlchemy (20)

Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
SQL Server - CLR integration
SQL Server - CLR integrationSQL Server - CLR integration
SQL Server - CLR integration
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the Indices
 
Sql tuning guideline
Sql tuning guidelineSql tuning guideline
Sql tuning guideline
 
Write Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfWrite Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdf
 
Jdbc
JdbcJdbc
Jdbc
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012
 
SQL Server 2008 Performance Enhancements
SQL Server 2008 Performance EnhancementsSQL Server 2008 Performance Enhancements
SQL Server 2008 Performance Enhancements
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
 
MAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptxMAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptx
 
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020MySQL Goes to 8!  FOSDEM 2020 Database Track, January 2nd, 2020
MySQL Goes to 8! FOSDEM 2020 Database Track, January 2nd, 2020
 
Jdbc
JdbcJdbc
Jdbc
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 

Recently uploaded

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

An introduction to SQLAlchemy

Editor's Notes

  1. If you use ORM you just use classes But if you use the core, you can also map the tables to Python classess with mapper()
  2. SQLAlchemy core consists of 6 classes
  3. We define columns as arguments to Table object
  4. Conn is retrieved from engine.connect()
  5. Case – when statement is a way of saying When the condition is met, use this value to update the column.