Selectables, Tables, FROM objects
The term “selectable” refers to any object that rows can be selected from;in SQLAlchemy, these objects descend from FromClause
and theirdistinguishing feature is their FromClause.c
attribute, which isa namespace of all the columns contained within the FROM clause (theseelements are themselves ColumnElement
subclasses).
sqlalchemy.sql.expression.
alias
(selectable, name=None, flat=False)- Return an
Alias
object.
An Alias
represents any FromClause
with an alternate name assigned within SQL, typically using the AS
clause when generated, e.g. SELECT * FROM table AS aliasname
.
Similar functionality is available via thealias()
methodavailable on all FromClause
subclasses. In terms of aSELECT object as generated from the select()
function, theSelectBase.alias()
method returns an Alias
orsimilar object which represents a named, parenthesized subquery.
When an Alias
is created from a Table
object,this has the effect of the table being renderedas tablename AS aliasname
in a SELECT statement.
For select()
objects, the effect is that of creating a namedsubquery, i.e. (select …) AS aliasname
.
The name
parameter is optional, and provides the nameto use in the rendered SQL. If blank, an “anonymous” namewill be deterministically generated at compile time.Deterministic means the name is guaranteed to be unique againstother constructs used in the same statement, and will also be thesame name for each successive compilation of the same statementobject.
- Parameters
selectable – any
FromClause
subclass,such as a table, select statement, etc.name – string name to be assigned as the alias.If
None
, a name will be deterministically generatedat compile time.
Will be passed through to if the given selectableis an instance of Join
- see Join.alias()
for details.
New in version 0.9.0.
sqlalchemy.sql.expression.
except
(selects, *kwargs)[](https://docs.sqlalchemy.org/en/13/core/#sqlalchemy.sql.expression.except)- Return an
EXCEPT
of multiple selectables.
The returned object is an instance ofCompoundSelect
.
- *selects
a list of
Select
instances.**kwargs
- available keyword arguments are the same as those of
select()
.
The returned object is an instance ofCompoundSelect
.
- *selects
a list of
Select
instances.**kwargs
- available keyword arguments are the same as those of
select()
.
sqlalchemy.sql.expression.
exists
(*args, **kwargs)- Construct a new
Exists
against an existingSelect
object.
Calling styles are of the following forms:
- # use on an existing select()
- s = select([table.c.col1]).where(table.c.col2==5)
- s = exists(s)
- # construct a select() at once
- exists(['*'], **select_arguments).where(criterion)
- # columns argument is optional, generates "EXISTS (SELECT *)"
- # by default.
- exists().where(table.c.col2==5)
The returned object is an instance ofCompoundSelect
.
- *selects
a list of
Select
instances.**kwargs
- available keyword arguments are the same as those of
select()
.
sqlalchemy.sql.expression.
intersectall
(selects, *kwargs_)- Return an
INTERSECT ALL
of multiple selectables.
The returned object is an instance ofCompoundSelect
.
- *selects
a list of
Select
instances.**kwargs
- available keyword arguments are the same as those of
select()
.
sqlalchemy.sql.expression.
join
(left, right, onclause=None, isouter=False, full=False)- Produce a
Join
object, given twoFromClause
expressions.
E.g.:
- j = join(user_table, address_table,
- user_table.c.id == address_table.c.user_id)
- stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
- SELECT user.id, user.name FROM user
- JOIN address ON user.id = address.user_id
Similar functionality is available given anyFromClause
object (e.g. such as a Table
) usingthe FromClause.join()
method.
- Parameters
right – the right side of the join; this is any
FromClause
object such as aTable
object, andmay also be a selectable-compatible object such as an ORM-mappedclass.onclause – a SQL expression representing the ON clause of thejoin. If left at
None
,FromClause.join()
will attempt tojoin the two tables based on a foreign key relationship.isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
if True, render a FULL OUTER JOIN, instead of JOIN.
New in version 1.1.
See also
FromClause.join()
- method form, based on a given left side
Join
- the type of object produced
sqlalchemy.sql.expression.
lateral
(selectable, name=None)- Return a
Lateral
object.
Lateral
is an Alias
subclass that representsa subquery with the LATERAL keyword applied to it.
The special behavior of a LATERAL subquery is that it appears in theFROM clause of an enclosing SELECT, but may correlate to otherFROM clauses of that SELECT. It is a special case of subqueryonly supported by a small number of backends, currently more recentPostgreSQL versions.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.
outerjoin
(left, right, onclause=None, full=False)- Return an
OUTER JOIN
clause element.
The returned object is an instance of Join
.
Similar functionality is also available via theouterjoin()
method on anyFromClause
.
- Parameters
To chain joins together, use the FromClause.join()
orFromClause.outerjoin()
methods on the resultingJoin
object.
sqlalchemy.sql.expression.
select
(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)- Construct a new
Select
.
Similar functionality is also available via theFromClause.select()
method on any FromClause
.
All arguments which accept ClauseElement
arguments alsoaccept string arguments, which will be converted as appropriate intoeither text()
or literal_column()
constructs.
See also
Selecting - Core Tutorial description ofselect()
.
A list of ColumnElement
or FromClause
objects which will form the columns clause of the resultingstatement. For those objects that are instances ofFromClause
(typically Table
or Alias
objects), the FromClause.c
collection is extractedto form a collection of ColumnElement
objects.
This parameter will also accept Text
constructs asgiven, as well as ORM-mapped classes.
Note
The select.columns
parameter is not availablein the method form of select()
, e.g.FromClause.select()
.
See also
-
A ClauseElement
expression which will be used to form theWHERE
clause. It is typically preferable to add WHEREcriterion to an existing Select
using method chainingwith Select.where()
.
See also
-
A list of ClauseElement
objects which will be added to theFROM
clause of the resulting statement. This is equivalentto calling Select.select_from()
using method chaining onan existing Select
object.
See also
Select.select_from()
- full description of explicitFROM clause specification.
-
legacy autocommit parameter.
Deprecated since version 0.6: The select.autocommit
parameter is deprecated and will be removed in a future release. Please refer to the Connection.execution_options.autocommit
parameter in conjunction with the the Executable.execution_options()
method in order to affect the autocommit behavior for a statement.
-
bind=None – an Engine
or Connection
instanceto which theresulting Select
object will be bound. TheSelect
object will otherwise automatically bind towhatever Connectable
instances can be located withinits contained ClauseElement
members.
-
indicates that this Select
object should have itscontained FromClause
elements “correlated” to an enclosingSelect
object. It is typically preferable to specifycorrelations on an existing Select
construct usingSelect.correlate()
.
See also
Select.correlate()
- full description of correlation.
-
when True
, applies a DISTINCT
qualifier to the columnsclause of the resulting statement.
The boolean argument may also be a column expression or listof column expressions - this is a special calling form whichis understood by the PostgreSQL dialect to render theDISTINCT ON (<columns>)
syntax.
distinct
is also available on an existing Select
object via the distinct()
method.
See also
-
when
True
, appliesFOR UPDATE
to the end of theresulting statement.
for_update
accepts various string values interpreted byspecific backends, including:
"read"
- on MySQL, translates toLOCK IN SHARE MODE
;on PostgreSQL, translates toFOR SHARE
.
"nowait"
- on PostgreSQL and Oracle, translates toFOR UPDATE NOWAIT
.
"read_nowait"
- on PostgreSQL, translates toFOR SHARE NOWAIT
.
See also
Select.with_for_update()
- improved API forspecifying the FOR UPDATE
clause.
-
a list of ClauseElement
objects which will comprise theGROUP BY
clause of the resulting select. This parameteris typically specified more naturally using theSelect.group_by()
method on an existing Select
.
See also
-
a ClauseElement
that will comprise the HAVING
clauseof the resulting select when GROUP BY
is used. This parameteris typically specified more naturally using theSelect.having()
method on an existing Select
.
See also
-
a numerical value which usually renders as a LIMIT
expression in the resulting select. Backends that don’tsupport LIMIT
will attempt to provide similarfunctionality. This parameter is typically specified morenaturally using the Select.limit()
method on an existingSelect
.
See also
-
a numeric value which usually renders as an OFFSET
expression in the resulting select. Backends that don’tsupport OFFSET
will attempt to provide similarfunctionality. This parameter is typically specified more naturallyusing the Select.offset()
method on an existingSelect
.
See also
-
a scalar or list of ClauseElement
objects which willcomprise the ORDER BY
clause of the resulting select.This parameter is typically specified more naturally using theSelect.order_by()
method on an existing Select
.
See also
-
when True
, the statement will be generated using labelsfor each column in the columns clause, which qualify eachcolumn with its parent table’s (or aliases) name so that nameconflicts between columns in different tables don’t occur.The format of the label is Select
object will use thesenames as well for targeting column members.
This parameter can also be specified on an existingSelect
object using the Select.apply_labels()
method.
See also
sqlalchemy.sql.expression.
subquery
(alias, *args, **kwargs)Return an
Alias
object derivedfrom aSelect
.- name
- alias name
args, *kwargs
all other arguments are delivered to the
select()
function.
sqlalchemy.sql.expression.
table
(name, *columns)- Produce a new
TableClause
.
The object returned is an instance of TableClause
, whichrepresents the “syntactical” portion of the schema-levelTable
object.It may be used to construct lightweight table constructs.
Changed in version 1.0.0: expression.table()
can nowbe imported from the plain sqlalchemy
namespace like anyother SQL element.
- Parameters
columns – A collection of
expression.column()
constructs.
sqlalchemy.sql.expression.
tablesample
(selectable, sampling, name=None, seed=None)- Return a
TableSample
object.
TableSample
is an Alias
subclass that representsa table with the TABLESAMPLE clause applied to it.tablesample()
is also available from the FromClause
class via theFromClause.tablesample()
method.
The TABLESAMPLE clause allows selecting a randomly selected approximatepercentage of rows from a table. It supports multiple sampling methods,most commonly BERNOULLI and SYSTEM.
e.g.:
- from sqlalchemy import func
- selectable = people.tablesample(
- func.bernoulli(1),
- name='alias',
- seed=func.random())
- stmt = select([selectable.c.people_id])
Assuming people
with a column people_id
, the abovestatement would render as:
- SELECT alias.people_id FROM
- people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
- REPEATABLE (random())
New in version 1.1.
- Parameters
sampling – a
float
percentage between 0 and 100 orfunctions.Function
.seed – any real-valued SQL expression. When specified, theREPEATABLE sub-clause is also rendered.
The returned object is an instance ofCompoundSelect
.
A similar union()
method is available on allFromClause
subclasses.
- *selects
a list of
Select
instances.**kwargs
- available keyword arguments are the same as those of
select()
.
The returned object is an instance ofCompoundSelect
.
A similar union_all()
method is available on allFromClause
subclasses.
- *selects
a list of
Select
instances.**kwargs
- available keyword arguments are the same as those of
select()
.
- class
sqlalchemy.sql.expression.
Alias
(*arg, **kw) - Bases:
sqlalchemy.sql.expression.FromClause
Represents an table or selectable alias (AS).
Represents an alias, as typically applied to any table orsub-select within a SQL statement using the AS
keyword (orwithout the keyword on certain databases such as Oracle).
This object is constructed from the alias()
modulelevel function as well as the FromClause.alias()
method availableon all FromClause
subclasses.
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
CompoundSelect
(keyword, *selects, **kwargs) Bases:
sqlalchemy.sql.expression.GenerativeSelect
- Forms the basis of
UNION
,UNION ALL
, and other - SELECT-based set operations.
- Forms the basis of
See also
except()
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
CTE
(*arg, **kw) - Bases:
sqlalchemy.sql.expression.Generative
,sqlalchemy.sql.expression.HasSuffixes
,sqlalchemy.sql.expression.Alias
Represent a Common Table Expression.
The CTE
object is obtained using theSelectBase.cte()
method from any selectable.See that method for complete examples.
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
Mark a ClauseElement as supporting execution.
Executable
is a superclass for all “statement” typesof objects, including select()
, delete()
, update()
,insert()
, text()
.
- property
bind
- Returns the
Engine
orConnection
towhich thisExecutable
is bound, or None if none found.
This is a traversal which checks locally, thenchecks among the “from” clauses of associated objectsuntil a bound engine or connection is found.
execute
(*multiparams, **params)Compile and execute this
Executable
.- Set non-SQL options for the statement which take effect duringexecution.
Execution options can be set on a per-statement orper Connection
basis. Additionally, theEngine
and ORM Query
objects provideaccess to execution options which they in turn configure uponconnections.
The execution_options()
method is generative. A newinstance of this statement is returned that contains the options:
- statement = select([table.c.x, table.c.y])
- statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be appliedto a statement - these include “autocommit” and “stream_results”,but not “isolation_level” or “compiled_cache”.See Connection.execution_options()
for a full list ofpossible options.
See also
Connection.execution_options()
Executable.get_execution_options()
New in version 1.3.
See also
Executable.execution_options()
scalar
(*multiparams, **params)- Compile and execute this
Executable
, returning theresult’s scalar representation.
- class
sqlalchemy.sql.expression.
FromClause
- Bases:
sqlalchemy.sql.expression.Selectable
Represent an element that can be used within the FROM
clause of a SELECT
statement.
The most common forms of FromClause
are theTable
and the select()
constructs. Keyfeatures common to all FromClause
objects include:
a
c
collection, which provides per-name access to a collectionofColumnElement
objects.a
primary_key
attribute, which is a collection of all thoseColumnElement
objects that indicate theprimary_key
flag.Methods to generate various derivations of a “from” clause, including
FromClause.alias()
,FromClause.join()
,FromClause.select()
.- return an alias of this
FromClause
.
E.g.:
- a2 = some_table.alias('a2')
The above code creates an Alias
object which can be usedas a FROM clause in any SELECT statement.
See also
- property
c
An alias for the
columns
attribute.- A named-based collection of
ColumnElement
objectsmaintained by thisFromClause
.
The columns
, or c
collection, is the gatewayto the construction of SQL expressions using table-bound orother selectable-bound columns:
- select([mytable]).where(mytable.c.somecolumn == 5)
correspondon_equivalents
(_column, equivalents)Return corresponding_column for the given column, or if Nonesearch for a match in the given dictionary.
Given a
ColumnElement
, return the exportedColumnElement
object from thisSelectable
which corresponds to that originalColumn
via a common ancestorcolumn.- Parameters
column – the target
ColumnElement
to be matchedrequire_embedded – only return corresponding columns forthe given
ColumnElement
, if the givenColumnElement
is actually present within a sub-elementof thisFromClause
. Normally the column will match ifit merely shares a common ancestor with one of the exportedcolumns of thisFromClause
.
- return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the functions.count
function available from the func
namespace.
See also
Used primarily for error message formatting.
foreign_keys
Return the collection of ForeignKey objects which thisFromClause references.
- Return True if this FromClause is ‘derived’ from the givenFromClause.
An example would be an Alias of a Table is derived from that Table.
join
(right, onclause=None, isouter=False, full=False)- Return a
Join
from thisFromClause
to anotherFromClause
.
E.g.:
- from sqlalchemy import join
- j = user_table.join(address_table,
- user_table.c.id == address_table.c.user_id)
- stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
- SELECT user.id, user.name FROM user
- JOIN address ON user.id = address.user_id
- Parameters
-
-
right – the right side of the join; this is anyFromClause
object such as a Table
object, andmay also be a selectable-compatible object such as an ORM-mappedclass.
-
onclause – a SQL expression representing the ON clause of thejoin. If left at None
, FromClause.join()
will attempt tojoin the two tables based on a foreign key relationship.
-
isouter – if True, render a LEFT OUTER JOIN, instead of JOIN.
-
if True, render a FULL OUTER JOIN, instead of LEFT OUTERJOIN. Implies FromClause.join.isouter
.
New in version 1.1.
See also
join()
- standalone function
Join
- the type of object produced
lateral
(name=None)- Return a LATERAL alias of this
FromClause
.
The return value is the Lateral
construct alsoprovided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
outerjoin
(right, onclause=None, full=False)- Return a
Join
from thisFromClause
to anotherFromClause
, with the “isouter” flag set toTrue.
E.g.:
- from sqlalchemy import outerjoin
- j = user_table.outerjoin(address_table,
- user_table.c.id == address_table.c.user_id)
The above is equivalent to:
- j = user_table.join(
- address_table,
- user_table.c.id == address_table.c.user_id,
- isouter=True)
- Parameters
-
-
right – the right side of the join; this is anyFromClause
object such as a Table
object, andmay also be a selectable-compatible object such as an ORM-mappedclass.
-
onclause – a SQL expression representing the ON clause of thejoin. If left at None
, FromClause.join()
will attempt tojoin the two tables based on a foreign key relationship.
-
if True, render a FULL OUTER JOIN, instead ofLEFT OUTER JOIN.
New in version 1.1.
See also
primary_key
Return the collection of Column objects which comprise theprimary key of this FromClause.
replace all occurrences of FromClause ‘old’ with the given Aliasobject, returning a copy of this
FromClause
.- Define the ‘schema’ attribute for this
FromClause
.
This is typically None
for most objects except that ofTable
, where it is taken as the value of theTable.schema
argument.
select
(whereclause=None, **params)- return a SELECT of this
FromClause
.
See also
select()
- general purposemethod which allows for arbitrary column lists.
tablesample
(sampling, name=None, seed=None)- Return a TABLESAMPLE alias of this
FromClause
.
The return value is the TableSample
construct alsoprovided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
- class
sqlalchemy.sql.expression.
GenerativeSelect
(use_labels=False, for_update=False, limit=None, offset=None, order_by=None, group_by=None, bind=None, autocommit=None) - Bases:
sqlalchemy.sql.expression.SelectBase
Base class for SELECT statements where additional elements can beadded.
This serves as the base for Select
and CompoundSelect
where elements such as ORDER BY, GROUP BY can be added and columnrendering can be controlled. Compare to TextAsFrom
, which,while it subclasses SelectBase
and is also a SELECT construct,represents a fixed textual string which cannot be altered at this level,only wrapped as a subquery.
New in version 0.9.0: GenerativeSelect
was added toprovide functionality specific to Select
andCompoundSelect
while allowing SelectBase
to beused for other SELECT-like objects, e.g. TextAsFrom
.
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
New in version 1.1.
cte
(name=None, recursive=False)- Return a new
CTE
, or Common Table Expression instance.
Common table expressions are a SQL standard whereby SELECTstatements can draw upon secondary statements specified alongwith the primary statement, using a clause called “WITH”.Special semantics regarding UNION can also be employed toallow “recursive” queries, where a SELECT statement can drawupon the set of rows that have previously been selected.
CTEs can also be applied to DML constructs UPDATE, INSERTand DELETE on some databases, both as a source of CTE rowswhen combined with RETURNING, as well as a consumer ofCTE rows.
SQLAlchemy detects CTE
objects, which are treatedsimilarly to Alias
objects, as special elementsto be delivered to the FROM clause of the statement as wellas to a WITH clause at the top of the statement.
Changed in version 1.1: Added support for UPDATE/INSERT/DELETE asCTE, CTEs added to UPDATE/INSERT/DELETE.
- Parameters
-
-
name – name given to the common table expression. Like_FromClause.alias()
, the name can be left as None
in which case an anonymous symbol will be used at querycompile time.
-
recursive – if True
, will render WITH RECURSIVE
.A recursive common table expression is intended to be used inconjunction with UNION ALL in order to derive rowsfrom those already selected.
The following examples include two from PostgreSQL’s documentation athttp://www.postgresql.org/docs/current/static/queries-with.html,as well as additional examples.
Example 1, non recursive:
- from sqlalchemy import (Table, Column, String, Integer,
- MetaData, select, func)
- metadata = MetaData()
- orders = Table('orders', metadata,
- Column('region', String),
- Column('amount', Integer),
- Column('product', String),
- Column('quantity', Integer)
- )
- regional_sales = select([
- orders.c.region,
- func.sum(orders.c.amount).label('total_sales')
- ]).group_by(orders.c.region).cte("regional_sales")
- top_regions = select([regional_sales.c.region]).\
- where(
- regional_sales.c.total_sales >
- select([
- func.sum(regional_sales.c.total_sales)/10
- ])
- ).cte("top_regions")
- statement = select([
- orders.c.region,
- orders.c.product,
- func.sum(orders.c.quantity).label("product_units"),
- func.sum(orders.c.amount).label("product_sales")
- ]).where(orders.c.region.in_(
- select([top_regions.c.region])
- )).group_by(orders.c.region, orders.c.product)
- result = conn.execute(statement).fetchall()
Example 2, WITH RECURSIVE:
- from sqlalchemy import (Table, Column, String, Integer,
- MetaData, select, func)
- metadata = MetaData()
- parts = Table('parts', metadata,
- Column('part', String),
- Column('sub_part', String),
- Column('quantity', Integer),
- )
- included_parts = select([
- parts.c.sub_part,
- parts.c.part,
- parts.c.quantity]).\
- where(parts.c.part=='our part').\
- cte(recursive=True)
- incl_alias = included_parts.alias()
- parts_alias = parts.alias()
- included_parts = included_parts.union_all(
- select([
- parts_alias.c.sub_part,
- parts_alias.c.part,
- parts_alias.c.quantity
- ]).
- where(parts_alias.c.part==incl_alias.c.sub_part)
- )
- statement = select([
- included_parts.c.sub_part,
- func.sum(included_parts.c.quantity).
- label('total_quantity')
- ]).\
- group_by(included_parts.c.sub_part)
- result = conn.execute(statement).fetchall()
Example 3, an upsert using UPDATE and INSERT with CTEs:
- from datetime import date
- from sqlalchemy import (MetaData, Table, Column, Integer,
- Date, select, literal, and_, exists)
- metadata = MetaData()
- visitors = Table('visitors', metadata,
- Column('product_id', Integer, primary_key=True),
- Column('date', Date, primary_key=True),
- Column('count', Integer),
- )
- # add 5 visitors for the product_id == 1
- product_id = 1
- day = date.today()
- count = 5
- update_cte = (
- visitors.update()
- .where(and_(visitors.c.product_id == product_id,
- visitors.c.date == day))
- .values(count=visitors.c.count + count)
- .returning(literal(1))
- .cte('update_cte')
- )
- upsert = visitors.insert().from_select(
- [visitors.c.product_id, visitors.c.date, visitors.c.count],
- select([literal(product_id), literal(day), literal(count)])
- .where(~exists(update_cte.select()))
- )
- connection.execute(upsert)
See also
orm.query.Query.cte()
- ORM version ofHasCTE.cte()
.
This is used to support backend-specific prefix keywords such as thoseprovided by MySQL.
E.g.:
- stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
- # MySQL 5.7 optimizer hints
- stmt = select([table]).prefix_with(
- "/*+ BKA(t1) */", dialect="mysql")
Multiple prefixes can be specified by multiple callsto prefix_with()
.
- Parameters
-
-
textual or ClauseElement
construct whichwill be rendered following the INSERT, UPDATE, or DELETEkeyword.
Warning
The HasPrefixes.prefix_with.*expr
argument to HasPrefixes.prefix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
-
**kw – A single keyword ‘dialect’ is accepted. This is anoptional string dialect name which willlimit rendering of this prefix to only that dialect.
This is used to support backend-specific suffix keywords oncertain constructs.
E.g.:
- stmt = select([col1, col2]).cte().suffix_with(
- "cycle empno set y_cycle to 1 default 0", dialect="oracle")
Multiple suffixes can be specified by multiple callsto suffix_with()
.
- Parameters
-
-
textual or ClauseElement
construct whichwill be rendered following the target clause.
Warning
The HasSuffixes.suffix_with.*expr
argument to HasSuffixes.suffix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
-
**kw – A single keyword ‘dialect’ is accepted. This is anoptional string dialect name which willlimit rendering of this suffix to only that dialect.
- class
sqlalchemy.sql.expression.
Join
(left, right, onclause=None, isouter=False, full=False) - Bases:
sqlalchemy.sql.expression.FromClause
represent a JOIN
construct between two FromClause
elements.
The public constructor function for Join
is the module-leveljoin()
function, as well as the FromClause.join()
methodof any FromClause
(e.g. such as Table
).
See also
inherited from the eq()
method of object
Return self==value.
init
(left, right, onclause=None, isouter=False, full=False)- Construct a new
Join
.
The usual entrypoint here is the join()
function or the FromClause.join()
method of anyFromClause
object.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
Lateral
(*arg, **kw) - Bases:
sqlalchemy.sql.expression.Alias
Represent a LATERAL subquery.
This object is constructed from the lateral()
modulelevel function as well as the FromClause.lateral()
method availableon all FromClause
subclasses.
While LATERAL is part of the SQL standard, currently only more recentPostgreSQL versions provide support for this keyword.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
ScalarSelect
(element) Bases:
sqlalchemy.sql.expression.Generative
,sqlalchemy.sql.expression.Grouping
selfgroup
(**kwargs_)- Apply a ‘grouping’ to this
ClauseElement
.
This method is overridden by subclasses to return a“grouping” construct, i.e. parenthesis. In particularit’s used by “binary” expressions to provide a groupingaround themselves when placed into a larger expression,as well as by select()
constructs when placed intothe FROM clause of another select()
. (Note thatsubqueries should be normally created using theSelect.alias()
method, as many platforms requirenested SELECT statements to be named).
As expressions are composed together, the application ofself_group()
is automatic - end-user code should neverneed to use this method directly. Note that SQLAlchemy’sclause constructs take operator precedence into account -so parenthesis might not be needed, for example, inan expression like x OR (y AND z)
- AND takes precedenceover OR.
The base self_group()
method of ClauseElement
just returns self.
where
(crit)- Apply a WHERE clause to the SELECT statement referred toby this
ScalarSelect
.
- class
sqlalchemy.sql.expression.
Select
(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs) - Bases:
sqlalchemy.sql.expression.HasPrefixes
,sqlalchemy.sql.expression.HasSuffixes
,sqlalchemy.sql.expression.GenerativeSelect
Represents a SELECT
statement.
inherited from the eq()
method of object
Return self==value.
init
(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)- Construct a new
Select
object.
This constructor is mirrored as a public API function; see select()
for a full usage and argument description.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
Selectable
- Bases:
sqlalchemy.sql.expression.ClauseElement
mark a class as being selectable
- class
sqlalchemy.sql.expression.
SelectBase
- Bases:
sqlalchemy.sql.expression.HasCTE
,sqlalchemy.sql.expression.Executable
,sqlalchemy.sql.expression.FromClause
Base class for SELECT statements.
This includes Select
, CompoundSelect
andTextAsFrom
.
inherited from the eq()
method of object
Return self==value.
inherited from the init()
method of object
Initialize self. See help(type(self)) for accurate signature.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
TableClause
(name, *columns) - Bases:
sqlalchemy.sql.expression.Immutable
,sqlalchemy.sql.expression.FromClause
Represents a minimal “table” construct.
This is a lightweight table object that has only a name and acollection of columns, which are typically producedby the expression.column()
function:
- from sqlalchemy import table, column
- user = table("user",
- column("id"),
- column("name"),
- column("description"),
- )
The TableClause
construct serves as the base forthe more commonly used Table
object, providingthe usual set of FromClause
services includingthe .c.
collection and statement generation methods.
It does not provide all the additional schema-level servicesof Table
, including constraints, references to othertables, or support for MetaData
-level services. It’s usefulon its own as an ad-hoc construct used to generate quick SQLstatements when a more fully fledged Table
is not on hand.
inherited from the eq()
method of object
Return self==value.
init
(name, *columns)- Construct a new
TableClause
object.
This constructor is mirrored as a public API function; see table()
for a full usage and argument description.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
TableSample
(*arg, **kw) - Bases:
sqlalchemy.sql.expression.Alias
Represent a TABLESAMPLE clause.
This object is constructed from the tablesample()
modulelevel function as well as the FromClause.tablesample()
methodavailable on all FromClause
subclasses.
New in version 1.1.
See also
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.sql.expression.
TextAsFrom
(text, columns, positional=False) - Bases:
sqlalchemy.sql.expression.SelectBase
Wrap a TextClause
construct within a SelectBase
interface.
This allows the TextClause
object to gain a .c
collectionand other FROM-like capabilities such as FromClause.alias()
,SelectBase.cte()
, etc.
The TextAsFrom
construct is produced via theTextClause.columns()
method - see that method for details.
New in version 0.9.0.
See also
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self