Edit on GitHub

sqlglot expressions query.

   1"""sqlglot expressions query."""
   2
   3from __future__ import annotations
   4
   5import typing as t
   6
   7from sqlglot.errors import ParseError
   8from sqlglot.helper import trait, ensure_list
   9from sqlglot.expressions.core import (
  10    Aliases,
  11    Column,
  12    Condition,
  13    Distinct,
  14    Dot,
  15    DynamicIdentifier,
  16    Expr,
  17    Expression,
  18    Func,
  19    Hint,
  20    Identifier,
  21    In,
  22    Var,
  23    _apply_builder,
  24    _apply_child_list_builder,
  25    _apply_list_builder,
  26    _apply_conjunction_builder,
  27    _apply_set_operation,
  28    ExpOrStr,
  29    QUERY_MODIFIERS,
  30    maybe_parse,
  31    maybe_copy,
  32    to_identifier,
  33    convert,
  34    and_,
  35    alias_,
  36    column,
  37)
  38
  39if t.TYPE_CHECKING:
  40    from sqlglot.dialects.dialect import DialectType
  41    from sqlglot.expressions.datatypes import DataType
  42    from sqlglot.expressions.constraints import ColumnConstraint
  43    from sqlglot.expressions.ddl import Create
  44    from sqlglot.expressions.array import Unnest
  45    from sqlglot._typing import E, ParserArgs, ParserNoDialectArgs
  46    from typing_extensions import Unpack
  47
  48    S = t.TypeVar("S", bound="SetOperation")
  49    Q = t.TypeVar("Q", bound="Query")
  50
  51
  52def _apply_cte_builder(
  53    instance: E,
  54    alias: ExpOrStr,
  55    as_: ExpOrStr,
  56    recursive: bool | None = None,
  57    materialized: bool | None = None,
  58    append: bool = True,
  59    dialect: DialectType = None,
  60    copy: bool = True,
  61    scalar: bool | None = None,
  62    **opts: Unpack[ParserNoDialectArgs],
  63) -> E:
  64    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
  65    as_expression = maybe_parse(as_, dialect=dialect, copy=copy, **opts)
  66    if scalar and not isinstance(as_expression, Subquery):
  67        # scalar CTE must be wrapped in a subquery
  68        as_expression = Subquery(this=as_expression)
  69    cte = CTE(this=as_expression, alias=alias_expression, materialized=materialized, scalar=scalar)
  70    return _apply_child_list_builder(
  71        cte,
  72        instance=instance,
  73        arg="with_",
  74        append=append,
  75        copy=copy,
  76        into=With,
  77        properties={"recursive": recursive} if recursive else {},
  78    )
  79
  80
  81@trait
  82class Selectable(Expr):
  83    @property
  84    def selects(self) -> list[Expr]:
  85        raise NotImplementedError("Subclasses must implement selects")
  86
  87    @property
  88    def named_selects(self) -> list[str]:
  89        return _named_selects(self)
  90
  91
  92def _named_selects(self: Expr) -> list[str]:
  93    selectable = t.cast(Selectable, self)
  94    return [select.output_name for select in selectable.selects]
  95
  96
  97@trait
  98class DerivedTable(Selectable):
  99    @property
 100    def selects(self) -> list[Expr]:
 101        this = self.this
 102        return this.selects if isinstance(this, Query) else []
 103
 104
 105@trait
 106class UDTF(DerivedTable):
 107    @property
 108    def selects(self) -> list[Expr]:
 109        alias = self.args.get("alias")
 110        return alias.columns if alias else []
 111
 112
 113@trait
 114class Query(Selectable):
 115    """Trait for any SELECT/UNION/etc. query expression."""
 116
 117    @property
 118    def ctes(self) -> list[CTE]:
 119        with_ = self.args.get("with_")
 120        return with_.expressions if with_ else []
 121
 122    def select(
 123        self: Q,
 124        *expressions: ExpOrStr | None,
 125        append: bool = True,
 126        dialect: DialectType = None,
 127        copy: bool = True,
 128        **opts: Unpack[ParserNoDialectArgs],
 129    ) -> Q:
 130        raise NotImplementedError("Query objects must implement `select`")
 131
 132    def subquery(self, alias: ExpOrStr | None = None, copy: bool = True) -> Subquery:
 133        """
 134        Returns a `Subquery` that wraps around this query.
 135
 136        Example:
 137            >>> subquery = Select().select("x").from_("tbl").subquery()
 138            >>> Select().select("x").from_(subquery).sql()
 139            'SELECT x FROM (SELECT x FROM tbl)'
 140
 141        Args:
 142            alias: an optional alias for the subquery.
 143            copy: if `False`, modify this expression instance in-place.
 144        """
 145        instance = maybe_copy(self, copy)
 146        if not isinstance(alias, Expr):
 147            alias = TableAlias(this=to_identifier(alias)) if alias else None
 148
 149        return Subquery(this=instance, alias=alias)
 150
 151    def limit(
 152        self: Q,
 153        expression: ExpOrStr | int,
 154        dialect: DialectType = None,
 155        copy: bool = True,
 156        **opts: Unpack[ParserNoDialectArgs],
 157    ) -> Q:
 158        """
 159        Adds a LIMIT clause to this query.
 160
 161        Example:
 162            >>> Select().select("1").union(Select().select("1")).limit(1).sql()
 163            'SELECT 1 UNION SELECT 1 LIMIT 1'
 164
 165        Args:
 166            expression: the SQL code string to parse.
 167                This can also be an integer.
 168                If a `Limit` instance is passed, it will be used as-is.
 169                If another `Expr` instance is passed, it will be wrapped in a `Limit`.
 170            dialect: the dialect used to parse the input expression.
 171            copy: if `False`, modify this expression instance in-place.
 172            opts: other options to use to parse the input expressions.
 173
 174        Returns:
 175            A limited Select expression.
 176        """
 177        return _apply_builder(
 178            expression=expression,
 179            instance=self,
 180            arg="limit",
 181            into=Limit,
 182            prefix="LIMIT",
 183            dialect=dialect,
 184            copy=copy,
 185            into_arg="expression",
 186            **opts,
 187        )
 188
 189    def offset(
 190        self: Q,
 191        expression: ExpOrStr | int,
 192        dialect: DialectType = None,
 193        copy: bool = True,
 194        **opts: Unpack[ParserNoDialectArgs],
 195    ) -> Q:
 196        """
 197        Set the OFFSET expression.
 198
 199        Example:
 200            >>> Select().from_("tbl").select("x").offset(10).sql()
 201            'SELECT x FROM tbl OFFSET 10'
 202
 203        Args:
 204            expression: the SQL code string to parse.
 205                This can also be an integer.
 206                If a `Offset` instance is passed, this is used as-is.
 207                If another `Expr` instance is passed, it will be wrapped in a `Offset`.
 208            dialect: the dialect used to parse the input expression.
 209            copy: if `False`, modify this expression instance in-place.
 210            opts: other options to use to parse the input expressions.
 211
 212        Returns:
 213            The modified Select expression.
 214        """
 215        return _apply_builder(
 216            expression=expression,
 217            instance=self,
 218            arg="offset",
 219            into=Offset,
 220            prefix="OFFSET",
 221            dialect=dialect,
 222            copy=copy,
 223            into_arg="expression",
 224            **opts,
 225        )
 226
 227    def order_by(
 228        self: Q,
 229        *expressions: ExpOrStr | None,
 230        append: bool = True,
 231        dialect: DialectType = None,
 232        copy: bool = True,
 233        **opts: Unpack[ParserNoDialectArgs],
 234    ) -> Q:
 235        """
 236        Set the ORDER BY expression.
 237
 238        Example:
 239            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
 240            'SELECT x FROM tbl ORDER BY x DESC'
 241
 242        Args:
 243            *expressions: the SQL code strings to parse.
 244                If a `Group` instance is passed, this is used as-is.
 245                If another `Expr` instance is passed, it will be wrapped in a `Order`.
 246            append: if `True`, add to any existing expressions.
 247                Otherwise, this flattens all the `Order` expression into a single expression.
 248            dialect: the dialect used to parse the input expression.
 249            copy: if `False`, modify this expression instance in-place.
 250            opts: other options to use to parse the input expressions.
 251
 252        Returns:
 253            The modified Select expression.
 254        """
 255        return _apply_child_list_builder(
 256            *expressions,
 257            instance=self,
 258            arg="order",
 259            append=append,
 260            copy=copy,
 261            prefix="ORDER BY",
 262            into=Order,
 263            dialect=dialect,
 264            **opts,
 265        )
 266
 267    def where(
 268        self: Q,
 269        *expressions: ExpOrStr | None,
 270        append: bool = True,
 271        dialect: DialectType = None,
 272        copy: bool = True,
 273        **opts: Unpack[ParserNoDialectArgs],
 274    ) -> Q:
 275        """
 276        Append to or set the WHERE expressions.
 277
 278        Examples:
 279            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
 280            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
 281
 282        Args:
 283            *expressions: the SQL code strings to parse.
 284                If an `Expr` instance is passed, it will be used as-is.
 285                Multiple expressions are combined with an AND operator.
 286            append: if `True`, AND the new expressions to any existing expression.
 287                Otherwise, this resets the expression.
 288            dialect: the dialect used to parse the input expressions.
 289            copy: if `False`, modify this expression instance in-place.
 290            opts: other options to use to parse the input expressions.
 291
 292        Returns:
 293            The modified expression.
 294        """
 295        return _apply_conjunction_builder(
 296            *[expr.this if isinstance(expr, Where) else expr for expr in expressions],
 297            instance=self,
 298            arg="where",
 299            append=append,
 300            into=Where,
 301            dialect=dialect,
 302            copy=copy,
 303            **opts,
 304        )
 305
 306    def with_(
 307        self: Q,
 308        alias: ExpOrStr,
 309        as_: ExpOrStr,
 310        recursive: bool | None = None,
 311        materialized: bool | None = None,
 312        append: bool = True,
 313        dialect: DialectType = None,
 314        copy: bool = True,
 315        scalar: bool | None = None,
 316        **opts: Unpack[ParserNoDialectArgs],
 317    ) -> Q:
 318        """
 319        Append to or set the common table expressions.
 320
 321        Example:
 322            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
 323            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
 324
 325        Args:
 326            alias: the SQL code string to parse as the table name.
 327                If an `Expr` instance is passed, this is used as-is.
 328            as_: the SQL code string to parse as the table expression.
 329                If an `Expr` instance is passed, it will be used as-is.
 330            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
 331            materialized: set the MATERIALIZED part of the expression.
 332            append: if `True`, add to any existing expressions.
 333                Otherwise, this resets the expressions.
 334            dialect: the dialect used to parse the input expression.
 335            copy: if `False`, modify this expression instance in-place.
 336            scalar: if `True`, this is a scalar common table expression.
 337            opts: other options to use to parse the input expressions.
 338
 339        Returns:
 340            The modified expression.
 341        """
 342        return _apply_cte_builder(
 343            self,
 344            alias,
 345            as_,
 346            recursive=recursive,
 347            materialized=materialized,
 348            append=append,
 349            dialect=dialect,
 350            copy=copy,
 351            scalar=scalar,
 352            **opts,
 353        )
 354
 355    def union(
 356        self,
 357        *expressions: ExpOrStr,
 358        distinct: bool = True,
 359        dialect: DialectType = None,
 360        copy: bool = True,
 361        **opts: Unpack[ParserNoDialectArgs],
 362    ) -> Union:
 363        """
 364        Builds a UNION expression.
 365
 366        Example:
 367            >>> import sqlglot
 368            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 369            'SELECT * FROM foo UNION SELECT * FROM bla'
 370
 371        Args:
 372            expressions: the SQL code strings.
 373                If `Expr` instances are passed, they will be used as-is.
 374            distinct: set the DISTINCT flag if and only if this is true.
 375            dialect: the dialect used to parse the input expression.
 376            opts: other options to use to parse the input expressions.
 377
 378        Returns:
 379            The new Union expression.
 380        """
 381        return union(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
 382
 383    def intersect(
 384        self,
 385        *expressions: ExpOrStr,
 386        distinct: bool = True,
 387        dialect: DialectType = None,
 388        copy: bool = True,
 389        **opts: Unpack[ParserNoDialectArgs],
 390    ) -> Intersect:
 391        """
 392        Builds an INTERSECT expression.
 393
 394        Example:
 395            >>> import sqlglot
 396            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 397            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 398
 399        Args:
 400            expressions: the SQL code strings.
 401                If `Expr` instances are passed, they will be used as-is.
 402            distinct: set the DISTINCT flag if and only if this is true.
 403            dialect: the dialect used to parse the input expression.
 404            opts: other options to use to parse the input expressions.
 405
 406        Returns:
 407            The new Intersect expression.
 408        """
 409        return intersect(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
 410
 411    def except_(
 412        self,
 413        *expressions: ExpOrStr,
 414        distinct: bool = True,
 415        dialect: DialectType = None,
 416        copy: bool = True,
 417        **opts: Unpack[ParserNoDialectArgs],
 418    ) -> Except:
 419        """
 420        Builds an EXCEPT expression.
 421
 422        Example:
 423            >>> import sqlglot
 424            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 425            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 426
 427        Args:
 428            expressions: the SQL code strings.
 429                If `Expr` instance are passed, they will be used as-is.
 430            distinct: set the DISTINCT flag if and only if this is true.
 431            dialect: the dialect used to parse the input expression.
 432            opts: other options to use to parse the input expressions.
 433
 434        Returns:
 435            The new Except expression.
 436        """
 437        return except_(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
 438
 439
 440class QueryBand(Expression):
 441    arg_types = {"this": True, "scope": False, "update": False}
 442
 443
 444class RecursiveWithSearch(Expression):
 445    arg_types = {
 446        "kind": True,
 447        "this": True,
 448        "expression": True,
 449        "to": False,
 450        "default": False,
 451        "using": False,
 452    }
 453
 454
 455class With(Expression):
 456    arg_types = {
 457        "expressions": False,
 458        "recursive": False,
 459        "search": False,
 460        "cycle": False,
 461        "udfs": False,
 462    }
 463
 464    @property
 465    def recursive(self) -> bool:
 466        return bool(self.args.get("recursive"))
 467
 468
 469class CTE(Expression, DerivedTable):
 470    arg_types = {
 471        "this": True,
 472        "alias": True,
 473        "scalar": False,
 474        "materialized": False,
 475        "key_expressions": False,
 476    }
 477
 478
 479class ProjectionDef(Expression):
 480    arg_types = {"this": True, "expression": True}
 481
 482
 483class TableAlias(Expression):
 484    arg_types = {"this": False, "columns": False}
 485
 486    @property
 487    def columns(self) -> list[t.Any]:
 488        return self.args.get("columns") or []
 489
 490
 491class BitString(Expression, Condition):
 492    is_primitive = True
 493
 494
 495class HexString(Expression, Condition):
 496    """Encoded hexadecimal data, binary by default or integer/character when flagged."""
 497
 498    arg_types = {"this": True, "is_integer": False, "is_character": False}
 499    is_primitive = True
 500
 501
 502class ByteString(Expression, Condition):
 503    arg_types = {"this": True, "is_bytes": False}
 504    is_primitive = True
 505    _hash_raw_args = True
 506
 507
 508class RawString(Expression, Condition):
 509    is_primitive = True
 510    _hash_raw_args = True
 511
 512
 513class UnicodeString(Expression, Condition):
 514    arg_types = {"this": True, "escape": False}
 515    _hash_raw_args = True
 516
 517
 518class ColumnPosition(Expression):
 519    arg_types = {"this": False, "position": True}
 520
 521
 522class ColumnDef(Expression):
 523    arg_types = {
 524        "this": True,
 525        "kind": False,
 526        "constraints": False,
 527        "exists": False,
 528        "position": False,
 529        "default": False,
 530        "output": False,
 531    }
 532
 533    @property
 534    def constraints(self) -> list[ColumnConstraint]:
 535        return self.args.get("constraints") or []
 536
 537    @property
 538    def kind(self) -> DataType | None:
 539        return self.args.get("kind")
 540
 541
 542class Changes(Expression):
 543    arg_types = {"information": True, "at_before": False, "end": False}
 544
 545
 546class Connect(Expression):
 547    arg_types = {"start": False, "connect": True, "nocycle": False}
 548
 549
 550class Prior(Expression):
 551    pass
 552
 553
 554class Into(Expression):
 555    arg_types = {
 556        "this": False,
 557        "temporary": False,
 558        "unlogged": False,
 559        "bulk_collect": False,
 560        "expressions": False,
 561    }
 562
 563
 564class From(Expression):
 565    @property
 566    def name(self) -> str:
 567        return self.this.name
 568
 569    @property
 570    def alias_or_name(self) -> str:
 571        return self.this.alias_or_name
 572
 573
 574class Having(Expression):
 575    pass
 576
 577
 578class Index(Expression):
 579    arg_types = {
 580        "this": False,
 581        "table": False,
 582        "unique": False,
 583        "primary": False,
 584        "amp": False,  # teradata
 585        "params": False,
 586    }
 587
 588
 589class ConditionalInsert(Expression):
 590    arg_types = {"this": True, "expression": False, "else_": False}
 591
 592
 593class MultitableInserts(Expression):
 594    arg_types = {"with_": False, "expressions": True, "kind": False, "source": True}
 595
 596
 597class OnCondition(Expression):
 598    arg_types = {"error": False, "empty": False, "null": False}
 599
 600
 601class Introducer(Expression):
 602    arg_types = {"this": True, "expression": True}
 603
 604
 605class National(Expression):
 606    is_primitive = True
 607    _hash_raw_args = True
 608
 609
 610class Partition(Expression):
 611    arg_types = {"expressions": True, "subpartition": False}
 612
 613
 614class PartitionRange(Expression):
 615    arg_types = {"this": True, "expression": False, "expressions": False}
 616
 617
 618class PartitionId(Expression):
 619    pass
 620
 621
 622class Fetch(Expression):
 623    arg_types = {
 624        "direction": False,
 625        "count": False,
 626        "limit_options": False,
 627    }
 628
 629
 630class Grant(Expression):
 631    arg_types = {
 632        "privileges": True,
 633        "kind": False,
 634        "securable": True,
 635        "principals": True,
 636        "grant_option": False,
 637    }
 638
 639
 640class Revoke(Expression):
 641    arg_types = {**Grant.arg_types, "cascade": False}
 642
 643
 644class Group(Expression):
 645    arg_types = {
 646        "expressions": False,
 647        "grouping_sets": False,
 648        "cube": False,
 649        "rollup": False,
 650        "totals": False,
 651        "all": False,
 652    }
 653
 654
 655class Cube(Expression):
 656    arg_types = {"expressions": False}
 657
 658
 659class Rollup(Expression):
 660    arg_types = {"expressions": False}
 661
 662
 663class GroupingSets(Expression):
 664    arg_types = {"expressions": True}
 665
 666
 667class Lambda(Expression):
 668    arg_types = {"this": True, "expressions": True}
 669
 670
 671class Limit(Expression):
 672    arg_types = {
 673        "this": False,
 674        "expression": True,
 675        "offset": False,
 676        "limit_options": False,
 677        "expressions": False,
 678    }
 679
 680    @property
 681    def is_limit_all(self) -> bool:
 682        limit_expression = self.args.get("expression")
 683        return isinstance(limit_expression, Var) and limit_expression.name.upper() == "ALL"
 684
 685
 686class LimitOptions(Expression):
 687    arg_types = {
 688        "percent": False,
 689        "rows": False,
 690        "with_ties": False,
 691    }
 692
 693
 694class Join(Expression):
 695    arg_types = {
 696        "this": True,
 697        "on": False,
 698        "side": False,
 699        "kind": False,
 700        "using": False,
 701        "method": False,
 702        "global_": False,
 703        "hint": False,
 704        "match_condition": False,
 705        "nearest": False,
 706        "directed": False,
 707        "expressions": False,
 708        "pivots": False,
 709    }
 710
 711    QUALIFIERS: t.ClassVar[tuple[str, ...]] = ("on", "using", "side", "kind", "method", "nearest")
 712
 713    @property
 714    def method(self) -> str:
 715        return self.text("method").upper()
 716
 717    @property
 718    def kind(self) -> str:
 719        return self.text("kind").upper()
 720
 721    @property
 722    def side(self) -> str:
 723        return self.text("side").upper()
 724
 725    @property
 726    def hint(self) -> str:
 727        return self.text("hint").upper()
 728
 729    @property
 730    def alias_or_name(self) -> str:
 731        return self.this.alias_or_name
 732
 733    @property
 734    def is_semi_or_anti_join(self) -> bool:
 735        return self.kind in ("SEMI", "ANTI")
 736
 737    def on(
 738        self,
 739        *expressions: ExpOrStr | None,
 740        append: bool = True,
 741        dialect: DialectType = None,
 742        copy: bool = True,
 743        **opts: Unpack[ParserNoDialectArgs],
 744    ) -> Join:
 745        """
 746        Append to or set the ON expressions.
 747
 748        Example:
 749            >>> import sqlglot
 750            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
 751            'JOIN x ON y = 1'
 752
 753        Args:
 754            *expressions: the SQL code strings to parse.
 755                If an `Expr` instance is passed, it will be used as-is.
 756                Multiple expressions are combined with an AND operator.
 757            append: if `True`, AND the new expressions to any existing expression.
 758                Otherwise, this resets the expression.
 759            dialect: the dialect used to parse the input expressions.
 760            copy: if `False`, modify this expression instance in-place.
 761            opts: other options to use to parse the input expressions.
 762
 763        Returns:
 764            The modified Join expression.
 765        """
 766        join = _apply_conjunction_builder(
 767            *expressions,
 768            instance=self,
 769            arg="on",
 770            append=append,
 771            dialect=dialect,
 772            copy=copy,
 773            **opts,
 774        )
 775
 776        if join.kind == "CROSS":
 777            join.set("kind", None)
 778
 779        return join
 780
 781    def using(
 782        self,
 783        *expressions: ExpOrStr | None,
 784        append: bool = True,
 785        dialect: DialectType = None,
 786        copy: bool = True,
 787        **opts: Unpack[ParserNoDialectArgs],
 788    ) -> Join:
 789        """
 790        Append to or set the USING expressions.
 791
 792        Example:
 793            >>> import sqlglot
 794            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
 795            'JOIN x USING (foo, bla)'
 796
 797        Args:
 798            *expressions: the SQL code strings to parse.
 799                If an `Expr` instance is passed, it will be used as-is.
 800            append: if `True`, concatenate the new expressions to the existing "using" list.
 801                Otherwise, this resets the expression.
 802            dialect: the dialect used to parse the input expressions.
 803            copy: if `False`, modify this expression instance in-place.
 804            opts: other options to use to parse the input expressions.
 805
 806        Returns:
 807            The modified Join expression.
 808        """
 809        join = _apply_list_builder(
 810            *expressions,
 811            instance=self,
 812            arg="using",
 813            append=append,
 814            dialect=dialect,
 815            copy=copy,
 816            **opts,
 817        )
 818
 819        if join.kind == "CROSS":
 820            join.set("kind", None)
 821
 822        return join
 823
 824
 825class Nearest(Expression):
 826    arg_types = {"this": True, "count": True, "approximate": False, "similarity": False}
 827
 828
 829class Lateral(Expression, UDTF):
 830    arg_types = {
 831        "this": True,
 832        "view": False,
 833        "outer": False,
 834        "alias": False,
 835        "cross_apply": False,  # True -> CROSS APPLY, False -> OUTER APPLY
 836        "ordinality": False,
 837    }
 838
 839    @property
 840    def selects(self) -> list[Expr]:
 841        from sqlglot.expressions.array import Unnest
 842
 843        columns = super().selects
 844
 845        # UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset
 846        offset = self.this.args.get("offset") if isinstance(self.this, Unnest) else None
 847        if isinstance(offset, Identifier):
 848            columns = columns + [offset]
 849
 850        return columns
 851
 852
 853class TableArgument(Expression):
 854    """A relation passed to a table function with the TABLE keyword."""
 855
 856
 857class TableFromRows(Expression, UDTF):
 858    arg_types = {
 859        "this": True,
 860        "alias": False,
 861        "joins": False,
 862        "pivots": False,
 863        "sample": False,
 864    }
 865
 866
 867class MatchRecognizeMeasure(Expression):
 868    arg_types = {
 869        "this": True,
 870        "window_frame": False,
 871    }
 872
 873
 874class MatchRecognize(Expression):
 875    arg_types = {
 876        "this": True,
 877        "partition_by": False,
 878        "order": False,
 879        "measures": False,
 880        "rows": False,
 881        "after": False,
 882        "pattern": False,
 883        "subset": False,
 884        "define": False,
 885        "alias": False,
 886        "sample": False,
 887        "joins": False,
 888    }
 889
 890
 891class Final(Expression):
 892    pass
 893
 894
 895class Offset(Expression):
 896    arg_types = {"this": False, "expression": True, "expressions": False}
 897
 898
 899class Order(Expression):
 900    arg_types = {"this": False, "expressions": True, "siblings": False}
 901
 902
 903class WithFill(Expression):
 904    arg_types = {
 905        "from_": False,
 906        "to": False,
 907        "step": False,
 908        "interpolate": False,
 909    }
 910
 911
 912class SkipJSONColumn(Expression):
 913    arg_types = {"regexp": False, "expression": True}
 914
 915
 916class Cluster(Expression):
 917    arg_types = {"expressions": True}
 918
 919
 920class Distribute(Order):
 921    pass
 922
 923
 924class Sort(Order):
 925    pass
 926
 927
 928class Qualify(Expression):
 929    pass
 930
 931
 932class InputOutputFormat(Expression):
 933    arg_types = {"input_format": False, "output_format": False}
 934
 935
 936class Return(Expression):
 937    pass
 938
 939
 940class Tuple(Expression):
 941    arg_types = {"expressions": False}
 942
 943    def isin(
 944        self,
 945        *expressions: t.Any,
 946        query: ExpOrStr | None = None,
 947        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
 948        copy: bool = True,
 949        **opts: Unpack[ParserArgs],
 950    ) -> In:
 951        return In(
 952            this=maybe_copy(self, copy),
 953            expressions=[convert(e, copy=copy) for e in expressions],
 954            query=maybe_parse(query, copy=copy, **opts) if query else None,
 955            unnest=(
 956                Unnest(
 957                    expressions=[
 958                        maybe_parse(e, copy=copy, **opts)
 959                        for e in t.cast(list[ExpOrStr], ensure_list(unnest))
 960                    ]
 961                )
 962                if unnest
 963                else None
 964            ),
 965        )
 966
 967
 968class QueryOption(Expression):
 969    arg_types = {"this": True, "expression": False}
 970
 971
 972# FOR { XML | JSON } query modifier; `kind` is the discriminant ("XML" or "JSON").
 973class ForClause(Expression):
 974    arg_types = {"kind": True, "expressions": False}
 975
 976
 977class WithTableHint(Expression):
 978    arg_types = {"expressions": True}
 979
 980
 981class IndexTableHint(Expression):
 982    arg_types = {"this": True, "expressions": False, "target": False}
 983
 984
 985class HistoricalData(Expression):
 986    arg_types = {"this": True, "kind": True, "expression": True}
 987
 988
 989class Put(Expression):
 990    arg_types = {"this": True, "target": True, "properties": False}
 991
 992
 993class Get(Expression):
 994    arg_types = {"this": True, "target": True, "properties": False}
 995
 996
 997class ListStage(Expression):
 998    """Lists files in a Snowflake stage or Git repository clone."""
 999
1000    arg_types = {"this": True, "pattern": False}
1001
1002
1003class Table(Expression, Selectable):
1004    arg_types = {
1005        "this": False,
1006        "alias": False,
1007        "db": False,
1008        "catalog": False,
1009        "laterals": False,
1010        "joins": False,
1011        "pivots": False,
1012        "hints": False,
1013        "system_time": False,
1014        "version": False,
1015        "format": False,
1016        "pattern": False,
1017        "ordinality": False,
1018        "when": False,
1019        "only": False,
1020        "partition": False,
1021        "changes": False,
1022        "rows_from": False,
1023        "sample": False,
1024        "indexed": False,
1025    }
1026
1027    @property
1028    def name(self) -> str:
1029        this = self.this
1030        if not this or (isinstance(this, Func) and not isinstance(this, DynamicIdentifier)):
1031            return ""
1032        return this.name
1033
1034    @property
1035    def db(self) -> str:
1036        return self.text("db")
1037
1038    @property
1039    def catalog(self) -> str:
1040        return self.text("catalog")
1041
1042    @property
1043    def selects(self) -> list[Expr]:
1044        return []
1045
1046    @property
1047    def named_selects(self) -> list[str]:
1048        return []
1049
1050    @property
1051    def parts(self) -> list[Expr]:
1052        """Return the parts of a table in order catalog, db, table."""
1053        parts: list[Expr] = []
1054
1055        for arg in ("catalog", "db", "this"):
1056            part = self.args.get(arg)
1057
1058            if isinstance(part, Dot):
1059                parts.extend(part.flatten())
1060            elif isinstance(part, Expr):
1061                parts.append(part)
1062
1063        return parts
1064
1065    def to_column(self, copy: bool = True) -> Expr:
1066        parts = self.parts
1067        last_part = parts[-1]
1068
1069        if isinstance(last_part, Identifier):
1070            col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy)  # type: ignore
1071        else:
1072            # This branch will be reached if a function or array is wrapped in a `Table`
1073            col = last_part
1074
1075        alias = self.args.get("alias")
1076        if alias:
1077            col = alias_(col, alias.this, copy=copy)
1078
1079        return col
1080
1081
1082def _is_star(expression: Expr) -> bool:
1083    stack = [expression]
1084    while stack:
1085        node = stack.pop()
1086        if isinstance(node, SetOperation):
1087            stack.append(node.this)
1088            stack.append(node.expression)
1089        elif isinstance(node, Subquery):
1090            stack.append(node.this)
1091        elif node.is_star:
1092            return True
1093    return False
1094
1095
1096class SetOperation(Expression, Query):
1097    arg_types = {
1098        "with_": False,
1099        "this": True,
1100        "expression": True,
1101        "distinct": False,
1102        "by_name": False,
1103        "side": False,
1104        "kind": False,
1105        "on": False,
1106        **QUERY_MODIFIERS,
1107    }
1108
1109    def select(
1110        self: S,
1111        *expressions: ExpOrStr | None,
1112        append: bool = True,
1113        dialect: DialectType = None,
1114        copy: bool = True,
1115        **opts: Unpack[ParserNoDialectArgs],
1116    ) -> S:
1117        this = maybe_copy(self, copy)
1118        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1119        this.expression.unnest().select(
1120            *expressions, append=append, dialect=dialect, copy=False, **opts
1121        )
1122        return this
1123
1124    @property
1125    def named_selects(self) -> list[str]:
1126        names = []
1127        stack: list[Expr] = [self]
1128        by_name = False
1129
1130        while stack:
1131            expr = stack.pop()
1132            if not isinstance(expr, SetOperation):
1133                names.extend(t.cast(Selectable, expr).named_selects)
1134                continue
1135
1136            while isinstance(expr, SetOperation):
1137                if expr.args.get("by_name"):
1138                    by_name = True
1139                    stack.append(expr.expression.unnest())
1140                    stack.append(expr.this.unnest())
1141                    break
1142                expr = expr.this.unnest()
1143            else:
1144                names.extend(_named_selects(expr))
1145
1146        return list(dict.fromkeys(names)) if by_name else names
1147
1148    @property
1149    def is_star(self) -> bool:
1150        return _is_star(self)
1151
1152    @property
1153    def selects(self) -> list[Expr]:
1154        expr: Expr = self
1155        while isinstance(expr, SetOperation):
1156            expr = expr.this.unnest()
1157        return getattr(expr, "selects", [])
1158
1159    @property
1160    def left(self) -> Query:
1161        return self.this
1162
1163    @property
1164    def right(self) -> Query:
1165        return self.expression
1166
1167    @property
1168    def kind(self) -> str:
1169        return self.text("kind").upper()
1170
1171    @property
1172    def side(self) -> str:
1173        return self.text("side").upper()
1174
1175
1176class Union(SetOperation):
1177    pass
1178
1179
1180class Except(SetOperation):
1181    pass
1182
1183
1184class Intersect(SetOperation):
1185    pass
1186
1187
1188class Values(Expression, UDTF):
1189    arg_types = {
1190        "expressions": True,
1191        "alias": False,
1192        "order": False,
1193        "limit": False,
1194        "offset": False,
1195        "pivots": False,
1196    }
1197
1198
1199class Version(Expression):
1200    """
1201    Time travel, iceberg, bigquery etc
1202    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
1203    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
1204    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
1205    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
1206    this is either TIMESTAMP or VERSION
1207    kind is ("AS OF", "BETWEEN")
1208    """
1209
1210    arg_types = {"this": True, "kind": True, "expression": False}
1211
1212
1213class Schema(Expression):
1214    arg_types = {"this": False, "expressions": False}
1215
1216
1217class Lock(Expression):
1218    arg_types = {"update": True, "expressions": False, "wait": False, "key": False}
1219
1220
1221class Select(Expression, Query):
1222    arg_types = {
1223        "with_": False,
1224        "kind": False,
1225        "expressions": False,
1226        "hint": False,
1227        "distinct": False,
1228        "into": False,
1229        "from_": False,
1230        "operation_modifiers": False,
1231        "exclude": False,
1232        **QUERY_MODIFIERS,
1233    }
1234
1235    def from_(
1236        self,
1237        expression: ExpOrStr,
1238        dialect: DialectType = None,
1239        copy: bool = True,
1240        **opts: Unpack[ParserNoDialectArgs],
1241    ) -> Select:
1242        """
1243        Set the FROM expression.
1244
1245        Example:
1246            >>> Select().from_("tbl").select("x").sql()
1247            'SELECT x FROM tbl'
1248
1249        Args:
1250            expression : the SQL code strings to parse.
1251                If a `From` instance is passed, this is used as-is.
1252                If another `Expr` instance is passed, it will be wrapped in a `From`.
1253            dialect: the dialect used to parse the input expression.
1254            copy: if `False`, modify this expression instance in-place.
1255            opts: other options to use to parse the input expressions.
1256
1257        Returns:
1258            The modified Select expression.
1259        """
1260        return _apply_builder(
1261            expression=expression,
1262            instance=self,
1263            arg="from_",
1264            into=From,
1265            prefix="FROM",
1266            dialect=dialect,
1267            copy=copy,
1268            **opts,
1269        )
1270
1271    def group_by(
1272        self,
1273        *expressions: ExpOrStr | None,
1274        append: bool = True,
1275        dialect: DialectType = None,
1276        copy: bool = True,
1277        **opts: Unpack[ParserNoDialectArgs],
1278    ) -> Select:
1279        """
1280        Set the GROUP BY expression.
1281
1282        Example:
1283            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
1284            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
1285
1286        Args:
1287            *expressions: the SQL code strings to parse.
1288                If a `Group` instance is passed, this is used as-is.
1289                If another `Expr` instance is passed, it will be wrapped in a `Group`.
1290                If nothing is passed in then a group by is not applied to the expression
1291            append: if `True`, add to any existing expressions.
1292                Otherwise, this flattens all the `Group` expression into a single expression.
1293            dialect: the dialect used to parse the input expression.
1294            copy: if `False`, modify this expression instance in-place.
1295            opts: other options to use to parse the input expressions.
1296
1297        Returns:
1298            The modified Select expression.
1299        """
1300        if not expressions:
1301            return self if not copy else self.copy()
1302
1303        return _apply_child_list_builder(
1304            *expressions,
1305            instance=self,
1306            arg="group",
1307            append=append,
1308            copy=copy,
1309            prefix="GROUP BY",
1310            into=Group,
1311            dialect=dialect,
1312            **opts,
1313        )
1314
1315    def sort_by(
1316        self,
1317        *expressions: ExpOrStr | None,
1318        append: bool = True,
1319        dialect: DialectType = None,
1320        copy: bool = True,
1321        **opts: Unpack[ParserNoDialectArgs],
1322    ) -> Select:
1323        """
1324        Set the SORT BY expression.
1325
1326        Example:
1327            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
1328            'SELECT x FROM tbl SORT BY x DESC'
1329
1330        Args:
1331            *expressions: the SQL code strings to parse.
1332                If a `Group` instance is passed, this is used as-is.
1333                If another `Expr` instance is passed, it will be wrapped in a `SORT`.
1334            append: if `True`, add to any existing expressions.
1335                Otherwise, this flattens all the `Order` expression into a single expression.
1336            dialect: the dialect used to parse the input expression.
1337            copy: if `False`, modify this expression instance in-place.
1338            opts: other options to use to parse the input expressions.
1339
1340        Returns:
1341            The modified Select expression.
1342        """
1343        return _apply_child_list_builder(
1344            *expressions,
1345            instance=self,
1346            arg="sort",
1347            append=append,
1348            copy=copy,
1349            prefix="SORT BY",
1350            into=Sort,
1351            dialect=dialect,
1352            **opts,
1353        )
1354
1355    def cluster_by(
1356        self,
1357        *expressions: ExpOrStr | None,
1358        append: bool = True,
1359        dialect: DialectType = None,
1360        copy: bool = True,
1361        **opts: Unpack[ParserNoDialectArgs],
1362    ) -> Select:
1363        """
1364        Set the CLUSTER BY expression.
1365
1366        Example:
1367            >>> Select().from_("tbl").select("x").cluster_by("x").sql(dialect="hive")
1368            'SELECT x FROM tbl CLUSTER BY x'
1369
1370        Args:
1371            *expressions: the SQL code strings to parse.
1372                If a `Group` instance is passed, this is used as-is.
1373                If another `Expr` instance is passed, it will be wrapped in a `Cluster`.
1374            append: if `True`, add to any existing expressions.
1375                Otherwise, this flattens all the `Order` expression into a single expression.
1376            dialect: the dialect used to parse the input expression.
1377            copy: if `False`, modify this expression instance in-place.
1378            opts: other options to use to parse the input expressions.
1379
1380        Returns:
1381            The modified Select expression.
1382        """
1383        return _apply_child_list_builder(
1384            *expressions,
1385            instance=self,
1386            arg="cluster",
1387            append=append,
1388            copy=copy,
1389            prefix="CLUSTER BY",
1390            into=Cluster,
1391            dialect=dialect,
1392            **opts,
1393        )
1394
1395    def select(
1396        self,
1397        *expressions: ExpOrStr | None,
1398        append: bool = True,
1399        dialect: DialectType = None,
1400        copy: bool = True,
1401        **opts: Unpack[ParserNoDialectArgs],
1402    ) -> Select:
1403        return _apply_list_builder(
1404            *expressions,
1405            instance=self,
1406            arg="expressions",
1407            append=append,
1408            dialect=dialect,
1409            into=Expr,
1410            copy=copy,
1411            **opts,
1412        )
1413
1414    def lateral(
1415        self,
1416        *expressions: ExpOrStr | None,
1417        append: bool = True,
1418        dialect: DialectType = None,
1419        copy: bool = True,
1420        **opts: Unpack[ParserNoDialectArgs],
1421    ) -> Select:
1422        """
1423        Append to or set the LATERAL expressions.
1424
1425        Example:
1426            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
1427            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
1428
1429        Args:
1430            *expressions: the SQL code strings to parse.
1431                If an `Expr` instance is passed, it will be used as-is.
1432            append: if `True`, add to any existing expressions.
1433                Otherwise, this resets the expressions.
1434            dialect: the dialect used to parse the input expressions.
1435            copy: if `False`, modify this expression instance in-place.
1436            opts: other options to use to parse the input expressions.
1437
1438        Returns:
1439            The modified Select expression.
1440        """
1441        return _apply_list_builder(
1442            *expressions,
1443            instance=self,
1444            arg="laterals",
1445            append=append,
1446            into=Lateral,
1447            prefix="LATERAL VIEW",
1448            dialect=dialect,
1449            copy=copy,
1450            **opts,
1451        )
1452
1453    def join(
1454        self,
1455        expression: ExpOrStr,
1456        on: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1457        using: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1458        append: bool = True,
1459        join_type: str | None = None,
1460        join_alias: Identifier | str | None = None,
1461        dialect: DialectType = None,
1462        copy: bool = True,
1463        **opts: Unpack[ParserNoDialectArgs],
1464    ) -> Select:
1465        """
1466        Append to or set the JOIN expressions.
1467
1468        Example:
1469            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
1470            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
1471
1472            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
1473            'SELECT 1 FROM a JOIN b USING (x, y, z)'
1474
1475            Use `join_type` to change the type of join:
1476
1477            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
1478            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
1479
1480        Args:
1481            expression: the SQL code string to parse.
1482                If an `Expr` instance is passed, it will be used as-is.
1483            on: optionally specify the join "on" criteria as a SQL string.
1484                If an `Expr` instance is passed, it will be used as-is.
1485            using: optionally specify the join "using" criteria as a SQL string.
1486                If an `Expr` instance is passed, it will be used as-is.
1487            append: if `True`, add to any existing expressions.
1488                Otherwise, this resets the expressions.
1489            join_type: if set, alter the parsed join type.
1490            join_alias: an optional alias for the joined source.
1491            dialect: the dialect used to parse the input expressions.
1492            copy: if `False`, modify this expression instance in-place.
1493            opts: other options to use to parse the input expressions.
1494
1495        Returns:
1496            Select: the modified expression.
1497        """
1498        parse_args: ParserArgs = {"dialect": dialect, **opts}
1499        try:
1500            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
1501        except ParseError:
1502            expression = maybe_parse(expression, into=(Join, Expr), **parse_args)
1503
1504        join = expression if isinstance(expression, Join) else Join(this=expression, kind="CROSS")
1505
1506        if join.kind == "CROSS" and (on or using or join_type):
1507            join.set("kind", None)
1508
1509        if isinstance(join.this, Select):
1510            join.this.replace(join.this.subquery())
1511
1512        if join_type:
1513            new_join: Join = maybe_parse(f"FROM _ {join_type} JOIN _", **parse_args).find(Join)
1514            method = new_join.method
1515            side = new_join.side
1516            kind = new_join.kind
1517
1518            if method:
1519                join.set("method", method)
1520            if side:
1521                join.set("side", side)
1522            if kind:
1523                join.set("kind", kind)
1524
1525        if on:
1526            on_exprs: list[ExpOrStr] = ensure_list(on)
1527            on = and_(*on_exprs, dialect=dialect, copy=copy, **opts)
1528            join.set("on", on)
1529
1530        if using:
1531            using_exprs: list[ExpOrStr] = ensure_list(using)
1532            join = _apply_list_builder(
1533                *using_exprs,
1534                instance=join,
1535                arg="using",
1536                append=append,
1537                copy=copy,
1538                into=Identifier,
1539                **opts,
1540            )
1541
1542        if join_alias:
1543            join.set("this", alias_(join.this, join_alias, table=True))
1544
1545        return _apply_list_builder(
1546            join,
1547            instance=self,
1548            arg="joins",
1549            append=append,
1550            copy=copy,
1551            **opts,
1552        )
1553
1554    def having(
1555        self,
1556        *expressions: ExpOrStr | None,
1557        append: bool = True,
1558        dialect: DialectType = None,
1559        copy: bool = True,
1560        **opts: Unpack[ParserNoDialectArgs],
1561    ) -> Select:
1562        """
1563        Append to or set the HAVING expressions.
1564
1565        Example:
1566            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
1567            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
1568
1569        Args:
1570            *expressions: the SQL code strings to parse.
1571                If an `Expr` instance is passed, it will be used as-is.
1572                Multiple expressions are combined with an AND operator.
1573            append: if `True`, AND the new expressions to any existing expression.
1574                Otherwise, this resets the expression.
1575            dialect: the dialect used to parse the input expressions.
1576            copy: if `False`, modify this expression instance in-place.
1577            opts: other options to use to parse the input expressions.
1578
1579        Returns:
1580            The modified Select expression.
1581        """
1582        return _apply_conjunction_builder(
1583            *expressions,
1584            instance=self,
1585            arg="having",
1586            append=append,
1587            into=Having,
1588            dialect=dialect,
1589            copy=copy,
1590            **opts,
1591        )
1592
1593    def window(
1594        self,
1595        *expressions: ExpOrStr | None,
1596        append: bool = True,
1597        dialect: DialectType = None,
1598        copy: bool = True,
1599        **opts: Unpack[ParserNoDialectArgs],
1600    ) -> Select:
1601        return _apply_list_builder(
1602            *expressions,
1603            instance=self,
1604            arg="windows",
1605            append=append,
1606            into=Window,
1607            dialect=dialect,
1608            copy=copy,
1609            **opts,
1610        )
1611
1612    def qualify(
1613        self,
1614        *expressions: ExpOrStr | None,
1615        append: bool = True,
1616        dialect: DialectType = None,
1617        copy: bool = True,
1618        **opts: Unpack[ParserNoDialectArgs],
1619    ) -> Select:
1620        return _apply_conjunction_builder(
1621            *expressions,
1622            instance=self,
1623            arg="qualify",
1624            append=append,
1625            into=Qualify,
1626            dialect=dialect,
1627            copy=copy,
1628            **opts,
1629        )
1630
1631    def distinct(self, *ons: ExpOrStr | None, distinct: bool = True, copy: bool = True) -> Select:
1632        """
1633        Set the OFFSET expression.
1634
1635        Example:
1636            >>> Select().from_("tbl").select("x").distinct().sql()
1637            'SELECT DISTINCT x FROM tbl'
1638
1639        Args:
1640            ons: the expressions to distinct on
1641            distinct: whether the Select should be distinct
1642            copy: if `False`, modify this expression instance in-place.
1643
1644        Returns:
1645            Select: the modified expression.
1646        """
1647        instance = maybe_copy(self, copy)
1648        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
1649        instance.set("distinct", Distinct(on=on) if distinct else None)
1650        return instance
1651
1652    def ctas(
1653        self,
1654        table: ExpOrStr,
1655        properties: dict | None = None,
1656        dialect: DialectType = None,
1657        copy: bool = True,
1658        **opts: Unpack[ParserNoDialectArgs],
1659    ) -> Create:
1660        """
1661        Convert this expression to a CREATE TABLE AS statement.
1662
1663        Example:
1664            >>> Select().select("*").from_("tbl").ctas("x").sql()
1665            'CREATE TABLE x AS SELECT * FROM tbl'
1666
1667        Args:
1668            table: the SQL code string to parse as the table name.
1669                If another `Expr` instance is passed, it will be used as-is.
1670            properties: an optional mapping of table properties
1671            dialect: the dialect used to parse the input table.
1672            copy: if `False`, modify this expression instance in-place.
1673            opts: other options to use to parse the input table.
1674
1675        Returns:
1676            The new Create expression.
1677        """
1678        instance = maybe_copy(self, copy)
1679        table_expression = maybe_parse(table, into=Table, dialect=dialect, **opts)
1680
1681        properties_expression = None
1682        if properties:
1683            from sqlglot.expressions.properties import Properties as _Properties
1684
1685            properties_expression = _Properties.from_dict(properties)
1686
1687        from sqlglot.expressions.ddl import Create as _Create
1688
1689        return _Create(
1690            this=table_expression,
1691            kind="TABLE",
1692            expression=instance,
1693            properties=properties_expression,
1694        )
1695
1696    def lock(self, update: bool = True, copy: bool = True) -> Select:
1697        """
1698        Set the locking read mode for this expression.
1699
1700        Examples:
1701            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
1702            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
1703
1704            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
1705            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
1706
1707        Args:
1708            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
1709            copy: if `False`, modify this expression instance in-place.
1710
1711        Returns:
1712            The modified expression.
1713        """
1714        inst = maybe_copy(self, copy)
1715        inst.set("locks", [Lock(update=update)])
1716
1717        return inst
1718
1719    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
1720        """
1721        Set hints for this expression.
1722
1723        Examples:
1724            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
1725            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
1726
1727        Args:
1728            hints: The SQL code strings to parse as the hints.
1729                If an `Expr` instance is passed, it will be used as-is.
1730            dialect: The dialect used to parse the hints.
1731            copy: If `False`, modify this expression instance in-place.
1732
1733        Returns:
1734            The modified expression.
1735        """
1736        inst = maybe_copy(self, copy)
1737        inst.set(
1738            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
1739        )
1740
1741        return inst
1742
1743    @property
1744    def named_selects(self) -> list[str]:
1745        selects = []
1746
1747        for e in self.expressions:
1748            if e.alias_or_name:
1749                selects.append(e.output_name)
1750            elif isinstance(e, Aliases):
1751                selects.extend([a.name for a in e.aliases])
1752        return selects
1753
1754    @property
1755    def is_star(self) -> bool:
1756        return any(expression.is_star for expression in self.expressions)
1757
1758    @property
1759    def selects(self) -> list[Expr]:
1760        return self.expressions
1761
1762
1763class Subquery(Expression, DerivedTable, Query):
1764    is_subquery: t.ClassVar[bool] = True
1765    arg_types = {
1766        "this": True,
1767        "alias": False,
1768        "with_": False,
1769        **QUERY_MODIFIERS,
1770    }
1771
1772    def unnest(self) -> Expr:
1773        """Returns the first non subquery."""
1774        expression: Expr = self
1775        while isinstance(expression, Subquery):
1776            expression = expression.this
1777        return expression
1778
1779    def unwrap(self) -> Subquery:
1780        expression = self
1781        while expression.same_parent and expression.is_wrapper:
1782            expression = t.cast(Subquery, expression.parent)
1783        return expression
1784
1785    def select(
1786        self,
1787        *expressions: ExpOrStr | None,
1788        append: bool = True,
1789        dialect: DialectType = None,
1790        copy: bool = True,
1791        **opts: Unpack[ParserNoDialectArgs],
1792    ) -> Subquery:
1793        this = maybe_copy(self, copy)
1794        inner = this.unnest()
1795        if hasattr(inner, "select"):
1796            inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1797        return this
1798
1799    @property
1800    def is_wrapper(self) -> bool:
1801        """
1802        Whether this Subquery acts as a simple wrapper around another expression.
1803
1804        SELECT * FROM (((SELECT * FROM t)))
1805                      ^
1806                      This corresponds to a "wrapper" Subquery node
1807        """
1808        return all(v is None for k, v in self.args.items() if k != "this")
1809
1810    @property
1811    def is_star(self) -> bool:
1812        return _is_star(self)
1813
1814    @property
1815    def output_name(self) -> str:
1816        return self.alias
1817
1818
1819class TableSample(Expression):
1820    arg_types = {
1821        "expressions": False,
1822        "method": False,
1823        "bucket_numerator": False,
1824        "bucket_denominator": False,
1825        "bucket_field": False,
1826        "percent": False,
1827        "rows": False,
1828        "size": False,
1829        "seed": False,
1830    }
1831
1832
1833class Tag(Expression):
1834    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
1835
1836    arg_types = {
1837        "this": False,
1838        "prefix": False,
1839        "postfix": False,
1840    }
1841
1842
1843class Pivot(Expression):
1844    arg_types = {
1845        "this": False,
1846        "alias": False,
1847        "expressions": False,
1848        "fields": False,
1849        "unpivot": False,
1850        "using": False,
1851        "group": False,
1852        "columns": False,
1853        "include_nulls": False,
1854        "default_on_null": False,
1855        "into": False,
1856        "with_": False,
1857        "identify_pivot_strings": False,
1858        "prefixed_pivot_columns": False,
1859        "pivot_column_naming": False,
1860        "value_columns_first": False,
1861    }
1862
1863    @property
1864    def unpivot(self) -> bool:
1865        return bool(self.args.get("unpivot"))
1866
1867    @property
1868    def fields(self) -> list[Expr]:
1869        return self.args.get("fields", [])
1870
1871    def output_columns(self, pre_pivot_columns: t.Iterable[str]) -> dict[str, str]:
1872        """
1873        Returns an ordered map of post-rename output column name -> pre-rename
1874        source-side name, in the order the (UN)PIVOT produces them.
1875
1876        For callers that just want the names, iterate the dict (or call .keys()):
1877            >>> from sqlglot import parse_one, exp
1878            >>> piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot)
1879            >>> list(piv.output_columns(["a", "b", "c"]))
1880            ['c', 'name', 'val']
1881
1882        AST shape:
1883            PIVOT(SUM(val) FOR name IN ('a', 'b')):
1884                expressions: aggregate(s), e.g. [Sum(this=Column(val))]
1885                fields:      [In(this=Column(name), expressions=[Literal('a'), Literal('b')])]
1886                columns:     optional explicit output identifiers (e.g. set by Snowflake)
1887
1888            UNPIVOT(val FOR name IN (a, b)):
1889                expressions: value Identifier(s), or Tuple(Identifiers) for multi-value
1890                fields:      [In(this=Identifier(name), expressions=[Column(a), Column(b)])]
1891                             For literal-aliased entries (`a AS 'x'`) the IN expressions
1892                             are wrapped in PivotAlias(this=Column, alias=Literal).
1893
1894        Args:
1895            pre_pivot_columns: Columns visible to the operator before it runs
1896                (e.g. the source table or subquery's projections).
1897        """
1898        if self.unpivot:
1899            excluded: set[str] = set()
1900            name_columns: list[Identifier] = []
1901            for field in self.fields:
1902                if not isinstance(field, In):
1903                    continue
1904                if isinstance(field.this, Identifier):
1905                    name_columns.append(field.this)
1906                for e in field.expressions:
1907                    excluded.update(c.output_name for c in e.find_all(Column))
1908            value_columns = [
1909                ident
1910                for e in self.expressions
1911                for ident in (e.expressions if isinstance(e, Tuple) else [e])
1912                if isinstance(ident, Identifier)
1913            ]
1914            # T-SQL emits the value column(s) ahead of the name column, everyone else emits them after it
1915            ordered = (
1916                value_columns + name_columns
1917                if self.args.get("value_columns_first")
1918                else name_columns + value_columns
1919            )
1920            outputs = [i.name for i in ordered]
1921        else:
1922            excluded = {c.output_name for c in self.find_all(Column)}
1923            outputs = [c.output_name for c in self.args.get("columns") or []]
1924            if not outputs:
1925                outputs = [c.alias_or_name for c in self.expressions]
1926
1927        if not excluded or not outputs:
1928            return {}
1929
1930        pre_rename = [c for c in pre_pivot_columns if c not in excluded] + outputs
1931
1932        alias = self.args.get("alias")
1933        renames = alias.args.get("columns") if alias else None
1934
1935        # `PIVOT(...) AS alias(c1, c2, ...)` renames the operator's output columns
1936        # positionally from the front (DuckDB, Snowflake): the user's names cover
1937        # the leading N output columns, remaining columns keep their auto names.
1938        if renames:
1939            rename_names = [r.name for r in renames]
1940            post_rename = rename_names + pre_rename[len(rename_names) :]
1941        else:
1942            post_rename = pre_rename
1943
1944        return dict(zip(post_rename, pre_rename))
1945
1946
1947class UnpivotColumns(Expression):
1948    arg_types = {"this": True, "expressions": True}
1949
1950
1951class Window(Expression, Condition):
1952    arg_types = {
1953        "this": True,
1954        "partition_by": False,
1955        "order": False,
1956        "spec": False,
1957        "alias": False,
1958        "over": False,
1959        "first": False,
1960    }
1961
1962
1963class WindowSpec(Expression):
1964    arg_types = {
1965        "kind": False,
1966        "start": False,
1967        "start_side": False,
1968        "end": False,
1969        "end_side": False,
1970        "exclude": False,
1971    }
1972
1973
1974class PartitionByExcluding(Expression):
1975    arg_types = {"expressions": True}
1976
1977
1978class PreWhere(Expression):
1979    pass
1980
1981
1982class Where(Expression):
1983    pass
1984
1985
1986class Optimize(Expression):
1987    arg_types = {"this": True, "full": False, "where": False, "zorder": False}
1988
1989
1990class Analyze(Expression):
1991    arg_types = {
1992        "kind": False,
1993        "tables": False,
1994        "options": False,
1995        "mode": False,
1996        "partition": False,
1997        "expression": False,
1998        "properties": False,
1999    }
2000
2001
2002class AnalyzeStatistics(Expression):
2003    arg_types = {
2004        "kind": True,
2005        "option": False,
2006        "this": False,
2007        "expressions": False,
2008    }
2009
2010
2011class AnalyzeHistogram(Expression):
2012    arg_types = {
2013        "this": True,
2014        "expressions": True,
2015        "expression": False,
2016        "update_options": False,
2017    }
2018
2019
2020class AnalyzeSample(Expression):
2021    arg_types = {"kind": True, "sample": True}
2022
2023
2024class AnalyzeListChainedRows(Expression):
2025    arg_types = {"expression": False}
2026
2027
2028class AnalyzeDelete(Expression):
2029    arg_types = {"kind": False}
2030
2031
2032class AnalyzeWith(Expression):
2033    arg_types = {"expressions": True}
2034
2035
2036class AnalyzeValidate(Expression):
2037    arg_types = {
2038        "kind": True,
2039        "this": False,
2040        "expression": False,
2041    }
2042
2043
2044class AnalyzeColumns(Expression):
2045    pass
2046
2047
2048class UsingData(Expression):
2049    pass
2050
2051
2052class AddPartition(Expression):
2053    arg_types = {"this": True, "exists": False, "location": False}
2054
2055
2056class AttachOption(Expression):
2057    arg_types = {"this": True, "expression": False}
2058
2059
2060class DropPartition(Expression):
2061    arg_types = {"expressions": True, "exists": False}
2062
2063
2064class ReplaceColumns(Expression):
2065    arg_types = {"expressions": True}
2066
2067
2068class ReplacePartition(Expression):
2069    arg_types = {"expression": True, "source": True}
2070
2071
2072class TranslateCharacters(Expression):
2073    arg_types = {"this": True, "expression": True, "with_error": False}
2074
2075
2076class OverflowTruncateBehavior(Expression):
2077    arg_types = {"this": False, "with_count": True}
2078
2079
2080class JSON(Expression):
2081    arg_types = {"this": False, "with_": False, "unique": False}
2082
2083
2084class JSONPath(Expression):
2085    arg_types = {"expressions": True}
2086
2087    @property
2088    def output_name(self) -> str:
2089        last_segment = self.expressions[-1].this
2090        return last_segment if isinstance(last_segment, str) else ""
2091
2092
2093class JSONPathPart(Expression):
2094    arg_types = {}
2095
2096
2097class JSONPathFilter(JSONPathPart):
2098    arg_types = {"this": True}
2099    _hash_raw_args = True
2100
2101
2102class JSONPathKey(JSONPathPart):
2103    arg_types = {"this": True, "quoted": False}
2104    _hash_raw_args = True
2105
2106
2107class JSONPathRecursive(JSONPathPart):
2108    arg_types = {"this": False}
2109    _hash_raw_args = True
2110
2111
2112class JSONPathRoot(JSONPathPart):
2113    pass
2114
2115
2116class JSONPathScript(JSONPathPart):
2117    arg_types = {"this": True}
2118    _hash_raw_args = True
2119
2120
2121class JSONPathSlice(JSONPathPart):
2122    arg_types = {"start": False, "end": False, "step": False}
2123
2124
2125class JSONPathSelector(JSONPathPart):
2126    arg_types = {"this": True}
2127
2128
2129class JSONPathSubscript(JSONPathPart):
2130    arg_types = {"this": True}
2131
2132
2133class JSONPathUnion(JSONPathPart):
2134    arg_types = {"expressions": True}
2135    _hash_raw_args = True
2136
2137
2138class JSONPathWildcard(JSONPathPart):
2139    pass
2140
2141
2142class FormatJson(Expression):
2143    pass
2144
2145
2146class JSONKeyValue(Expression):
2147    arg_types = {"this": True, "expression": True}
2148
2149
2150class JSONColumnDef(Expression):
2151    arg_types = {
2152        "this": False,
2153        "kind": False,
2154        "path": False,
2155        "nested_schema": False,
2156        "ordinality": False,
2157        "format_json": False,
2158    }
2159
2160
2161class JSONSchema(Expression):
2162    arg_types = {"expressions": True}
2163
2164
2165class JSONValue(Expression):
2166    arg_types = {
2167        "this": True,
2168        "path": True,
2169        "returning": False,
2170        "on_condition": False,
2171    }
2172
2173
2174class JSONValueArray(Expression, Func):
2175    arg_types = {"this": True, "expression": False}
2176
2177
2178class OpenJSONColumnDef(Expression):
2179    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
2180
2181
2182class JSONExtractQuote(Expression):
2183    arg_types = {
2184        "option": True,
2185        "scalar": False,
2186    }
2187
2188
2189class ScopeResolution(Expression):
2190    arg_types = {"this": False, "expression": True}
2191
2192
2193class Stream(Expression):
2194    pass
2195
2196
2197class ModelAttribute(Expression):
2198    arg_types = {"this": True, "expression": True}
2199
2200
2201class XMLNamespace(Expression):
2202    pass
2203
2204
2205class XMLKeyValueOption(Expression):
2206    arg_types = {"this": True, "expression": False}
2207
2208
2209class Semicolon(Expression):
2210    arg_types = {}
2211
2212
2213class TableColumn(Expression):
2214    @property
2215    def output_name(self) -> str:
2216        return self.name
2217
2218
2219class Variadic(Expression):
2220    pass
2221
2222
2223class StoredProcedure(Expression):
2224    arg_types = {"this": True, "expressions": False, "wrapped": False}
2225
2226
2227class Block(Expression):
2228    arg_types = {"expressions": True, "begin": False}
2229
2230
2231class IfBlock(Expression):
2232    arg_types = {"this": True, "true": True, "false": False}
2233
2234
2235class CaseStatement(Expression):
2236    arg_types = {"this": False, "ifs": True, "default": False}
2237
2238
2239class WhileBlock(Expression):
2240    arg_types = {"this": True, "body": True, "label": False}
2241
2242
2243class LoopBlock(Expression):
2244    arg_types = {"body": True, "label": False}
2245
2246
2247class RepeatBlock(Expression):
2248    arg_types = {"body": True, "until": True, "label": False}
2249
2250
2251class Leave(Expression):
2252    pass
2253
2254
2255class Iterate(Expression):
2256    pass
2257
2258
2259class EndStatement(Expression):
2260    arg_types = {}
2261
2262
2263# https://trino.io/docs/current/udf.html
2264class FunctionSpecification(Expression):
2265    arg_types = {
2266        "this": True,
2267        "characteristics": False,
2268        "properties": False,
2269        "expression": True,
2270    }
2271
2272
2273UNWRAPPED_QUERIES = (Select, SetOperation)
2274
2275
2276def union(
2277    *expressions: ExpOrStr,
2278    distinct: bool = True,
2279    dialect: DialectType = None,
2280    copy: bool = True,
2281    **opts: Unpack[ParserNoDialectArgs],
2282) -> Union:
2283    """
2284    Initializes a syntax tree for the `UNION` operation.
2285
2286    Example:
2287        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
2288        'SELECT * FROM foo UNION SELECT * FROM bla'
2289
2290    Args:
2291        expressions: the SQL code strings, corresponding to the `UNION`'s operands.
2292            If `Expr` instances are passed, they will be used as-is.
2293        distinct: set the DISTINCT flag if and only if this is true.
2294        dialect: the dialect used to parse the input expression.
2295        copy: whether to copy the expression.
2296        opts: other options to use to parse the input expressions.
2297
2298    Returns:
2299        The new Union instance.
2300    """
2301    assert len(expressions) >= 2, "At least two expressions are required by `union`."
2302    return _apply_set_operation(
2303        *expressions, set_operation=Union, distinct=distinct, dialect=dialect, copy=copy, **opts
2304    )
2305
2306
2307def intersect(
2308    *expressions: ExpOrStr,
2309    distinct: bool = True,
2310    dialect: DialectType = None,
2311    copy: bool = True,
2312    **opts: Unpack[ParserNoDialectArgs],
2313) -> Intersect:
2314    """
2315    Initializes a syntax tree for the `INTERSECT` operation.
2316
2317    Example:
2318        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
2319        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
2320
2321    Args:
2322        expressions: the SQL code strings, corresponding to the `INTERSECT`'s operands.
2323            If `Expr` instances are passed, they will be used as-is.
2324        distinct: set the DISTINCT flag if and only if this is true.
2325        dialect: the dialect used to parse the input expression.
2326        copy: whether to copy the expression.
2327        opts: other options to use to parse the input expressions.
2328
2329    Returns:
2330        The new Intersect instance.
2331    """
2332    assert len(expressions) >= 2, "At least two expressions are required by `intersect`."
2333    return _apply_set_operation(
2334        *expressions, set_operation=Intersect, distinct=distinct, dialect=dialect, copy=copy, **opts
2335    )
2336
2337
2338def except_(
2339    *expressions: ExpOrStr,
2340    distinct: bool = True,
2341    dialect: DialectType = None,
2342    copy: bool = True,
2343    **opts: Unpack[ParserNoDialectArgs],
2344) -> Except:
2345    """
2346    Initializes a syntax tree for the `EXCEPT` operation.
2347
2348    Example:
2349        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
2350        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
2351
2352    Args:
2353        expressions: the SQL code strings, corresponding to the `EXCEPT`'s operands.
2354            If `Expr` instances are passed, they will be used as-is.
2355        distinct: set the DISTINCT flag if and only if this is true.
2356        dialect: the dialect used to parse the input expression.
2357        copy: whether to copy the expression.
2358        opts: other options to use to parse the input expressions.
2359
2360    Returns:
2361        The new Except instance.
2362    """
2363    assert len(expressions) >= 2, "At least two expressions are required by `except_`."
2364    return _apply_set_operation(
2365        *expressions, set_operation=Except, distinct=distinct, dialect=dialect, copy=copy, **opts
2366    )
@trait
class Selectable(sqlglot.expressions.core.Expr):
82@trait
83class Selectable(Expr):
84    @property
85    def selects(self) -> list[Expr]:
86        raise NotImplementedError("Subclasses must implement selects")
87
88    @property
89    def named_selects(self) -> list[str]:
90        return _named_selects(self)
selects: list[sqlglot.expressions.core.Expr]
84    @property
85    def selects(self) -> list[Expr]:
86        raise NotImplementedError("Subclasses must implement selects")
named_selects: list[str]
88    @property
89    def named_selects(self) -> list[str]:
90        return _named_selects(self)
key: ClassVar[str] = 'selectable'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class DerivedTable(Selectable):
 98@trait
 99class DerivedTable(Selectable):
100    @property
101    def selects(self) -> list[Expr]:
102        this = self.this
103        return this.selects if isinstance(this, Query) else []
selects: list[sqlglot.expressions.core.Expr]
100    @property
101    def selects(self) -> list[Expr]:
102        this = self.this
103        return this.selects if isinstance(this, Query) else []
key: ClassVar[str] = 'derivedtable'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class UDTF(DerivedTable):
106@trait
107class UDTF(DerivedTable):
108    @property
109    def selects(self) -> list[Expr]:
110        alias = self.args.get("alias")
111        return alias.columns if alias else []
selects: list[sqlglot.expressions.core.Expr]
108    @property
109    def selects(self) -> list[Expr]:
110        alias = self.args.get("alias")
111        return alias.columns if alias else []
key: ClassVar[str] = 'udtf'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class Query(Selectable):
114@trait
115class Query(Selectable):
116    """Trait for any SELECT/UNION/etc. query expression."""
117
118    @property
119    def ctes(self) -> list[CTE]:
120        with_ = self.args.get("with_")
121        return with_.expressions if with_ else []
122
123    def select(
124        self: Q,
125        *expressions: ExpOrStr | None,
126        append: bool = True,
127        dialect: DialectType = None,
128        copy: bool = True,
129        **opts: Unpack[ParserNoDialectArgs],
130    ) -> Q:
131        raise NotImplementedError("Query objects must implement `select`")
132
133    def subquery(self, alias: ExpOrStr | None = None, copy: bool = True) -> Subquery:
134        """
135        Returns a `Subquery` that wraps around this query.
136
137        Example:
138            >>> subquery = Select().select("x").from_("tbl").subquery()
139            >>> Select().select("x").from_(subquery).sql()
140            'SELECT x FROM (SELECT x FROM tbl)'
141
142        Args:
143            alias: an optional alias for the subquery.
144            copy: if `False`, modify this expression instance in-place.
145        """
146        instance = maybe_copy(self, copy)
147        if not isinstance(alias, Expr):
148            alias = TableAlias(this=to_identifier(alias)) if alias else None
149
150        return Subquery(this=instance, alias=alias)
151
152    def limit(
153        self: Q,
154        expression: ExpOrStr | int,
155        dialect: DialectType = None,
156        copy: bool = True,
157        **opts: Unpack[ParserNoDialectArgs],
158    ) -> Q:
159        """
160        Adds a LIMIT clause to this query.
161
162        Example:
163            >>> Select().select("1").union(Select().select("1")).limit(1).sql()
164            'SELECT 1 UNION SELECT 1 LIMIT 1'
165
166        Args:
167            expression: the SQL code string to parse.
168                This can also be an integer.
169                If a `Limit` instance is passed, it will be used as-is.
170                If another `Expr` instance is passed, it will be wrapped in a `Limit`.
171            dialect: the dialect used to parse the input expression.
172            copy: if `False`, modify this expression instance in-place.
173            opts: other options to use to parse the input expressions.
174
175        Returns:
176            A limited Select expression.
177        """
178        return _apply_builder(
179            expression=expression,
180            instance=self,
181            arg="limit",
182            into=Limit,
183            prefix="LIMIT",
184            dialect=dialect,
185            copy=copy,
186            into_arg="expression",
187            **opts,
188        )
189
190    def offset(
191        self: Q,
192        expression: ExpOrStr | int,
193        dialect: DialectType = None,
194        copy: bool = True,
195        **opts: Unpack[ParserNoDialectArgs],
196    ) -> Q:
197        """
198        Set the OFFSET expression.
199
200        Example:
201            >>> Select().from_("tbl").select("x").offset(10).sql()
202            'SELECT x FROM tbl OFFSET 10'
203
204        Args:
205            expression: the SQL code string to parse.
206                This can also be an integer.
207                If a `Offset` instance is passed, this is used as-is.
208                If another `Expr` instance is passed, it will be wrapped in a `Offset`.
209            dialect: the dialect used to parse the input expression.
210            copy: if `False`, modify this expression instance in-place.
211            opts: other options to use to parse the input expressions.
212
213        Returns:
214            The modified Select expression.
215        """
216        return _apply_builder(
217            expression=expression,
218            instance=self,
219            arg="offset",
220            into=Offset,
221            prefix="OFFSET",
222            dialect=dialect,
223            copy=copy,
224            into_arg="expression",
225            **opts,
226        )
227
228    def order_by(
229        self: Q,
230        *expressions: ExpOrStr | None,
231        append: bool = True,
232        dialect: DialectType = None,
233        copy: bool = True,
234        **opts: Unpack[ParserNoDialectArgs],
235    ) -> Q:
236        """
237        Set the ORDER BY expression.
238
239        Example:
240            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
241            'SELECT x FROM tbl ORDER BY x DESC'
242
243        Args:
244            *expressions: the SQL code strings to parse.
245                If a `Group` instance is passed, this is used as-is.
246                If another `Expr` instance is passed, it will be wrapped in a `Order`.
247            append: if `True`, add to any existing expressions.
248                Otherwise, this flattens all the `Order` expression into a single expression.
249            dialect: the dialect used to parse the input expression.
250            copy: if `False`, modify this expression instance in-place.
251            opts: other options to use to parse the input expressions.
252
253        Returns:
254            The modified Select expression.
255        """
256        return _apply_child_list_builder(
257            *expressions,
258            instance=self,
259            arg="order",
260            append=append,
261            copy=copy,
262            prefix="ORDER BY",
263            into=Order,
264            dialect=dialect,
265            **opts,
266        )
267
268    def where(
269        self: Q,
270        *expressions: ExpOrStr | None,
271        append: bool = True,
272        dialect: DialectType = None,
273        copy: bool = True,
274        **opts: Unpack[ParserNoDialectArgs],
275    ) -> Q:
276        """
277        Append to or set the WHERE expressions.
278
279        Examples:
280            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
281            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
282
283        Args:
284            *expressions: the SQL code strings to parse.
285                If an `Expr` instance is passed, it will be used as-is.
286                Multiple expressions are combined with an AND operator.
287            append: if `True`, AND the new expressions to any existing expression.
288                Otherwise, this resets the expression.
289            dialect: the dialect used to parse the input expressions.
290            copy: if `False`, modify this expression instance in-place.
291            opts: other options to use to parse the input expressions.
292
293        Returns:
294            The modified expression.
295        """
296        return _apply_conjunction_builder(
297            *[expr.this if isinstance(expr, Where) else expr for expr in expressions],
298            instance=self,
299            arg="where",
300            append=append,
301            into=Where,
302            dialect=dialect,
303            copy=copy,
304            **opts,
305        )
306
307    def with_(
308        self: Q,
309        alias: ExpOrStr,
310        as_: ExpOrStr,
311        recursive: bool | None = None,
312        materialized: bool | None = None,
313        append: bool = True,
314        dialect: DialectType = None,
315        copy: bool = True,
316        scalar: bool | None = None,
317        **opts: Unpack[ParserNoDialectArgs],
318    ) -> Q:
319        """
320        Append to or set the common table expressions.
321
322        Example:
323            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
324            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
325
326        Args:
327            alias: the SQL code string to parse as the table name.
328                If an `Expr` instance is passed, this is used as-is.
329            as_: the SQL code string to parse as the table expression.
330                If an `Expr` instance is passed, it will be used as-is.
331            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
332            materialized: set the MATERIALIZED part of the expression.
333            append: if `True`, add to any existing expressions.
334                Otherwise, this resets the expressions.
335            dialect: the dialect used to parse the input expression.
336            copy: if `False`, modify this expression instance in-place.
337            scalar: if `True`, this is a scalar common table expression.
338            opts: other options to use to parse the input expressions.
339
340        Returns:
341            The modified expression.
342        """
343        return _apply_cte_builder(
344            self,
345            alias,
346            as_,
347            recursive=recursive,
348            materialized=materialized,
349            append=append,
350            dialect=dialect,
351            copy=copy,
352            scalar=scalar,
353            **opts,
354        )
355
356    def union(
357        self,
358        *expressions: ExpOrStr,
359        distinct: bool = True,
360        dialect: DialectType = None,
361        copy: bool = True,
362        **opts: Unpack[ParserNoDialectArgs],
363    ) -> Union:
364        """
365        Builds a UNION expression.
366
367        Example:
368            >>> import sqlglot
369            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
370            'SELECT * FROM foo UNION SELECT * FROM bla'
371
372        Args:
373            expressions: the SQL code strings.
374                If `Expr` instances are passed, they will be used as-is.
375            distinct: set the DISTINCT flag if and only if this is true.
376            dialect: the dialect used to parse the input expression.
377            opts: other options to use to parse the input expressions.
378
379        Returns:
380            The new Union expression.
381        """
382        return union(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
383
384    def intersect(
385        self,
386        *expressions: ExpOrStr,
387        distinct: bool = True,
388        dialect: DialectType = None,
389        copy: bool = True,
390        **opts: Unpack[ParserNoDialectArgs],
391    ) -> Intersect:
392        """
393        Builds an INTERSECT expression.
394
395        Example:
396            >>> import sqlglot
397            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
398            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
399
400        Args:
401            expressions: the SQL code strings.
402                If `Expr` instances are passed, they will be used as-is.
403            distinct: set the DISTINCT flag if and only if this is true.
404            dialect: the dialect used to parse the input expression.
405            opts: other options to use to parse the input expressions.
406
407        Returns:
408            The new Intersect expression.
409        """
410        return intersect(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)
411
412    def except_(
413        self,
414        *expressions: ExpOrStr,
415        distinct: bool = True,
416        dialect: DialectType = None,
417        copy: bool = True,
418        **opts: Unpack[ParserNoDialectArgs],
419    ) -> Except:
420        """
421        Builds an EXCEPT expression.
422
423        Example:
424            >>> import sqlglot
425            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
426            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
427
428        Args:
429            expressions: the SQL code strings.
430                If `Expr` instance are passed, they will be used as-is.
431            distinct: set the DISTINCT flag if and only if this is true.
432            dialect: the dialect used to parse the input expression.
433            opts: other options to use to parse the input expressions.
434
435        Returns:
436            The new Except expression.
437        """
438        return except_(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)

Trait for any SELECT/UNION/etc. query expression.

ctes: list[CTE]
118    @property
119    def ctes(self) -> list[CTE]:
120        with_ = self.args.get("with_")
121        return with_.expressions if with_ else []
def select( self: ~Q, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> ~Q:
123    def select(
124        self: Q,
125        *expressions: ExpOrStr | None,
126        append: bool = True,
127        dialect: DialectType = None,
128        copy: bool = True,
129        **opts: Unpack[ParserNoDialectArgs],
130    ) -> Q:
131        raise NotImplementedError("Query objects must implement `select`")
def subquery( self, alias: Union[int, str, sqlglot.expressions.core.Expr, NoneType] = None, copy: bool = True) -> Subquery:
133    def subquery(self, alias: ExpOrStr | None = None, copy: bool = True) -> Subquery:
134        """
135        Returns a `Subquery` that wraps around this query.
136
137        Example:
138            >>> subquery = Select().select("x").from_("tbl").subquery()
139            >>> Select().select("x").from_(subquery).sql()
140            'SELECT x FROM (SELECT x FROM tbl)'
141
142        Args:
143            alias: an optional alias for the subquery.
144            copy: if `False`, modify this expression instance in-place.
145        """
146        instance = maybe_copy(self, copy)
147        if not isinstance(alias, Expr):
148            alias = TableAlias(this=to_identifier(alias)) if alias else None
149
150        return Subquery(this=instance, alias=alias)

Returns a Subquery that wraps around this query.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias: an optional alias for the subquery.
  • copy: if False, modify this expression instance in-place.
def limit( self: ~Q, expression: Union[int, str, sqlglot.expressions.core.Expr], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> ~Q:
152    def limit(
153        self: Q,
154        expression: ExpOrStr | int,
155        dialect: DialectType = None,
156        copy: bool = True,
157        **opts: Unpack[ParserNoDialectArgs],
158    ) -> Q:
159        """
160        Adds a LIMIT clause to this query.
161
162        Example:
163            >>> Select().select("1").union(Select().select("1")).limit(1).sql()
164            'SELECT 1 UNION SELECT 1 LIMIT 1'
165
166        Args:
167            expression: the SQL code string to parse.
168                This can also be an integer.
169                If a `Limit` instance is passed, it will be used as-is.
170                If another `Expr` instance is passed, it will be wrapped in a `Limit`.
171            dialect: the dialect used to parse the input expression.
172            copy: if `False`, modify this expression instance in-place.
173            opts: other options to use to parse the input expressions.
174
175        Returns:
176            A limited Select expression.
177        """
178        return _apply_builder(
179            expression=expression,
180            instance=self,
181            arg="limit",
182            into=Limit,
183            prefix="LIMIT",
184            dialect=dialect,
185            copy=copy,
186            into_arg="expression",
187            **opts,
188        )

Adds a LIMIT clause to this query.

Example:
>>> Select().select("1").union(Select().select("1")).limit(1).sql()
'SELECT 1 UNION SELECT 1 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, it will be used as-is. If another Expr instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

A limited Select expression.

def offset( self: ~Q, expression: Union[int, str, sqlglot.expressions.core.Expr], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> ~Q:
190    def offset(
191        self: Q,
192        expression: ExpOrStr | int,
193        dialect: DialectType = None,
194        copy: bool = True,
195        **opts: Unpack[ParserNoDialectArgs],
196    ) -> Q:
197        """
198        Set the OFFSET expression.
199
200        Example:
201            >>> Select().from_("tbl").select("x").offset(10).sql()
202            'SELECT x FROM tbl OFFSET 10'
203
204        Args:
205            expression: the SQL code string to parse.
206                This can also be an integer.
207                If a `Offset` instance is passed, this is used as-is.
208                If another `Expr` instance is passed, it will be wrapped in a `Offset`.
209            dialect: the dialect used to parse the input expression.
210            copy: if `False`, modify this expression instance in-place.
211            opts: other options to use to parse the input expressions.
212
213        Returns:
214            The modified Select expression.
215        """
216        return _apply_builder(
217            expression=expression,
218            instance=self,
219            arg="offset",
220            into=Offset,
221            prefix="OFFSET",
222            dialect=dialect,
223            copy=copy,
224            into_arg="expression",
225            **opts,
226        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expr instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self: ~Q, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> ~Q:
228    def order_by(
229        self: Q,
230        *expressions: ExpOrStr | None,
231        append: bool = True,
232        dialect: DialectType = None,
233        copy: bool = True,
234        **opts: Unpack[ParserNoDialectArgs],
235    ) -> Q:
236        """
237        Set the ORDER BY expression.
238
239        Example:
240            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
241            'SELECT x FROM tbl ORDER BY x DESC'
242
243        Args:
244            *expressions: the SQL code strings to parse.
245                If a `Group` instance is passed, this is used as-is.
246                If another `Expr` instance is passed, it will be wrapped in a `Order`.
247            append: if `True`, add to any existing expressions.
248                Otherwise, this flattens all the `Order` expression into a single expression.
249            dialect: the dialect used to parse the input expression.
250            copy: if `False`, modify this expression instance in-place.
251            opts: other options to use to parse the input expressions.
252
253        Returns:
254            The modified Select expression.
255        """
256        return _apply_child_list_builder(
257            *expressions,
258            instance=self,
259            arg="order",
260            append=append,
261            copy=copy,
262            prefix="ORDER BY",
263            into=Order,
264            dialect=dialect,
265            **opts,
266        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expr instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def where( self: ~Q, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> ~Q:
268    def where(
269        self: Q,
270        *expressions: ExpOrStr | None,
271        append: bool = True,
272        dialect: DialectType = None,
273        copy: bool = True,
274        **opts: Unpack[ParserNoDialectArgs],
275    ) -> Q:
276        """
277        Append to or set the WHERE expressions.
278
279        Examples:
280            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
281            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
282
283        Args:
284            *expressions: the SQL code strings to parse.
285                If an `Expr` instance is passed, it will be used as-is.
286                Multiple expressions are combined with an AND operator.
287            append: if `True`, AND the new expressions to any existing expression.
288                Otherwise, this resets the expression.
289            dialect: the dialect used to parse the input expressions.
290            copy: if `False`, modify this expression instance in-place.
291            opts: other options to use to parse the input expressions.
292
293        Returns:
294            The modified expression.
295        """
296        return _apply_conjunction_builder(
297            *[expr.this if isinstance(expr, Where) else expr for expr in expressions],
298            instance=self,
299            arg="where",
300            append=append,
301            into=Where,
302            dialect=dialect,
303            copy=copy,
304            **opts,
305        )

Append to or set the WHERE expressions.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

def with_( self: ~Q, alias: Union[int, str, sqlglot.expressions.core.Expr], as_: Union[int, str, sqlglot.expressions.core.Expr], recursive: bool | None = None, materialized: bool | None = None, append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, scalar: bool | None = None, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> ~Q:
307    def with_(
308        self: Q,
309        alias: ExpOrStr,
310        as_: ExpOrStr,
311        recursive: bool | None = None,
312        materialized: bool | None = None,
313        append: bool = True,
314        dialect: DialectType = None,
315        copy: bool = True,
316        scalar: bool | None = None,
317        **opts: Unpack[ParserNoDialectArgs],
318    ) -> Q:
319        """
320        Append to or set the common table expressions.
321
322        Example:
323            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
324            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
325
326        Args:
327            alias: the SQL code string to parse as the table name.
328                If an `Expr` instance is passed, this is used as-is.
329            as_: the SQL code string to parse as the table expression.
330                If an `Expr` instance is passed, it will be used as-is.
331            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
332            materialized: set the MATERIALIZED part of the expression.
333            append: if `True`, add to any existing expressions.
334                Otherwise, this resets the expressions.
335            dialect: the dialect used to parse the input expression.
336            copy: if `False`, modify this expression instance in-place.
337            scalar: if `True`, this is a scalar common table expression.
338            opts: other options to use to parse the input expressions.
339
340        Returns:
341            The modified expression.
342        """
343        return _apply_cte_builder(
344            self,
345            alias,
346            as_,
347            recursive=recursive,
348            materialized=materialized,
349            append=append,
350            dialect=dialect,
351            copy=copy,
352            scalar=scalar,
353            **opts,
354        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expr instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expr instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • materialized: set the MATERIALIZED part of the expression.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • scalar: if True, this is a scalar common table expression.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

def union( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr], distinct: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Union:
356    def union(
357        self,
358        *expressions: ExpOrStr,
359        distinct: bool = True,
360        dialect: DialectType = None,
361        copy: bool = True,
362        **opts: Unpack[ParserNoDialectArgs],
363    ) -> Union:
364        """
365        Builds a UNION expression.
366
367        Example:
368            >>> import sqlglot
369            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
370            'SELECT * FROM foo UNION SELECT * FROM bla'
371
372        Args:
373            expressions: the SQL code strings.
374                If `Expr` instances are passed, they will be used as-is.
375            distinct: set the DISTINCT flag if and only if this is true.
376            dialect: the dialect used to parse the input expression.
377            opts: other options to use to parse the input expressions.
378
379        Returns:
380            The new Union expression.
381        """
382        return union(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expressions: the SQL code strings. If Expr instances are passed, they will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr], distinct: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Intersect:
384    def intersect(
385        self,
386        *expressions: ExpOrStr,
387        distinct: bool = True,
388        dialect: DialectType = None,
389        copy: bool = True,
390        **opts: Unpack[ParserNoDialectArgs],
391    ) -> Intersect:
392        """
393        Builds an INTERSECT expression.
394
395        Example:
396            >>> import sqlglot
397            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
398            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
399
400        Args:
401            expressions: the SQL code strings.
402                If `Expr` instances are passed, they will be used as-is.
403            distinct: set the DISTINCT flag if and only if this is true.
404            dialect: the dialect used to parse the input expression.
405            opts: other options to use to parse the input expressions.
406
407        Returns:
408            The new Intersect expression.
409        """
410        return intersect(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expressions: the SQL code strings. If Expr instances are passed, they will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr], distinct: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Except:
412    def except_(
413        self,
414        *expressions: ExpOrStr,
415        distinct: bool = True,
416        dialect: DialectType = None,
417        copy: bool = True,
418        **opts: Unpack[ParserNoDialectArgs],
419    ) -> Except:
420        """
421        Builds an EXCEPT expression.
422
423        Example:
424            >>> import sqlglot
425            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
426            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
427
428        Args:
429            expressions: the SQL code strings.
430                If `Expr` instance are passed, they will be used as-is.
431            distinct: set the DISTINCT flag if and only if this is true.
432            dialect: the dialect used to parse the input expression.
433            opts: other options to use to parse the input expressions.
434
435        Returns:
436            The new Except expression.
437        """
438        return except_(self, *expressions, distinct=distinct, dialect=dialect, copy=copy, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expressions: the SQL code strings. If Expr instance are passed, they will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

key: ClassVar[str] = 'query'
required_args: 't.ClassVar[set[str]]' = {'this'}
class QueryBand(sqlglot.expressions.core.Expression):
441class QueryBand(Expression):
442    arg_types = {"this": True, "scope": False, "update": False}
arg_types = {'this': True, 'scope': False, 'update': False}
key: ClassVar[str] = 'queryband'
required_args: 't.ClassVar[set[str]]' = {'this'}
class RecursiveWithSearch(sqlglot.expressions.core.Expression):
445class RecursiveWithSearch(Expression):
446    arg_types = {
447        "kind": True,
448        "this": True,
449        "expression": True,
450        "to": False,
451        "default": False,
452        "using": False,
453    }
arg_types = {'kind': True, 'this': True, 'expression': True, 'to': False, 'default': False, 'using': False}
key: ClassVar[str] = 'recursivewithsearch'
required_args: 't.ClassVar[set[str]]' = {'kind', 'expression', 'this'}
class With(sqlglot.expressions.core.Expression):
456class With(Expression):
457    arg_types = {
458        "expressions": False,
459        "recursive": False,
460        "search": False,
461        "cycle": False,
462        "udfs": False,
463    }
464
465    @property
466    def recursive(self) -> bool:
467        return bool(self.args.get("recursive"))
arg_types = {'expressions': False, 'recursive': False, 'search': False, 'cycle': False, 'udfs': False}
recursive: bool
465    @property
466    def recursive(self) -> bool:
467        return bool(self.args.get("recursive"))
key: ClassVar[str] = 'with'
required_args: 't.ClassVar[set[str]]' = set()
470class CTE(Expression, DerivedTable):
471    arg_types = {
472        "this": True,
473        "alias": True,
474        "scalar": False,
475        "materialized": False,
476        "key_expressions": False,
477    }
arg_types = {'this': True, 'alias': True, 'scalar': False, 'materialized': False, 'key_expressions': False}
key: ClassVar[str] = 'cte'
required_args: 't.ClassVar[set[str]]' = {'alias', 'this'}
class ProjectionDef(sqlglot.expressions.core.Expression):
480class ProjectionDef(Expression):
481    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'projectiondef'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class TableAlias(sqlglot.expressions.core.Expression):
484class TableAlias(Expression):
485    arg_types = {"this": False, "columns": False}
486
487    @property
488    def columns(self) -> list[t.Any]:
489        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns: list[typing.Any]
487    @property
488    def columns(self) -> list[t.Any]:
489        return self.args.get("columns") or []
key: ClassVar[str] = 'tablealias'
required_args: 't.ClassVar[set[str]]' = set()
492class BitString(Expression, Condition):
493    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'bitstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
496class HexString(Expression, Condition):
497    """Encoded hexadecimal data, binary by default or integer/character when flagged."""
498
499    arg_types = {"this": True, "is_integer": False, "is_character": False}
500    is_primitive = True

Encoded hexadecimal data, binary by default or integer/character when flagged.

arg_types = {'this': True, 'is_integer': False, 'is_character': False}
is_primitive = True
key: ClassVar[str] = 'hexstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
503class ByteString(Expression, Condition):
504    arg_types = {"this": True, "is_bytes": False}
505    is_primitive = True
506    _hash_raw_args = True
arg_types = {'this': True, 'is_bytes': False}
is_primitive = True
key: ClassVar[str] = 'bytestring'
required_args: 't.ClassVar[set[str]]' = {'this'}
509class RawString(Expression, Condition):
510    is_primitive = True
511    _hash_raw_args = True
is_primitive = True
key: ClassVar[str] = 'rawstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
514class UnicodeString(Expression, Condition):
515    arg_types = {"this": True, "escape": False}
516    _hash_raw_args = True
arg_types = {'this': True, 'escape': False}
key: ClassVar[str] = 'unicodestring'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ColumnPosition(sqlglot.expressions.core.Expression):
519class ColumnPosition(Expression):
520    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key: ClassVar[str] = 'columnposition'
required_args: 't.ClassVar[set[str]]' = {'position'}
class ColumnDef(sqlglot.expressions.core.Expression):
523class ColumnDef(Expression):
524    arg_types = {
525        "this": True,
526        "kind": False,
527        "constraints": False,
528        "exists": False,
529        "position": False,
530        "default": False,
531        "output": False,
532    }
533
534    @property
535    def constraints(self) -> list[ColumnConstraint]:
536        return self.args.get("constraints") or []
537
538    @property
539    def kind(self) -> DataType | None:
540        return self.args.get("kind")
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False, 'default': False, 'output': False}
constraints: list[sqlglot.expressions.constraints.ColumnConstraint]
534    @property
535    def constraints(self) -> list[ColumnConstraint]:
536        return self.args.get("constraints") or []
kind: sqlglot.expressions.datatypes.DataType | None
538    @property
539    def kind(self) -> DataType | None:
540        return self.args.get("kind")
key: ClassVar[str] = 'columndef'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Changes(sqlglot.expressions.core.Expression):
543class Changes(Expression):
544    arg_types = {"information": True, "at_before": False, "end": False}
arg_types = {'information': True, 'at_before': False, 'end': False}
key: ClassVar[str] = 'changes'
required_args: 't.ClassVar[set[str]]' = {'information'}
class Connect(sqlglot.expressions.core.Expression):
547class Connect(Expression):
548    arg_types = {"start": False, "connect": True, "nocycle": False}
arg_types = {'start': False, 'connect': True, 'nocycle': False}
key: ClassVar[str] = 'connect'
required_args: 't.ClassVar[set[str]]' = {'connect'}
class Prior(sqlglot.expressions.core.Expression):
551class Prior(Expression):
552    pass
key: ClassVar[str] = 'prior'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Into(sqlglot.expressions.core.Expression):
555class Into(Expression):
556    arg_types = {
557        "this": False,
558        "temporary": False,
559        "unlogged": False,
560        "bulk_collect": False,
561        "expressions": False,
562    }
arg_types = {'this': False, 'temporary': False, 'unlogged': False, 'bulk_collect': False, 'expressions': False}
key: ClassVar[str] = 'into'
required_args: 't.ClassVar[set[str]]' = set()
class From(sqlglot.expressions.core.Expression):
565class From(Expression):
566    @property
567    def name(self) -> str:
568        return self.this.name
569
570    @property
571    def alias_or_name(self) -> str:
572        return self.this.alias_or_name
name: str
566    @property
567    def name(self) -> str:
568        return self.this.name
alias_or_name: str
570    @property
571    def alias_or_name(self) -> str:
572        return self.this.alias_or_name
key: ClassVar[str] = 'from'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Having(sqlglot.expressions.core.Expression):
575class Having(Expression):
576    pass
key: ClassVar[str] = 'having'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Index(sqlglot.expressions.core.Expression):
579class Index(Expression):
580    arg_types = {
581        "this": False,
582        "table": False,
583        "unique": False,
584        "primary": False,
585        "amp": False,  # teradata
586        "params": False,
587    }
arg_types = {'this': False, 'table': False, 'unique': False, 'primary': False, 'amp': False, 'params': False}
key: ClassVar[str] = 'index'
required_args: 't.ClassVar[set[str]]' = set()
class ConditionalInsert(sqlglot.expressions.core.Expression):
590class ConditionalInsert(Expression):
591    arg_types = {"this": True, "expression": False, "else_": False}
arg_types = {'this': True, 'expression': False, 'else_': False}
key: ClassVar[str] = 'conditionalinsert'
required_args: 't.ClassVar[set[str]]' = {'this'}
class MultitableInserts(sqlglot.expressions.core.Expression):
594class MultitableInserts(Expression):
595    arg_types = {"with_": False, "expressions": True, "kind": False, "source": True}
arg_types = {'with_': False, 'expressions': True, 'kind': False, 'source': True}
key: ClassVar[str] = 'multitableinserts'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'source'}
class OnCondition(sqlglot.expressions.core.Expression):
598class OnCondition(Expression):
599    arg_types = {"error": False, "empty": False, "null": False}
arg_types = {'error': False, 'empty': False, 'null': False}
key: ClassVar[str] = 'oncondition'
required_args: 't.ClassVar[set[str]]' = set()
class Introducer(sqlglot.expressions.core.Expression):
602class Introducer(Expression):
603    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'introducer'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class National(sqlglot.expressions.core.Expression):
606class National(Expression):
607    is_primitive = True
608    _hash_raw_args = True
is_primitive = True
key: ClassVar[str] = 'national'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Partition(sqlglot.expressions.core.Expression):
611class Partition(Expression):
612    arg_types = {"expressions": True, "subpartition": False}
arg_types = {'expressions': True, 'subpartition': False}
key: ClassVar[str] = 'partition'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class PartitionRange(sqlglot.expressions.core.Expression):
615class PartitionRange(Expression):
616    arg_types = {"this": True, "expression": False, "expressions": False}
arg_types = {'this': True, 'expression': False, 'expressions': False}
key: ClassVar[str] = 'partitionrange'
required_args: 't.ClassVar[set[str]]' = {'this'}
class PartitionId(sqlglot.expressions.core.Expression):
619class PartitionId(Expression):
620    pass
key: ClassVar[str] = 'partitionid'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Fetch(sqlglot.expressions.core.Expression):
623class Fetch(Expression):
624    arg_types = {
625        "direction": False,
626        "count": False,
627        "limit_options": False,
628    }
arg_types = {'direction': False, 'count': False, 'limit_options': False}
key: ClassVar[str] = 'fetch'
required_args: 't.ClassVar[set[str]]' = set()
class Grant(sqlglot.expressions.core.Expression):
631class Grant(Expression):
632    arg_types = {
633        "privileges": True,
634        "kind": False,
635        "securable": True,
636        "principals": True,
637        "grant_option": False,
638    }
arg_types = {'privileges': True, 'kind': False, 'securable': True, 'principals': True, 'grant_option': False}
key: ClassVar[str] = 'grant'
required_args: 't.ClassVar[set[str]]' = {'securable', 'privileges', 'principals'}
class Revoke(sqlglot.expressions.core.Expression):
641class Revoke(Expression):
642    arg_types = {**Grant.arg_types, "cascade": False}
arg_types = {'privileges': True, 'kind': False, 'securable': True, 'principals': True, 'grant_option': False, 'cascade': False}
key: ClassVar[str] = 'revoke'
required_args: 't.ClassVar[set[str]]' = {'securable', 'privileges', 'principals'}
class Group(sqlglot.expressions.core.Expression):
645class Group(Expression):
646    arg_types = {
647        "expressions": False,
648        "grouping_sets": False,
649        "cube": False,
650        "rollup": False,
651        "totals": False,
652        "all": False,
653    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key: ClassVar[str] = 'group'
required_args: 't.ClassVar[set[str]]' = set()
class Cube(sqlglot.expressions.core.Expression):
656class Cube(Expression):
657    arg_types = {"expressions": False}
arg_types = {'expressions': False}
key: ClassVar[str] = 'cube'
required_args: 't.ClassVar[set[str]]' = set()
class Rollup(sqlglot.expressions.core.Expression):
660class Rollup(Expression):
661    arg_types = {"expressions": False}
arg_types = {'expressions': False}
key: ClassVar[str] = 'rollup'
required_args: 't.ClassVar[set[str]]' = set()
class GroupingSets(sqlglot.expressions.core.Expression):
664class GroupingSets(Expression):
665    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'groupingsets'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Lambda(sqlglot.expressions.core.Expression):
668class Lambda(Expression):
669    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key: ClassVar[str] = 'lambda'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
class Limit(sqlglot.expressions.core.Expression):
672class Limit(Expression):
673    arg_types = {
674        "this": False,
675        "expression": True,
676        "offset": False,
677        "limit_options": False,
678        "expressions": False,
679    }
680
681    @property
682    def is_limit_all(self) -> bool:
683        limit_expression = self.args.get("expression")
684        return isinstance(limit_expression, Var) and limit_expression.name.upper() == "ALL"
arg_types = {'this': False, 'expression': True, 'offset': False, 'limit_options': False, 'expressions': False}
is_limit_all: bool
681    @property
682    def is_limit_all(self) -> bool:
683        limit_expression = self.args.get("expression")
684        return isinstance(limit_expression, Var) and limit_expression.name.upper() == "ALL"
key: ClassVar[str] = 'limit'
required_args: 't.ClassVar[set[str]]' = {'expression'}
class LimitOptions(sqlglot.expressions.core.Expression):
687class LimitOptions(Expression):
688    arg_types = {
689        "percent": False,
690        "rows": False,
691        "with_ties": False,
692    }
arg_types = {'percent': False, 'rows': False, 'with_ties': False}
key: ClassVar[str] = 'limitoptions'
required_args: 't.ClassVar[set[str]]' = set()
class Join(sqlglot.expressions.core.Expression):
695class Join(Expression):
696    arg_types = {
697        "this": True,
698        "on": False,
699        "side": False,
700        "kind": False,
701        "using": False,
702        "method": False,
703        "global_": False,
704        "hint": False,
705        "match_condition": False,
706        "nearest": False,
707        "directed": False,
708        "expressions": False,
709        "pivots": False,
710    }
711
712    QUALIFIERS: t.ClassVar[tuple[str, ...]] = ("on", "using", "side", "kind", "method", "nearest")
713
714    @property
715    def method(self) -> str:
716        return self.text("method").upper()
717
718    @property
719    def kind(self) -> str:
720        return self.text("kind").upper()
721
722    @property
723    def side(self) -> str:
724        return self.text("side").upper()
725
726    @property
727    def hint(self) -> str:
728        return self.text("hint").upper()
729
730    @property
731    def alias_or_name(self) -> str:
732        return self.this.alias_or_name
733
734    @property
735    def is_semi_or_anti_join(self) -> bool:
736        return self.kind in ("SEMI", "ANTI")
737
738    def on(
739        self,
740        *expressions: ExpOrStr | None,
741        append: bool = True,
742        dialect: DialectType = None,
743        copy: bool = True,
744        **opts: Unpack[ParserNoDialectArgs],
745    ) -> Join:
746        """
747        Append to or set the ON expressions.
748
749        Example:
750            >>> import sqlglot
751            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
752            'JOIN x ON y = 1'
753
754        Args:
755            *expressions: the SQL code strings to parse.
756                If an `Expr` instance is passed, it will be used as-is.
757                Multiple expressions are combined with an AND operator.
758            append: if `True`, AND the new expressions to any existing expression.
759                Otherwise, this resets the expression.
760            dialect: the dialect used to parse the input expressions.
761            copy: if `False`, modify this expression instance in-place.
762            opts: other options to use to parse the input expressions.
763
764        Returns:
765            The modified Join expression.
766        """
767        join = _apply_conjunction_builder(
768            *expressions,
769            instance=self,
770            arg="on",
771            append=append,
772            dialect=dialect,
773            copy=copy,
774            **opts,
775        )
776
777        if join.kind == "CROSS":
778            join.set("kind", None)
779
780        return join
781
782    def using(
783        self,
784        *expressions: ExpOrStr | None,
785        append: bool = True,
786        dialect: DialectType = None,
787        copy: bool = True,
788        **opts: Unpack[ParserNoDialectArgs],
789    ) -> Join:
790        """
791        Append to or set the USING expressions.
792
793        Example:
794            >>> import sqlglot
795            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
796            'JOIN x USING (foo, bla)'
797
798        Args:
799            *expressions: the SQL code strings to parse.
800                If an `Expr` instance is passed, it will be used as-is.
801            append: if `True`, concatenate the new expressions to the existing "using" list.
802                Otherwise, this resets the expression.
803            dialect: the dialect used to parse the input expressions.
804            copy: if `False`, modify this expression instance in-place.
805            opts: other options to use to parse the input expressions.
806
807        Returns:
808            The modified Join expression.
809        """
810        join = _apply_list_builder(
811            *expressions,
812            instance=self,
813            arg="using",
814            append=append,
815            dialect=dialect,
816            copy=copy,
817            **opts,
818        )
819
820        if join.kind == "CROSS":
821            join.set("kind", None)
822
823        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global_': False, 'hint': False, 'match_condition': False, 'nearest': False, 'directed': False, 'expressions': False, 'pivots': False}
QUALIFIERS: ClassVar[tuple[str, ...]] = ('on', 'using', 'side', 'kind', 'method', 'nearest')
method: str
714    @property
715    def method(self) -> str:
716        return self.text("method").upper()
kind: str
718    @property
719    def kind(self) -> str:
720        return self.text("kind").upper()
side: str
722    @property
723    def side(self) -> str:
724        return self.text("side").upper()
hint: str
726    @property
727    def hint(self) -> str:
728        return self.text("hint").upper()
alias_or_name: str
730    @property
731    def alias_or_name(self) -> str:
732        return self.this.alias_or_name
is_semi_or_anti_join: bool
734    @property
735    def is_semi_or_anti_join(self) -> bool:
736        return self.kind in ("SEMI", "ANTI")
def on( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Join:
738    def on(
739        self,
740        *expressions: ExpOrStr | None,
741        append: bool = True,
742        dialect: DialectType = None,
743        copy: bool = True,
744        **opts: Unpack[ParserNoDialectArgs],
745    ) -> Join:
746        """
747        Append to or set the ON expressions.
748
749        Example:
750            >>> import sqlglot
751            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
752            'JOIN x ON y = 1'
753
754        Args:
755            *expressions: the SQL code strings to parse.
756                If an `Expr` instance is passed, it will be used as-is.
757                Multiple expressions are combined with an AND operator.
758            append: if `True`, AND the new expressions to any existing expression.
759                Otherwise, this resets the expression.
760            dialect: the dialect used to parse the input expressions.
761            copy: if `False`, modify this expression instance in-place.
762            opts: other options to use to parse the input expressions.
763
764        Returns:
765            The modified Join expression.
766        """
767        join = _apply_conjunction_builder(
768            *expressions,
769            instance=self,
770            arg="on",
771            append=append,
772            dialect=dialect,
773            copy=copy,
774            **opts,
775        )
776
777        if join.kind == "CROSS":
778            join.set("kind", None)
779
780        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Join:
782    def using(
783        self,
784        *expressions: ExpOrStr | None,
785        append: bool = True,
786        dialect: DialectType = None,
787        copy: bool = True,
788        **opts: Unpack[ParserNoDialectArgs],
789    ) -> Join:
790        """
791        Append to or set the USING expressions.
792
793        Example:
794            >>> import sqlglot
795            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
796            'JOIN x USING (foo, bla)'
797
798        Args:
799            *expressions: the SQL code strings to parse.
800                If an `Expr` instance is passed, it will be used as-is.
801            append: if `True`, concatenate the new expressions to the existing "using" list.
802                Otherwise, this resets the expression.
803            dialect: the dialect used to parse the input expressions.
804            copy: if `False`, modify this expression instance in-place.
805            opts: other options to use to parse the input expressions.
806
807        Returns:
808            The modified Join expression.
809        """
810        join = _apply_list_builder(
811            *expressions,
812            instance=self,
813            arg="using",
814            append=append,
815            dialect=dialect,
816            copy=copy,
817            **opts,
818        )
819
820        if join.kind == "CROSS":
821            join.set("kind", None)
822
823        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key: ClassVar[str] = 'join'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Nearest(sqlglot.expressions.core.Expression):
826class Nearest(Expression):
827    arg_types = {"this": True, "count": True, "approximate": False, "similarity": False}
arg_types = {'this': True, 'count': True, 'approximate': False, 'similarity': False}
key: ClassVar[str] = 'nearest'
required_args: 't.ClassVar[set[str]]' = {'count', 'this'}
class Lateral(sqlglot.expressions.core.Expression, UDTF):
830class Lateral(Expression, UDTF):
831    arg_types = {
832        "this": True,
833        "view": False,
834        "outer": False,
835        "alias": False,
836        "cross_apply": False,  # True -> CROSS APPLY, False -> OUTER APPLY
837        "ordinality": False,
838    }
839
840    @property
841    def selects(self) -> list[Expr]:
842        from sqlglot.expressions.array import Unnest
843
844        columns = super().selects
845
846        # UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset
847        offset = self.this.args.get("offset") if isinstance(self.this, Unnest) else None
848        if isinstance(offset, Identifier):
849            columns = columns + [offset]
850
851        return columns
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False, 'cross_apply': False, 'ordinality': False}
selects: list[sqlglot.expressions.core.Expr]
840    @property
841    def selects(self) -> list[Expr]:
842        from sqlglot.expressions.array import Unnest
843
844        columns = super().selects
845
846        # UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset
847        offset = self.this.args.get("offset") if isinstance(self.this, Unnest) else None
848        if isinstance(offset, Identifier):
849            columns = columns + [offset]
850
851        return columns
key: ClassVar[str] = 'lateral'
required_args: 't.ClassVar[set[str]]' = {'this'}
class TableArgument(sqlglot.expressions.core.Expression):
854class TableArgument(Expression):
855    """A relation passed to a table function with the TABLE keyword."""

A relation passed to a table function with the TABLE keyword.

key: ClassVar[str] = 'tableargument'
required_args: 't.ClassVar[set[str]]' = {'this'}
class TableFromRows(sqlglot.expressions.core.Expression, UDTF):
858class TableFromRows(Expression, UDTF):
859    arg_types = {
860        "this": True,
861        "alias": False,
862        "joins": False,
863        "pivots": False,
864        "sample": False,
865    }
arg_types = {'this': True, 'alias': False, 'joins': False, 'pivots': False, 'sample': False}
key: ClassVar[str] = 'tablefromrows'
required_args: 't.ClassVar[set[str]]' = {'this'}
class MatchRecognizeMeasure(sqlglot.expressions.core.Expression):
868class MatchRecognizeMeasure(Expression):
869    arg_types = {
870        "this": True,
871        "window_frame": False,
872    }
arg_types = {'this': True, 'window_frame': False}
key: ClassVar[str] = 'matchrecognizemeasure'
required_args: 't.ClassVar[set[str]]' = {'this'}
class MatchRecognize(sqlglot.expressions.core.Expression):
875class MatchRecognize(Expression):
876    arg_types = {
877        "this": True,
878        "partition_by": False,
879        "order": False,
880        "measures": False,
881        "rows": False,
882        "after": False,
883        "pattern": False,
884        "subset": False,
885        "define": False,
886        "alias": False,
887        "sample": False,
888        "joins": False,
889    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'subset': False, 'define': False, 'alias': False, 'sample': False, 'joins': False}
key: ClassVar[str] = 'matchrecognize'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Final(sqlglot.expressions.core.Expression):
892class Final(Expression):
893    pass
key: ClassVar[str] = 'final'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Offset(sqlglot.expressions.core.Expression):
896class Offset(Expression):
897    arg_types = {"this": False, "expression": True, "expressions": False}
arg_types = {'this': False, 'expression': True, 'expressions': False}
key: ClassVar[str] = 'offset'
required_args: 't.ClassVar[set[str]]' = {'expression'}
class Order(sqlglot.expressions.core.Expression):
900class Order(Expression):
901    arg_types = {"this": False, "expressions": True, "siblings": False}
arg_types = {'this': False, 'expressions': True, 'siblings': False}
key: ClassVar[str] = 'order'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class WithFill(sqlglot.expressions.core.Expression):
904class WithFill(Expression):
905    arg_types = {
906        "from_": False,
907        "to": False,
908        "step": False,
909        "interpolate": False,
910    }
arg_types = {'from_': False, 'to': False, 'step': False, 'interpolate': False}
key: ClassVar[str] = 'withfill'
required_args: 't.ClassVar[set[str]]' = set()
class SkipJSONColumn(sqlglot.expressions.core.Expression):
913class SkipJSONColumn(Expression):
914    arg_types = {"regexp": False, "expression": True}
arg_types = {'regexp': False, 'expression': True}
key: ClassVar[str] = 'skipjsoncolumn'
required_args: 't.ClassVar[set[str]]' = {'expression'}
class Cluster(sqlglot.expressions.core.Expression):
917class Cluster(Expression):
918    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'cluster'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Distribute(Order):
921class Distribute(Order):
922    pass
key: ClassVar[str] = 'distribute'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Sort(Order):
925class Sort(Order):
926    pass
key: ClassVar[str] = 'sort'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Qualify(sqlglot.expressions.core.Expression):
929class Qualify(Expression):
930    pass
key: ClassVar[str] = 'qualify'
required_args: 't.ClassVar[set[str]]' = {'this'}
class InputOutputFormat(sqlglot.expressions.core.Expression):
933class InputOutputFormat(Expression):
934    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key: ClassVar[str] = 'inputoutputformat'
required_args: 't.ClassVar[set[str]]' = set()
class Return(sqlglot.expressions.core.Expression):
937class Return(Expression):
938    pass
key: ClassVar[str] = 'return'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Tuple(sqlglot.expressions.core.Expression):
941class Tuple(Expression):
942    arg_types = {"expressions": False}
943
944    def isin(
945        self,
946        *expressions: t.Any,
947        query: ExpOrStr | None = None,
948        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
949        copy: bool = True,
950        **opts: Unpack[ParserArgs],
951    ) -> In:
952        return In(
953            this=maybe_copy(self, copy),
954            expressions=[convert(e, copy=copy) for e in expressions],
955            query=maybe_parse(query, copy=copy, **opts) if query else None,
956            unnest=(
957                Unnest(
958                    expressions=[
959                        maybe_parse(e, copy=copy, **opts)
960                        for e in t.cast(list[ExpOrStr], ensure_list(unnest))
961                    ]
962                )
963                if unnest
964                else None
965            ),
966        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[int, str, sqlglot.expressions.core.Expr, NoneType] = None, unnest: Union[int, str, sqlglot.expressions.core.Expr, NoneType, list[Union[int, str, sqlglot.expressions.core.Expr]], tuple[Union[int, str, sqlglot.expressions.core.Expr], ...]] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserArgs]) -> sqlglot.expressions.core.In:
944    def isin(
945        self,
946        *expressions: t.Any,
947        query: ExpOrStr | None = None,
948        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
949        copy: bool = True,
950        **opts: Unpack[ParserArgs],
951    ) -> In:
952        return In(
953            this=maybe_copy(self, copy),
954            expressions=[convert(e, copy=copy) for e in expressions],
955            query=maybe_parse(query, copy=copy, **opts) if query else None,
956            unnest=(
957                Unnest(
958                    expressions=[
959                        maybe_parse(e, copy=copy, **opts)
960                        for e in t.cast(list[ExpOrStr], ensure_list(unnest))
961                    ]
962                )
963                if unnest
964                else None
965            ),
966        )
key: ClassVar[str] = 'tuple'
required_args: 't.ClassVar[set[str]]' = set()
class QueryOption(sqlglot.expressions.core.Expression):
969class QueryOption(Expression):
970    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key: ClassVar[str] = 'queryoption'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ForClause(sqlglot.expressions.core.Expression):
974class ForClause(Expression):
975    arg_types = {"kind": True, "expressions": False}
arg_types = {'kind': True, 'expressions': False}
key: ClassVar[str] = 'forclause'
required_args: 't.ClassVar[set[str]]' = {'kind'}
class WithTableHint(sqlglot.expressions.core.Expression):
978class WithTableHint(Expression):
979    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'withtablehint'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class IndexTableHint(sqlglot.expressions.core.Expression):
982class IndexTableHint(Expression):
983    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key: ClassVar[str] = 'indextablehint'
required_args: 't.ClassVar[set[str]]' = {'this'}
class HistoricalData(sqlglot.expressions.core.Expression):
986class HistoricalData(Expression):
987    arg_types = {"this": True, "kind": True, "expression": True}
arg_types = {'this': True, 'kind': True, 'expression': True}
key: ClassVar[str] = 'historicaldata'
required_args: 't.ClassVar[set[str]]' = {'kind', 'expression', 'this'}
class Put(sqlglot.expressions.core.Expression):
990class Put(Expression):
991    arg_types = {"this": True, "target": True, "properties": False}
arg_types = {'this': True, 'target': True, 'properties': False}
key: ClassVar[str] = 'put'
required_args: 't.ClassVar[set[str]]' = {'target', 'this'}
class Get(sqlglot.expressions.core.Expression):
994class Get(Expression):
995    arg_types = {"this": True, "target": True, "properties": False}
arg_types = {'this': True, 'target': True, 'properties': False}
key: ClassVar[str] = 'get'
required_args: 't.ClassVar[set[str]]' = {'target', 'this'}
class ListStage(sqlglot.expressions.core.Expression):
 998class ListStage(Expression):
 999    """Lists files in a Snowflake stage or Git repository clone."""
1000
1001    arg_types = {"this": True, "pattern": False}

Lists files in a Snowflake stage or Git repository clone.

arg_types = {'this': True, 'pattern': False}
key: ClassVar[str] = 'liststage'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Table(sqlglot.expressions.core.Expression, Selectable):
1004class Table(Expression, Selectable):
1005    arg_types = {
1006        "this": False,
1007        "alias": False,
1008        "db": False,
1009        "catalog": False,
1010        "laterals": False,
1011        "joins": False,
1012        "pivots": False,
1013        "hints": False,
1014        "system_time": False,
1015        "version": False,
1016        "format": False,
1017        "pattern": False,
1018        "ordinality": False,
1019        "when": False,
1020        "only": False,
1021        "partition": False,
1022        "changes": False,
1023        "rows_from": False,
1024        "sample": False,
1025        "indexed": False,
1026    }
1027
1028    @property
1029    def name(self) -> str:
1030        this = self.this
1031        if not this or (isinstance(this, Func) and not isinstance(this, DynamicIdentifier)):
1032            return ""
1033        return this.name
1034
1035    @property
1036    def db(self) -> str:
1037        return self.text("db")
1038
1039    @property
1040    def catalog(self) -> str:
1041        return self.text("catalog")
1042
1043    @property
1044    def selects(self) -> list[Expr]:
1045        return []
1046
1047    @property
1048    def named_selects(self) -> list[str]:
1049        return []
1050
1051    @property
1052    def parts(self) -> list[Expr]:
1053        """Return the parts of a table in order catalog, db, table."""
1054        parts: list[Expr] = []
1055
1056        for arg in ("catalog", "db", "this"):
1057            part = self.args.get(arg)
1058
1059            if isinstance(part, Dot):
1060                parts.extend(part.flatten())
1061            elif isinstance(part, Expr):
1062                parts.append(part)
1063
1064        return parts
1065
1066    def to_column(self, copy: bool = True) -> Expr:
1067        parts = self.parts
1068        last_part = parts[-1]
1069
1070        if isinstance(last_part, Identifier):
1071            col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy)  # type: ignore
1072        else:
1073            # This branch will be reached if a function or array is wrapped in a `Table`
1074            col = last_part
1075
1076        alias = self.args.get("alias")
1077        if alias:
1078            col = alias_(col, alias.this, copy=copy)
1079
1080        return col
arg_types = {'this': False, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False, 'version': False, 'format': False, 'pattern': False, 'ordinality': False, 'when': False, 'only': False, 'partition': False, 'changes': False, 'rows_from': False, 'sample': False, 'indexed': False}
name: str
1028    @property
1029    def name(self) -> str:
1030        this = self.this
1031        if not this or (isinstance(this, Func) and not isinstance(this, DynamicIdentifier)):
1032            return ""
1033        return this.name
db: str
1035    @property
1036    def db(self) -> str:
1037        return self.text("db")
catalog: str
1039    @property
1040    def catalog(self) -> str:
1041        return self.text("catalog")
selects: list[sqlglot.expressions.core.Expr]
1043    @property
1044    def selects(self) -> list[Expr]:
1045        return []
named_selects: list[str]
1047    @property
1048    def named_selects(self) -> list[str]:
1049        return []
parts: list[sqlglot.expressions.core.Expr]
1051    @property
1052    def parts(self) -> list[Expr]:
1053        """Return the parts of a table in order catalog, db, table."""
1054        parts: list[Expr] = []
1055
1056        for arg in ("catalog", "db", "this"):
1057            part = self.args.get(arg)
1058
1059            if isinstance(part, Dot):
1060                parts.extend(part.flatten())
1061            elif isinstance(part, Expr):
1062                parts.append(part)
1063
1064        return parts

Return the parts of a table in order catalog, db, table.

def to_column(self, copy: bool = True) -> sqlglot.expressions.core.Expr:
1066    def to_column(self, copy: bool = True) -> Expr:
1067        parts = self.parts
1068        last_part = parts[-1]
1069
1070        if isinstance(last_part, Identifier):
1071            col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy)  # type: ignore
1072        else:
1073            # This branch will be reached if a function or array is wrapped in a `Table`
1074            col = last_part
1075
1076        alias = self.args.get("alias")
1077        if alias:
1078            col = alias_(col, alias.this, copy=copy)
1079
1080        return col
key: ClassVar[str] = 'table'
required_args: 't.ClassVar[set[str]]' = set()
class SetOperation(sqlglot.expressions.core.Expression, Query):
1097class SetOperation(Expression, Query):
1098    arg_types = {
1099        "with_": False,
1100        "this": True,
1101        "expression": True,
1102        "distinct": False,
1103        "by_name": False,
1104        "side": False,
1105        "kind": False,
1106        "on": False,
1107        **QUERY_MODIFIERS,
1108    }
1109
1110    def select(
1111        self: S,
1112        *expressions: ExpOrStr | None,
1113        append: bool = True,
1114        dialect: DialectType = None,
1115        copy: bool = True,
1116        **opts: Unpack[ParserNoDialectArgs],
1117    ) -> S:
1118        this = maybe_copy(self, copy)
1119        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1120        this.expression.unnest().select(
1121            *expressions, append=append, dialect=dialect, copy=False, **opts
1122        )
1123        return this
1124
1125    @property
1126    def named_selects(self) -> list[str]:
1127        names = []
1128        stack: list[Expr] = [self]
1129        by_name = False
1130
1131        while stack:
1132            expr = stack.pop()
1133            if not isinstance(expr, SetOperation):
1134                names.extend(t.cast(Selectable, expr).named_selects)
1135                continue
1136
1137            while isinstance(expr, SetOperation):
1138                if expr.args.get("by_name"):
1139                    by_name = True
1140                    stack.append(expr.expression.unnest())
1141                    stack.append(expr.this.unnest())
1142                    break
1143                expr = expr.this.unnest()
1144            else:
1145                names.extend(_named_selects(expr))
1146
1147        return list(dict.fromkeys(names)) if by_name else names
1148
1149    @property
1150    def is_star(self) -> bool:
1151        return _is_star(self)
1152
1153    @property
1154    def selects(self) -> list[Expr]:
1155        expr: Expr = self
1156        while isinstance(expr, SetOperation):
1157            expr = expr.this.unnest()
1158        return getattr(expr, "selects", [])
1159
1160    @property
1161    def left(self) -> Query:
1162        return self.this
1163
1164    @property
1165    def right(self) -> Query:
1166        return self.expression
1167
1168    @property
1169    def kind(self) -> str:
1170        return self.text("kind").upper()
1171
1172    @property
1173    def side(self) -> str:
1174        return self.text("side").upper()
arg_types = {'with_': False, 'this': True, 'expression': True, 'distinct': False, 'by_name': False, 'side': False, 'kind': False, 'on': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'prewhere': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False, 'options': False, 'for_': False}
def select( self: ~S, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> ~S:
1110    def select(
1111        self: S,
1112        *expressions: ExpOrStr | None,
1113        append: bool = True,
1114        dialect: DialectType = None,
1115        copy: bool = True,
1116        **opts: Unpack[ParserNoDialectArgs],
1117    ) -> S:
1118        this = maybe_copy(self, copy)
1119        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1120        this.expression.unnest().select(
1121            *expressions, append=append, dialect=dialect, copy=False, **opts
1122        )
1123        return this
named_selects: list[str]
1125    @property
1126    def named_selects(self) -> list[str]:
1127        names = []
1128        stack: list[Expr] = [self]
1129        by_name = False
1130
1131        while stack:
1132            expr = stack.pop()
1133            if not isinstance(expr, SetOperation):
1134                names.extend(t.cast(Selectable, expr).named_selects)
1135                continue
1136
1137            while isinstance(expr, SetOperation):
1138                if expr.args.get("by_name"):
1139                    by_name = True
1140                    stack.append(expr.expression.unnest())
1141                    stack.append(expr.this.unnest())
1142                    break
1143                expr = expr.this.unnest()
1144            else:
1145                names.extend(_named_selects(expr))
1146
1147        return list(dict.fromkeys(names)) if by_name else names
is_star: bool
1149    @property
1150    def is_star(self) -> bool:
1151        return _is_star(self)

Checks whether an expression is a star.

selects: list[sqlglot.expressions.core.Expr]
1153    @property
1154    def selects(self) -> list[Expr]:
1155        expr: Expr = self
1156        while isinstance(expr, SetOperation):
1157            expr = expr.this.unnest()
1158        return getattr(expr, "selects", [])
left: Query
1160    @property
1161    def left(self) -> Query:
1162        return self.this
right: Query
1164    @property
1165    def right(self) -> Query:
1166        return self.expression
kind: str
1168    @property
1169    def kind(self) -> str:
1170        return self.text("kind").upper()
side: str
1172    @property
1173    def side(self) -> str:
1174        return self.text("side").upper()
key: ClassVar[str] = 'setoperation'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Union(SetOperation):
1177class Union(SetOperation):
1178    pass
key: ClassVar[str] = 'union'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Except(SetOperation):
1181class Except(SetOperation):
1182    pass
key: ClassVar[str] = 'except'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Intersect(SetOperation):
1185class Intersect(SetOperation):
1186    pass
key: ClassVar[str] = 'intersect'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Values(sqlglot.expressions.core.Expression, UDTF):
1189class Values(Expression, UDTF):
1190    arg_types = {
1191        "expressions": True,
1192        "alias": False,
1193        "order": False,
1194        "limit": False,
1195        "offset": False,
1196        "pivots": False,
1197    }
arg_types = {'expressions': True, 'alias': False, 'order': False, 'limit': False, 'offset': False, 'pivots': False}
key: ClassVar[str] = 'values'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Version(sqlglot.expressions.core.Expression):
1200class Version(Expression):
1201    """
1202    Time travel, iceberg, bigquery etc
1203    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
1204    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
1205    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
1206    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
1207    this is either TIMESTAMP or VERSION
1208    kind is ("AS OF", "BETWEEN")
1209    """
1210
1211    arg_types = {"this": True, "kind": True, "expression": False}
arg_types = {'this': True, 'kind': True, 'expression': False}
key: ClassVar[str] = 'version'
required_args: 't.ClassVar[set[str]]' = {'kind', 'this'}
class Schema(sqlglot.expressions.core.Expression):
1214class Schema(Expression):
1215    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key: ClassVar[str] = 'schema'
required_args: 't.ClassVar[set[str]]' = set()
class Lock(sqlglot.expressions.core.Expression):
1218class Lock(Expression):
1219    arg_types = {"update": True, "expressions": False, "wait": False, "key": False}
arg_types = {'update': True, 'expressions': False, 'wait': False, 'key': False}
key: ClassVar[str] = 'lock'
required_args: 't.ClassVar[set[str]]' = {'update'}
class Select(sqlglot.expressions.core.Expression, Query):
1222class Select(Expression, Query):
1223    arg_types = {
1224        "with_": False,
1225        "kind": False,
1226        "expressions": False,
1227        "hint": False,
1228        "distinct": False,
1229        "into": False,
1230        "from_": False,
1231        "operation_modifiers": False,
1232        "exclude": False,
1233        **QUERY_MODIFIERS,
1234    }
1235
1236    def from_(
1237        self,
1238        expression: ExpOrStr,
1239        dialect: DialectType = None,
1240        copy: bool = True,
1241        **opts: Unpack[ParserNoDialectArgs],
1242    ) -> Select:
1243        """
1244        Set the FROM expression.
1245
1246        Example:
1247            >>> Select().from_("tbl").select("x").sql()
1248            'SELECT x FROM tbl'
1249
1250        Args:
1251            expression : the SQL code strings to parse.
1252                If a `From` instance is passed, this is used as-is.
1253                If another `Expr` instance is passed, it will be wrapped in a `From`.
1254            dialect: the dialect used to parse the input expression.
1255            copy: if `False`, modify this expression instance in-place.
1256            opts: other options to use to parse the input expressions.
1257
1258        Returns:
1259            The modified Select expression.
1260        """
1261        return _apply_builder(
1262            expression=expression,
1263            instance=self,
1264            arg="from_",
1265            into=From,
1266            prefix="FROM",
1267            dialect=dialect,
1268            copy=copy,
1269            **opts,
1270        )
1271
1272    def group_by(
1273        self,
1274        *expressions: ExpOrStr | None,
1275        append: bool = True,
1276        dialect: DialectType = None,
1277        copy: bool = True,
1278        **opts: Unpack[ParserNoDialectArgs],
1279    ) -> Select:
1280        """
1281        Set the GROUP BY expression.
1282
1283        Example:
1284            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
1285            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
1286
1287        Args:
1288            *expressions: the SQL code strings to parse.
1289                If a `Group` instance is passed, this is used as-is.
1290                If another `Expr` instance is passed, it will be wrapped in a `Group`.
1291                If nothing is passed in then a group by is not applied to the expression
1292            append: if `True`, add to any existing expressions.
1293                Otherwise, this flattens all the `Group` expression into a single expression.
1294            dialect: the dialect used to parse the input expression.
1295            copy: if `False`, modify this expression instance in-place.
1296            opts: other options to use to parse the input expressions.
1297
1298        Returns:
1299            The modified Select expression.
1300        """
1301        if not expressions:
1302            return self if not copy else self.copy()
1303
1304        return _apply_child_list_builder(
1305            *expressions,
1306            instance=self,
1307            arg="group",
1308            append=append,
1309            copy=copy,
1310            prefix="GROUP BY",
1311            into=Group,
1312            dialect=dialect,
1313            **opts,
1314        )
1315
1316    def sort_by(
1317        self,
1318        *expressions: ExpOrStr | None,
1319        append: bool = True,
1320        dialect: DialectType = None,
1321        copy: bool = True,
1322        **opts: Unpack[ParserNoDialectArgs],
1323    ) -> Select:
1324        """
1325        Set the SORT BY expression.
1326
1327        Example:
1328            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
1329            'SELECT x FROM tbl SORT BY x DESC'
1330
1331        Args:
1332            *expressions: the SQL code strings to parse.
1333                If a `Group` instance is passed, this is used as-is.
1334                If another `Expr` instance is passed, it will be wrapped in a `SORT`.
1335            append: if `True`, add to any existing expressions.
1336                Otherwise, this flattens all the `Order` expression into a single expression.
1337            dialect: the dialect used to parse the input expression.
1338            copy: if `False`, modify this expression instance in-place.
1339            opts: other options to use to parse the input expressions.
1340
1341        Returns:
1342            The modified Select expression.
1343        """
1344        return _apply_child_list_builder(
1345            *expressions,
1346            instance=self,
1347            arg="sort",
1348            append=append,
1349            copy=copy,
1350            prefix="SORT BY",
1351            into=Sort,
1352            dialect=dialect,
1353            **opts,
1354        )
1355
1356    def cluster_by(
1357        self,
1358        *expressions: ExpOrStr | None,
1359        append: bool = True,
1360        dialect: DialectType = None,
1361        copy: bool = True,
1362        **opts: Unpack[ParserNoDialectArgs],
1363    ) -> Select:
1364        """
1365        Set the CLUSTER BY expression.
1366
1367        Example:
1368            >>> Select().from_("tbl").select("x").cluster_by("x").sql(dialect="hive")
1369            'SELECT x FROM tbl CLUSTER BY x'
1370
1371        Args:
1372            *expressions: the SQL code strings to parse.
1373                If a `Group` instance is passed, this is used as-is.
1374                If another `Expr` instance is passed, it will be wrapped in a `Cluster`.
1375            append: if `True`, add to any existing expressions.
1376                Otherwise, this flattens all the `Order` expression into a single expression.
1377            dialect: the dialect used to parse the input expression.
1378            copy: if `False`, modify this expression instance in-place.
1379            opts: other options to use to parse the input expressions.
1380
1381        Returns:
1382            The modified Select expression.
1383        """
1384        return _apply_child_list_builder(
1385            *expressions,
1386            instance=self,
1387            arg="cluster",
1388            append=append,
1389            copy=copy,
1390            prefix="CLUSTER BY",
1391            into=Cluster,
1392            dialect=dialect,
1393            **opts,
1394        )
1395
1396    def select(
1397        self,
1398        *expressions: ExpOrStr | None,
1399        append: bool = True,
1400        dialect: DialectType = None,
1401        copy: bool = True,
1402        **opts: Unpack[ParserNoDialectArgs],
1403    ) -> Select:
1404        return _apply_list_builder(
1405            *expressions,
1406            instance=self,
1407            arg="expressions",
1408            append=append,
1409            dialect=dialect,
1410            into=Expr,
1411            copy=copy,
1412            **opts,
1413        )
1414
1415    def lateral(
1416        self,
1417        *expressions: ExpOrStr | None,
1418        append: bool = True,
1419        dialect: DialectType = None,
1420        copy: bool = True,
1421        **opts: Unpack[ParserNoDialectArgs],
1422    ) -> Select:
1423        """
1424        Append to or set the LATERAL expressions.
1425
1426        Example:
1427            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
1428            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
1429
1430        Args:
1431            *expressions: the SQL code strings to parse.
1432                If an `Expr` instance is passed, it will be used as-is.
1433            append: if `True`, add to any existing expressions.
1434                Otherwise, this resets the expressions.
1435            dialect: the dialect used to parse the input expressions.
1436            copy: if `False`, modify this expression instance in-place.
1437            opts: other options to use to parse the input expressions.
1438
1439        Returns:
1440            The modified Select expression.
1441        """
1442        return _apply_list_builder(
1443            *expressions,
1444            instance=self,
1445            arg="laterals",
1446            append=append,
1447            into=Lateral,
1448            prefix="LATERAL VIEW",
1449            dialect=dialect,
1450            copy=copy,
1451            **opts,
1452        )
1453
1454    def join(
1455        self,
1456        expression: ExpOrStr,
1457        on: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1458        using: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1459        append: bool = True,
1460        join_type: str | None = None,
1461        join_alias: Identifier | str | None = None,
1462        dialect: DialectType = None,
1463        copy: bool = True,
1464        **opts: Unpack[ParserNoDialectArgs],
1465    ) -> Select:
1466        """
1467        Append to or set the JOIN expressions.
1468
1469        Example:
1470            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
1471            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
1472
1473            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
1474            'SELECT 1 FROM a JOIN b USING (x, y, z)'
1475
1476            Use `join_type` to change the type of join:
1477
1478            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
1479            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
1480
1481        Args:
1482            expression: the SQL code string to parse.
1483                If an `Expr` instance is passed, it will be used as-is.
1484            on: optionally specify the join "on" criteria as a SQL string.
1485                If an `Expr` instance is passed, it will be used as-is.
1486            using: optionally specify the join "using" criteria as a SQL string.
1487                If an `Expr` instance is passed, it will be used as-is.
1488            append: if `True`, add to any existing expressions.
1489                Otherwise, this resets the expressions.
1490            join_type: if set, alter the parsed join type.
1491            join_alias: an optional alias for the joined source.
1492            dialect: the dialect used to parse the input expressions.
1493            copy: if `False`, modify this expression instance in-place.
1494            opts: other options to use to parse the input expressions.
1495
1496        Returns:
1497            Select: the modified expression.
1498        """
1499        parse_args: ParserArgs = {"dialect": dialect, **opts}
1500        try:
1501            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
1502        except ParseError:
1503            expression = maybe_parse(expression, into=(Join, Expr), **parse_args)
1504
1505        join = expression if isinstance(expression, Join) else Join(this=expression, kind="CROSS")
1506
1507        if join.kind == "CROSS" and (on or using or join_type):
1508            join.set("kind", None)
1509
1510        if isinstance(join.this, Select):
1511            join.this.replace(join.this.subquery())
1512
1513        if join_type:
1514            new_join: Join = maybe_parse(f"FROM _ {join_type} JOIN _", **parse_args).find(Join)
1515            method = new_join.method
1516            side = new_join.side
1517            kind = new_join.kind
1518
1519            if method:
1520                join.set("method", method)
1521            if side:
1522                join.set("side", side)
1523            if kind:
1524                join.set("kind", kind)
1525
1526        if on:
1527            on_exprs: list[ExpOrStr] = ensure_list(on)
1528            on = and_(*on_exprs, dialect=dialect, copy=copy, **opts)
1529            join.set("on", on)
1530
1531        if using:
1532            using_exprs: list[ExpOrStr] = ensure_list(using)
1533            join = _apply_list_builder(
1534                *using_exprs,
1535                instance=join,
1536                arg="using",
1537                append=append,
1538                copy=copy,
1539                into=Identifier,
1540                **opts,
1541            )
1542
1543        if join_alias:
1544            join.set("this", alias_(join.this, join_alias, table=True))
1545
1546        return _apply_list_builder(
1547            join,
1548            instance=self,
1549            arg="joins",
1550            append=append,
1551            copy=copy,
1552            **opts,
1553        )
1554
1555    def having(
1556        self,
1557        *expressions: ExpOrStr | None,
1558        append: bool = True,
1559        dialect: DialectType = None,
1560        copy: bool = True,
1561        **opts: Unpack[ParserNoDialectArgs],
1562    ) -> Select:
1563        """
1564        Append to or set the HAVING expressions.
1565
1566        Example:
1567            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
1568            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
1569
1570        Args:
1571            *expressions: the SQL code strings to parse.
1572                If an `Expr` instance is passed, it will be used as-is.
1573                Multiple expressions are combined with an AND operator.
1574            append: if `True`, AND the new expressions to any existing expression.
1575                Otherwise, this resets the expression.
1576            dialect: the dialect used to parse the input expressions.
1577            copy: if `False`, modify this expression instance in-place.
1578            opts: other options to use to parse the input expressions.
1579
1580        Returns:
1581            The modified Select expression.
1582        """
1583        return _apply_conjunction_builder(
1584            *expressions,
1585            instance=self,
1586            arg="having",
1587            append=append,
1588            into=Having,
1589            dialect=dialect,
1590            copy=copy,
1591            **opts,
1592        )
1593
1594    def window(
1595        self,
1596        *expressions: ExpOrStr | None,
1597        append: bool = True,
1598        dialect: DialectType = None,
1599        copy: bool = True,
1600        **opts: Unpack[ParserNoDialectArgs],
1601    ) -> Select:
1602        return _apply_list_builder(
1603            *expressions,
1604            instance=self,
1605            arg="windows",
1606            append=append,
1607            into=Window,
1608            dialect=dialect,
1609            copy=copy,
1610            **opts,
1611        )
1612
1613    def qualify(
1614        self,
1615        *expressions: ExpOrStr | None,
1616        append: bool = True,
1617        dialect: DialectType = None,
1618        copy: bool = True,
1619        **opts: Unpack[ParserNoDialectArgs],
1620    ) -> Select:
1621        return _apply_conjunction_builder(
1622            *expressions,
1623            instance=self,
1624            arg="qualify",
1625            append=append,
1626            into=Qualify,
1627            dialect=dialect,
1628            copy=copy,
1629            **opts,
1630        )
1631
1632    def distinct(self, *ons: ExpOrStr | None, distinct: bool = True, copy: bool = True) -> Select:
1633        """
1634        Set the OFFSET expression.
1635
1636        Example:
1637            >>> Select().from_("tbl").select("x").distinct().sql()
1638            'SELECT DISTINCT x FROM tbl'
1639
1640        Args:
1641            ons: the expressions to distinct on
1642            distinct: whether the Select should be distinct
1643            copy: if `False`, modify this expression instance in-place.
1644
1645        Returns:
1646            Select: the modified expression.
1647        """
1648        instance = maybe_copy(self, copy)
1649        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
1650        instance.set("distinct", Distinct(on=on) if distinct else None)
1651        return instance
1652
1653    def ctas(
1654        self,
1655        table: ExpOrStr,
1656        properties: dict | None = None,
1657        dialect: DialectType = None,
1658        copy: bool = True,
1659        **opts: Unpack[ParserNoDialectArgs],
1660    ) -> Create:
1661        """
1662        Convert this expression to a CREATE TABLE AS statement.
1663
1664        Example:
1665            >>> Select().select("*").from_("tbl").ctas("x").sql()
1666            'CREATE TABLE x AS SELECT * FROM tbl'
1667
1668        Args:
1669            table: the SQL code string to parse as the table name.
1670                If another `Expr` instance is passed, it will be used as-is.
1671            properties: an optional mapping of table properties
1672            dialect: the dialect used to parse the input table.
1673            copy: if `False`, modify this expression instance in-place.
1674            opts: other options to use to parse the input table.
1675
1676        Returns:
1677            The new Create expression.
1678        """
1679        instance = maybe_copy(self, copy)
1680        table_expression = maybe_parse(table, into=Table, dialect=dialect, **opts)
1681
1682        properties_expression = None
1683        if properties:
1684            from sqlglot.expressions.properties import Properties as _Properties
1685
1686            properties_expression = _Properties.from_dict(properties)
1687
1688        from sqlglot.expressions.ddl import Create as _Create
1689
1690        return _Create(
1691            this=table_expression,
1692            kind="TABLE",
1693            expression=instance,
1694            properties=properties_expression,
1695        )
1696
1697    def lock(self, update: bool = True, copy: bool = True) -> Select:
1698        """
1699        Set the locking read mode for this expression.
1700
1701        Examples:
1702            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
1703            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
1704
1705            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
1706            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
1707
1708        Args:
1709            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
1710            copy: if `False`, modify this expression instance in-place.
1711
1712        Returns:
1713            The modified expression.
1714        """
1715        inst = maybe_copy(self, copy)
1716        inst.set("locks", [Lock(update=update)])
1717
1718        return inst
1719
1720    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
1721        """
1722        Set hints for this expression.
1723
1724        Examples:
1725            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
1726            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
1727
1728        Args:
1729            hints: The SQL code strings to parse as the hints.
1730                If an `Expr` instance is passed, it will be used as-is.
1731            dialect: The dialect used to parse the hints.
1732            copy: If `False`, modify this expression instance in-place.
1733
1734        Returns:
1735            The modified expression.
1736        """
1737        inst = maybe_copy(self, copy)
1738        inst.set(
1739            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
1740        )
1741
1742        return inst
1743
1744    @property
1745    def named_selects(self) -> list[str]:
1746        selects = []
1747
1748        for e in self.expressions:
1749            if e.alias_or_name:
1750                selects.append(e.output_name)
1751            elif isinstance(e, Aliases):
1752                selects.extend([a.name for a in e.aliases])
1753        return selects
1754
1755    @property
1756    def is_star(self) -> bool:
1757        return any(expression.is_star for expression in self.expressions)
1758
1759    @property
1760    def selects(self) -> list[Expr]:
1761        return self.expressions
arg_types = {'with_': False, 'kind': False, 'expressions': False, 'hint': False, 'distinct': False, 'into': False, 'from_': False, 'operation_modifiers': False, 'exclude': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'prewhere': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False, 'options': False, 'for_': False}
def from_( self, expression: Union[int, str, sqlglot.expressions.core.Expr], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1236    def from_(
1237        self,
1238        expression: ExpOrStr,
1239        dialect: DialectType = None,
1240        copy: bool = True,
1241        **opts: Unpack[ParserNoDialectArgs],
1242    ) -> Select:
1243        """
1244        Set the FROM expression.
1245
1246        Example:
1247            >>> Select().from_("tbl").select("x").sql()
1248            'SELECT x FROM tbl'
1249
1250        Args:
1251            expression : the SQL code strings to parse.
1252                If a `From` instance is passed, this is used as-is.
1253                If another `Expr` instance is passed, it will be wrapped in a `From`.
1254            dialect: the dialect used to parse the input expression.
1255            copy: if `False`, modify this expression instance in-place.
1256            opts: other options to use to parse the input expressions.
1257
1258        Returns:
1259            The modified Select expression.
1260        """
1261        return _apply_builder(
1262            expression=expression,
1263            instance=self,
1264            arg="from_",
1265            into=From,
1266            prefix="FROM",
1267            dialect=dialect,
1268            copy=copy,
1269            **opts,
1270        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expr instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1272    def group_by(
1273        self,
1274        *expressions: ExpOrStr | None,
1275        append: bool = True,
1276        dialect: DialectType = None,
1277        copy: bool = True,
1278        **opts: Unpack[ParserNoDialectArgs],
1279    ) -> Select:
1280        """
1281        Set the GROUP BY expression.
1282
1283        Example:
1284            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
1285            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
1286
1287        Args:
1288            *expressions: the SQL code strings to parse.
1289                If a `Group` instance is passed, this is used as-is.
1290                If another `Expr` instance is passed, it will be wrapped in a `Group`.
1291                If nothing is passed in then a group by is not applied to the expression
1292            append: if `True`, add to any existing expressions.
1293                Otherwise, this flattens all the `Group` expression into a single expression.
1294            dialect: the dialect used to parse the input expression.
1295            copy: if `False`, modify this expression instance in-place.
1296            opts: other options to use to parse the input expressions.
1297
1298        Returns:
1299            The modified Select expression.
1300        """
1301        if not expressions:
1302            return self if not copy else self.copy()
1303
1304        return _apply_child_list_builder(
1305            *expressions,
1306            instance=self,
1307            arg="group",
1308            append=append,
1309            copy=copy,
1310            prefix="GROUP BY",
1311            into=Group,
1312            dialect=dialect,
1313            **opts,
1314        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expr instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1316    def sort_by(
1317        self,
1318        *expressions: ExpOrStr | None,
1319        append: bool = True,
1320        dialect: DialectType = None,
1321        copy: bool = True,
1322        **opts: Unpack[ParserNoDialectArgs],
1323    ) -> Select:
1324        """
1325        Set the SORT BY expression.
1326
1327        Example:
1328            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
1329            'SELECT x FROM tbl SORT BY x DESC'
1330
1331        Args:
1332            *expressions: the SQL code strings to parse.
1333                If a `Group` instance is passed, this is used as-is.
1334                If another `Expr` instance is passed, it will be wrapped in a `SORT`.
1335            append: if `True`, add to any existing expressions.
1336                Otherwise, this flattens all the `Order` expression into a single expression.
1337            dialect: the dialect used to parse the input expression.
1338            copy: if `False`, modify this expression instance in-place.
1339            opts: other options to use to parse the input expressions.
1340
1341        Returns:
1342            The modified Select expression.
1343        """
1344        return _apply_child_list_builder(
1345            *expressions,
1346            instance=self,
1347            arg="sort",
1348            append=append,
1349            copy=copy,
1350            prefix="SORT BY",
1351            into=Sort,
1352            dialect=dialect,
1353            **opts,
1354        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expr instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1356    def cluster_by(
1357        self,
1358        *expressions: ExpOrStr | None,
1359        append: bool = True,
1360        dialect: DialectType = None,
1361        copy: bool = True,
1362        **opts: Unpack[ParserNoDialectArgs],
1363    ) -> Select:
1364        """
1365        Set the CLUSTER BY expression.
1366
1367        Example:
1368            >>> Select().from_("tbl").select("x").cluster_by("x").sql(dialect="hive")
1369            'SELECT x FROM tbl CLUSTER BY x'
1370
1371        Args:
1372            *expressions: the SQL code strings to parse.
1373                If a `Group` instance is passed, this is used as-is.
1374                If another `Expr` instance is passed, it will be wrapped in a `Cluster`.
1375            append: if `True`, add to any existing expressions.
1376                Otherwise, this flattens all the `Order` expression into a single expression.
1377            dialect: the dialect used to parse the input expression.
1378            copy: if `False`, modify this expression instance in-place.
1379            opts: other options to use to parse the input expressions.
1380
1381        Returns:
1382            The modified Select expression.
1383        """
1384        return _apply_child_list_builder(
1385            *expressions,
1386            instance=self,
1387            arg="cluster",
1388            append=append,
1389            copy=copy,
1390            prefix="CLUSTER BY",
1391            into=Cluster,
1392            dialect=dialect,
1393            **opts,
1394        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expr instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1396    def select(
1397        self,
1398        *expressions: ExpOrStr | None,
1399        append: bool = True,
1400        dialect: DialectType = None,
1401        copy: bool = True,
1402        **opts: Unpack[ParserNoDialectArgs],
1403    ) -> Select:
1404        return _apply_list_builder(
1405            *expressions,
1406            instance=self,
1407            arg="expressions",
1408            append=append,
1409            dialect=dialect,
1410            into=Expr,
1411            copy=copy,
1412            **opts,
1413        )
def lateral( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1415    def lateral(
1416        self,
1417        *expressions: ExpOrStr | None,
1418        append: bool = True,
1419        dialect: DialectType = None,
1420        copy: bool = True,
1421        **opts: Unpack[ParserNoDialectArgs],
1422    ) -> Select:
1423        """
1424        Append to or set the LATERAL expressions.
1425
1426        Example:
1427            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
1428            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
1429
1430        Args:
1431            *expressions: the SQL code strings to parse.
1432                If an `Expr` instance is passed, it will be used as-is.
1433            append: if `True`, add to any existing expressions.
1434                Otherwise, this resets the expressions.
1435            dialect: the dialect used to parse the input expressions.
1436            copy: if `False`, modify this expression instance in-place.
1437            opts: other options to use to parse the input expressions.
1438
1439        Returns:
1440            The modified Select expression.
1441        """
1442        return _apply_list_builder(
1443            *expressions,
1444            instance=self,
1445            arg="laterals",
1446            append=append,
1447            into=Lateral,
1448            prefix="LATERAL VIEW",
1449            dialect=dialect,
1450            copy=copy,
1451            **opts,
1452        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[int, str, sqlglot.expressions.core.Expr], on: Union[int, str, sqlglot.expressions.core.Expr, list[Union[int, str, sqlglot.expressions.core.Expr]], tuple[Union[int, str, sqlglot.expressions.core.Expr], ...], NoneType] = None, using: Union[int, str, sqlglot.expressions.core.Expr, list[Union[int, str, sqlglot.expressions.core.Expr]], tuple[Union[int, str, sqlglot.expressions.core.Expr], ...], NoneType] = None, append: bool = True, join_type: str | None = None, join_alias: sqlglot.expressions.core.Identifier | str | None = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1454    def join(
1455        self,
1456        expression: ExpOrStr,
1457        on: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1458        using: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1459        append: bool = True,
1460        join_type: str | None = None,
1461        join_alias: Identifier | str | None = None,
1462        dialect: DialectType = None,
1463        copy: bool = True,
1464        **opts: Unpack[ParserNoDialectArgs],
1465    ) -> Select:
1466        """
1467        Append to or set the JOIN expressions.
1468
1469        Example:
1470            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
1471            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
1472
1473            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
1474            'SELECT 1 FROM a JOIN b USING (x, y, z)'
1475
1476            Use `join_type` to change the type of join:
1477
1478            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
1479            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
1480
1481        Args:
1482            expression: the SQL code string to parse.
1483                If an `Expr` instance is passed, it will be used as-is.
1484            on: optionally specify the join "on" criteria as a SQL string.
1485                If an `Expr` instance is passed, it will be used as-is.
1486            using: optionally specify the join "using" criteria as a SQL string.
1487                If an `Expr` instance is passed, it will be used as-is.
1488            append: if `True`, add to any existing expressions.
1489                Otherwise, this resets the expressions.
1490            join_type: if set, alter the parsed join type.
1491            join_alias: an optional alias for the joined source.
1492            dialect: the dialect used to parse the input expressions.
1493            copy: if `False`, modify this expression instance in-place.
1494            opts: other options to use to parse the input expressions.
1495
1496        Returns:
1497            Select: the modified expression.
1498        """
1499        parse_args: ParserArgs = {"dialect": dialect, **opts}
1500        try:
1501            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
1502        except ParseError:
1503            expression = maybe_parse(expression, into=(Join, Expr), **parse_args)
1504
1505        join = expression if isinstance(expression, Join) else Join(this=expression, kind="CROSS")
1506
1507        if join.kind == "CROSS" and (on or using or join_type):
1508            join.set("kind", None)
1509
1510        if isinstance(join.this, Select):
1511            join.this.replace(join.this.subquery())
1512
1513        if join_type:
1514            new_join: Join = maybe_parse(f"FROM _ {join_type} JOIN _", **parse_args).find(Join)
1515            method = new_join.method
1516            side = new_join.side
1517            kind = new_join.kind
1518
1519            if method:
1520                join.set("method", method)
1521            if side:
1522                join.set("side", side)
1523            if kind:
1524                join.set("kind", kind)
1525
1526        if on:
1527            on_exprs: list[ExpOrStr] = ensure_list(on)
1528            on = and_(*on_exprs, dialect=dialect, copy=copy, **opts)
1529            join.set("on", on)
1530
1531        if using:
1532            using_exprs: list[ExpOrStr] = ensure_list(using)
1533            join = _apply_list_builder(
1534                *using_exprs,
1535                instance=join,
1536                arg="using",
1537                append=append,
1538                copy=copy,
1539                into=Identifier,
1540                **opts,
1541            )
1542
1543        if join_alias:
1544            join.set("this", alias_(join.this, join_alias, table=True))
1545
1546        return _apply_list_builder(
1547            join,
1548            instance=self,
1549            arg="joins",
1550            append=append,
1551            copy=copy,
1552            **opts,
1553        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expr instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expr instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expr instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1555    def having(
1556        self,
1557        *expressions: ExpOrStr | None,
1558        append: bool = True,
1559        dialect: DialectType = None,
1560        copy: bool = True,
1561        **opts: Unpack[ParserNoDialectArgs],
1562    ) -> Select:
1563        """
1564        Append to or set the HAVING expressions.
1565
1566        Example:
1567            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
1568            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
1569
1570        Args:
1571            *expressions: the SQL code strings to parse.
1572                If an `Expr` instance is passed, it will be used as-is.
1573                Multiple expressions are combined with an AND operator.
1574            append: if `True`, AND the new expressions to any existing expression.
1575                Otherwise, this resets the expression.
1576            dialect: the dialect used to parse the input expressions.
1577            copy: if `False`, modify this expression instance in-place.
1578            opts: other options to use to parse the input expressions.
1579
1580        Returns:
1581            The modified Select expression.
1582        """
1583        return _apply_conjunction_builder(
1584            *expressions,
1585            instance=self,
1586            arg="having",
1587            append=append,
1588            into=Having,
1589            dialect=dialect,
1590            copy=copy,
1591            **opts,
1592        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1594    def window(
1595        self,
1596        *expressions: ExpOrStr | None,
1597        append: bool = True,
1598        dialect: DialectType = None,
1599        copy: bool = True,
1600        **opts: Unpack[ParserNoDialectArgs],
1601    ) -> Select:
1602        return _apply_list_builder(
1603            *expressions,
1604            instance=self,
1605            arg="windows",
1606            append=append,
1607            into=Window,
1608            dialect=dialect,
1609            copy=copy,
1610            **opts,
1611        )
def qualify( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Select:
1613    def qualify(
1614        self,
1615        *expressions: ExpOrStr | None,
1616        append: bool = True,
1617        dialect: DialectType = None,
1618        copy: bool = True,
1619        **opts: Unpack[ParserNoDialectArgs],
1620    ) -> Select:
1621        return _apply_conjunction_builder(
1622            *expressions,
1623            instance=self,
1624            arg="qualify",
1625            append=append,
1626            into=Qualify,
1627            dialect=dialect,
1628            copy=copy,
1629            **opts,
1630        )
def distinct( self, *ons: Union[int, str, sqlglot.expressions.core.Expr, NoneType], distinct: bool = True, copy: bool = True) -> Select:
1632    def distinct(self, *ons: ExpOrStr | None, distinct: bool = True, copy: bool = True) -> Select:
1633        """
1634        Set the OFFSET expression.
1635
1636        Example:
1637            >>> Select().from_("tbl").select("x").distinct().sql()
1638            'SELECT DISTINCT x FROM tbl'
1639
1640        Args:
1641            ons: the expressions to distinct on
1642            distinct: whether the Select should be distinct
1643            copy: if `False`, modify this expression instance in-place.
1644
1645        Returns:
1646            Select: the modified expression.
1647        """
1648        instance = maybe_copy(self, copy)
1649        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
1650        instance.set("distinct", Distinct(on=on) if distinct else None)
1651        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[int, str, sqlglot.expressions.core.Expr], properties: dict | None = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> sqlglot.expressions.ddl.Create:
1653    def ctas(
1654        self,
1655        table: ExpOrStr,
1656        properties: dict | None = None,
1657        dialect: DialectType = None,
1658        copy: bool = True,
1659        **opts: Unpack[ParserNoDialectArgs],
1660    ) -> Create:
1661        """
1662        Convert this expression to a CREATE TABLE AS statement.
1663
1664        Example:
1665            >>> Select().select("*").from_("tbl").ctas("x").sql()
1666            'CREATE TABLE x AS SELECT * FROM tbl'
1667
1668        Args:
1669            table: the SQL code string to parse as the table name.
1670                If another `Expr` instance is passed, it will be used as-is.
1671            properties: an optional mapping of table properties
1672            dialect: the dialect used to parse the input table.
1673            copy: if `False`, modify this expression instance in-place.
1674            opts: other options to use to parse the input table.
1675
1676        Returns:
1677            The new Create expression.
1678        """
1679        instance = maybe_copy(self, copy)
1680        table_expression = maybe_parse(table, into=Table, dialect=dialect, **opts)
1681
1682        properties_expression = None
1683        if properties:
1684            from sqlglot.expressions.properties import Properties as _Properties
1685
1686            properties_expression = _Properties.from_dict(properties)
1687
1688        from sqlglot.expressions.ddl import Create as _Create
1689
1690        return _Create(
1691            this=table_expression,
1692            kind="TABLE",
1693            expression=instance,
1694            properties=properties_expression,
1695        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expr instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> Select:
1697    def lock(self, update: bool = True, copy: bool = True) -> Select:
1698        """
1699        Set the locking read mode for this expression.
1700
1701        Examples:
1702            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
1703            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
1704
1705            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
1706            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
1707
1708        Args:
1709            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
1710            copy: if `False`, modify this expression instance in-place.
1711
1712        Returns:
1713            The modified expression.
1714        """
1715        inst = maybe_copy(self, copy)
1716        inst.set("locks", [Lock(update=update)])
1717
1718        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[int, str, sqlglot.expressions.core.Expr], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True) -> Select:
1720    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
1721        """
1722        Set hints for this expression.
1723
1724        Examples:
1725            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
1726            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
1727
1728        Args:
1729            hints: The SQL code strings to parse as the hints.
1730                If an `Expr` instance is passed, it will be used as-is.
1731            dialect: The dialect used to parse the hints.
1732            copy: If `False`, modify this expression instance in-place.
1733
1734        Returns:
1735            The modified expression.
1736        """
1737        inst = maybe_copy(self, copy)
1738        inst.set(
1739            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
1740        )
1741
1742        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expr instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: list[str]
1744    @property
1745    def named_selects(self) -> list[str]:
1746        selects = []
1747
1748        for e in self.expressions:
1749            if e.alias_or_name:
1750                selects.append(e.output_name)
1751            elif isinstance(e, Aliases):
1752                selects.extend([a.name for a in e.aliases])
1753        return selects
is_star: bool
1755    @property
1756    def is_star(self) -> bool:
1757        return any(expression.is_star for expression in self.expressions)

Checks whether an expression is a star.

selects: list[sqlglot.expressions.core.Expr]
1759    @property
1760    def selects(self) -> list[Expr]:
1761        return self.expressions
key: ClassVar[str] = 'select'
required_args: 't.ClassVar[set[str]]' = set()
class Subquery(sqlglot.expressions.core.Expression, DerivedTable, Query):
1764class Subquery(Expression, DerivedTable, Query):
1765    is_subquery: t.ClassVar[bool] = True
1766    arg_types = {
1767        "this": True,
1768        "alias": False,
1769        "with_": False,
1770        **QUERY_MODIFIERS,
1771    }
1772
1773    def unnest(self) -> Expr:
1774        """Returns the first non subquery."""
1775        expression: Expr = self
1776        while isinstance(expression, Subquery):
1777            expression = expression.this
1778        return expression
1779
1780    def unwrap(self) -> Subquery:
1781        expression = self
1782        while expression.same_parent and expression.is_wrapper:
1783            expression = t.cast(Subquery, expression.parent)
1784        return expression
1785
1786    def select(
1787        self,
1788        *expressions: ExpOrStr | None,
1789        append: bool = True,
1790        dialect: DialectType = None,
1791        copy: bool = True,
1792        **opts: Unpack[ParserNoDialectArgs],
1793    ) -> Subquery:
1794        this = maybe_copy(self, copy)
1795        inner = this.unnest()
1796        if hasattr(inner, "select"):
1797            inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1798        return this
1799
1800    @property
1801    def is_wrapper(self) -> bool:
1802        """
1803        Whether this Subquery acts as a simple wrapper around another expression.
1804
1805        SELECT * FROM (((SELECT * FROM t)))
1806                      ^
1807                      This corresponds to a "wrapper" Subquery node
1808        """
1809        return all(v is None for k, v in self.args.items() if k != "this")
1810
1811    @property
1812    def is_star(self) -> bool:
1813        return _is_star(self)
1814
1815    @property
1816    def output_name(self) -> str:
1817        return self.alias
is_subquery: ClassVar[bool] = True
arg_types = {'this': True, 'alias': False, 'with_': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'prewhere': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False, 'options': False, 'for_': False}
def unnest(self) -> sqlglot.expressions.core.Expr:
1773    def unnest(self) -> Expr:
1774        """Returns the first non subquery."""
1775        expression: Expr = self
1776        while isinstance(expression, Subquery):
1777            expression = expression.this
1778        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
1780    def unwrap(self) -> Subquery:
1781        expression = self
1782        while expression.same_parent and expression.is_wrapper:
1783            expression = t.cast(Subquery, expression.parent)
1784        return expression
def select( self, *expressions: Union[int, str, sqlglot.expressions.core.Expr, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Subquery:
1786    def select(
1787        self,
1788        *expressions: ExpOrStr | None,
1789        append: bool = True,
1790        dialect: DialectType = None,
1791        copy: bool = True,
1792        **opts: Unpack[ParserNoDialectArgs],
1793    ) -> Subquery:
1794        this = maybe_copy(self, copy)
1795        inner = this.unnest()
1796        if hasattr(inner, "select"):
1797            inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1798        return this
is_wrapper: bool
1800    @property
1801    def is_wrapper(self) -> bool:
1802        """
1803        Whether this Subquery acts as a simple wrapper around another expression.
1804
1805        SELECT * FROM (((SELECT * FROM t)))
1806                      ^
1807                      This corresponds to a "wrapper" Subquery node
1808        """
1809        return all(v is None for k, v in self.args.items() if k != "this")

Whether this Subquery acts as a simple wrapper around another expression.

SELECT * FROM (((SELECT * FROM t))) ^ This corresponds to a "wrapper" Subquery node

is_star: bool
1811    @property
1812    def is_star(self) -> bool:
1813        return _is_star(self)

Checks whether an expression is a star.

output_name: str
1815    @property
1816    def output_name(self) -> str:
1817        return self.alias

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'subquery'
required_args: 't.ClassVar[set[str]]' = {'this'}
class TableSample(sqlglot.expressions.core.Expression):
1820class TableSample(Expression):
1821    arg_types = {
1822        "expressions": False,
1823        "method": False,
1824        "bucket_numerator": False,
1825        "bucket_denominator": False,
1826        "bucket_field": False,
1827        "percent": False,
1828        "rows": False,
1829        "size": False,
1830        "seed": False,
1831    }
arg_types = {'expressions': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False}
key: ClassVar[str] = 'tablesample'
required_args: 't.ClassVar[set[str]]' = set()
class Tag(sqlglot.expressions.core.Expression):
1834class Tag(Expression):
1835    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
1836
1837    arg_types = {
1838        "this": False,
1839        "prefix": False,
1840        "postfix": False,
1841    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key: ClassVar[str] = 'tag'
required_args: 't.ClassVar[set[str]]' = set()
class Pivot(sqlglot.expressions.core.Expression):
1844class Pivot(Expression):
1845    arg_types = {
1846        "this": False,
1847        "alias": False,
1848        "expressions": False,
1849        "fields": False,
1850        "unpivot": False,
1851        "using": False,
1852        "group": False,
1853        "columns": False,
1854        "include_nulls": False,
1855        "default_on_null": False,
1856        "into": False,
1857        "with_": False,
1858        "identify_pivot_strings": False,
1859        "prefixed_pivot_columns": False,
1860        "pivot_column_naming": False,
1861        "value_columns_first": False,
1862    }
1863
1864    @property
1865    def unpivot(self) -> bool:
1866        return bool(self.args.get("unpivot"))
1867
1868    @property
1869    def fields(self) -> list[Expr]:
1870        return self.args.get("fields", [])
1871
1872    def output_columns(self, pre_pivot_columns: t.Iterable[str]) -> dict[str, str]:
1873        """
1874        Returns an ordered map of post-rename output column name -> pre-rename
1875        source-side name, in the order the (UN)PIVOT produces them.
1876
1877        For callers that just want the names, iterate the dict (or call .keys()):
1878            >>> from sqlglot import parse_one, exp
1879            >>> piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot)
1880            >>> list(piv.output_columns(["a", "b", "c"]))
1881            ['c', 'name', 'val']
1882
1883        AST shape:
1884            PIVOT(SUM(val) FOR name IN ('a', 'b')):
1885                expressions: aggregate(s), e.g. [Sum(this=Column(val))]
1886                fields:      [In(this=Column(name), expressions=[Literal('a'), Literal('b')])]
1887                columns:     optional explicit output identifiers (e.g. set by Snowflake)
1888
1889            UNPIVOT(val FOR name IN (a, b)):
1890                expressions: value Identifier(s), or Tuple(Identifiers) for multi-value
1891                fields:      [In(this=Identifier(name), expressions=[Column(a), Column(b)])]
1892                             For literal-aliased entries (`a AS 'x'`) the IN expressions
1893                             are wrapped in PivotAlias(this=Column, alias=Literal).
1894
1895        Args:
1896            pre_pivot_columns: Columns visible to the operator before it runs
1897                (e.g. the source table or subquery's projections).
1898        """
1899        if self.unpivot:
1900            excluded: set[str] = set()
1901            name_columns: list[Identifier] = []
1902            for field in self.fields:
1903                if not isinstance(field, In):
1904                    continue
1905                if isinstance(field.this, Identifier):
1906                    name_columns.append(field.this)
1907                for e in field.expressions:
1908                    excluded.update(c.output_name for c in e.find_all(Column))
1909            value_columns = [
1910                ident
1911                for e in self.expressions
1912                for ident in (e.expressions if isinstance(e, Tuple) else [e])
1913                if isinstance(ident, Identifier)
1914            ]
1915            # T-SQL emits the value column(s) ahead of the name column, everyone else emits them after it
1916            ordered = (
1917                value_columns + name_columns
1918                if self.args.get("value_columns_first")
1919                else name_columns + value_columns
1920            )
1921            outputs = [i.name for i in ordered]
1922        else:
1923            excluded = {c.output_name for c in self.find_all(Column)}
1924            outputs = [c.output_name for c in self.args.get("columns") or []]
1925            if not outputs:
1926                outputs = [c.alias_or_name for c in self.expressions]
1927
1928        if not excluded or not outputs:
1929            return {}
1930
1931        pre_rename = [c for c in pre_pivot_columns if c not in excluded] + outputs
1932
1933        alias = self.args.get("alias")
1934        renames = alias.args.get("columns") if alias else None
1935
1936        # `PIVOT(...) AS alias(c1, c2, ...)` renames the operator's output columns
1937        # positionally from the front (DuckDB, Snowflake): the user's names cover
1938        # the leading N output columns, remaining columns keep their auto names.
1939        if renames:
1940            rename_names = [r.name for r in renames]
1941            post_rename = rename_names + pre_rename[len(rename_names) :]
1942        else:
1943            post_rename = pre_rename
1944
1945        return dict(zip(post_rename, pre_rename))
arg_types = {'this': False, 'alias': False, 'expressions': False, 'fields': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False, 'default_on_null': False, 'into': False, 'with_': False, 'identify_pivot_strings': False, 'prefixed_pivot_columns': False, 'pivot_column_naming': False, 'value_columns_first': False}
unpivot: bool
1864    @property
1865    def unpivot(self) -> bool:
1866        return bool(self.args.get("unpivot"))
fields: list[sqlglot.expressions.core.Expr]
1868    @property
1869    def fields(self) -> list[Expr]:
1870        return self.args.get("fields", [])
def output_columns(self, pre_pivot_columns: Iterable[str]) -> dict[str, str]:
1872    def output_columns(self, pre_pivot_columns: t.Iterable[str]) -> dict[str, str]:
1873        """
1874        Returns an ordered map of post-rename output column name -> pre-rename
1875        source-side name, in the order the (UN)PIVOT produces them.
1876
1877        For callers that just want the names, iterate the dict (or call .keys()):
1878            >>> from sqlglot import parse_one, exp
1879            >>> piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot)
1880            >>> list(piv.output_columns(["a", "b", "c"]))
1881            ['c', 'name', 'val']
1882
1883        AST shape:
1884            PIVOT(SUM(val) FOR name IN ('a', 'b')):
1885                expressions: aggregate(s), e.g. [Sum(this=Column(val))]
1886                fields:      [In(this=Column(name), expressions=[Literal('a'), Literal('b')])]
1887                columns:     optional explicit output identifiers (e.g. set by Snowflake)
1888
1889            UNPIVOT(val FOR name IN (a, b)):
1890                expressions: value Identifier(s), or Tuple(Identifiers) for multi-value
1891                fields:      [In(this=Identifier(name), expressions=[Column(a), Column(b)])]
1892                             For literal-aliased entries (`a AS 'x'`) the IN expressions
1893                             are wrapped in PivotAlias(this=Column, alias=Literal).
1894
1895        Args:
1896            pre_pivot_columns: Columns visible to the operator before it runs
1897                (e.g. the source table or subquery's projections).
1898        """
1899        if self.unpivot:
1900            excluded: set[str] = set()
1901            name_columns: list[Identifier] = []
1902            for field in self.fields:
1903                if not isinstance(field, In):
1904                    continue
1905                if isinstance(field.this, Identifier):
1906                    name_columns.append(field.this)
1907                for e in field.expressions:
1908                    excluded.update(c.output_name for c in e.find_all(Column))
1909            value_columns = [
1910                ident
1911                for e in self.expressions
1912                for ident in (e.expressions if isinstance(e, Tuple) else [e])
1913                if isinstance(ident, Identifier)
1914            ]
1915            # T-SQL emits the value column(s) ahead of the name column, everyone else emits them after it
1916            ordered = (
1917                value_columns + name_columns
1918                if self.args.get("value_columns_first")
1919                else name_columns + value_columns
1920            )
1921            outputs = [i.name for i in ordered]
1922        else:
1923            excluded = {c.output_name for c in self.find_all(Column)}
1924            outputs = [c.output_name for c in self.args.get("columns") or []]
1925            if not outputs:
1926                outputs = [c.alias_or_name for c in self.expressions]
1927
1928        if not excluded or not outputs:
1929            return {}
1930
1931        pre_rename = [c for c in pre_pivot_columns if c not in excluded] + outputs
1932
1933        alias = self.args.get("alias")
1934        renames = alias.args.get("columns") if alias else None
1935
1936        # `PIVOT(...) AS alias(c1, c2, ...)` renames the operator's output columns
1937        # positionally from the front (DuckDB, Snowflake): the user's names cover
1938        # the leading N output columns, remaining columns keep their auto names.
1939        if renames:
1940            rename_names = [r.name for r in renames]
1941            post_rename = rename_names + pre_rename[len(rename_names) :]
1942        else:
1943            post_rename = pre_rename
1944
1945        return dict(zip(post_rename, pre_rename))

Returns an ordered map of post-rename output column name -> pre-rename source-side name, in the order the (UN)PIVOT produces them.

For callers that just want the names, iterate the dict (or call .keys()):

from sqlglot import parse_one, exp piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot) list(piv.output_columns(["a", "b", "c"])) ['c', 'name', 'val']

AST shape:

PIVOT(SUM(val) FOR name IN ('a', 'b')): expressions: aggregate(s), e.g. [Sum(this=Column(val))] fields: [In(this=Column(name), expressions=[Literal('a'), Literal('b')])] columns: optional explicit output identifiers (e.g. set by Snowflake)

UNPIVOT(val FOR name IN (a, b)): expressions: value Identifier(s), or Tuple(Identifiers) for multi-value fields: [In(this=Identifier(name), expressions=[Column(a), Column(b)])] For literal-aliased entries (a AS 'x') the IN expressions are wrapped in PivotAlias(this=Column, alias=Literal).

Arguments:
  • pre_pivot_columns: Columns visible to the operator before it runs (e.g. the source table or subquery's projections).
key: ClassVar[str] = 'pivot'
required_args: 't.ClassVar[set[str]]' = set()
class UnpivotColumns(sqlglot.expressions.core.Expression):
1948class UnpivotColumns(Expression):
1949    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key: ClassVar[str] = 'unpivotcolumns'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
1952class Window(Expression, Condition):
1953    arg_types = {
1954        "this": True,
1955        "partition_by": False,
1956        "order": False,
1957        "spec": False,
1958        "alias": False,
1959        "over": False,
1960        "first": False,
1961    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key: ClassVar[str] = 'window'
required_args: 't.ClassVar[set[str]]' = {'this'}
class WindowSpec(sqlglot.expressions.core.Expression):
1964class WindowSpec(Expression):
1965    arg_types = {
1966        "kind": False,
1967        "start": False,
1968        "start_side": False,
1969        "end": False,
1970        "end_side": False,
1971        "exclude": False,
1972    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False, 'exclude': False}
key: ClassVar[str] = 'windowspec'
required_args: 't.ClassVar[set[str]]' = set()
class PartitionByExcluding(sqlglot.expressions.core.Expression):
1975class PartitionByExcluding(Expression):
1976    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'partitionbyexcluding'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class PreWhere(sqlglot.expressions.core.Expression):
1979class PreWhere(Expression):
1980    pass
key: ClassVar[str] = 'prewhere'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Where(sqlglot.expressions.core.Expression):
1983class Where(Expression):
1984    pass
key: ClassVar[str] = 'where'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Optimize(sqlglot.expressions.core.Expression):
1987class Optimize(Expression):
1988    arg_types = {"this": True, "full": False, "where": False, "zorder": False}
arg_types = {'this': True, 'full': False, 'where': False, 'zorder': False}
key: ClassVar[str] = 'optimize'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Analyze(sqlglot.expressions.core.Expression):
1991class Analyze(Expression):
1992    arg_types = {
1993        "kind": False,
1994        "tables": False,
1995        "options": False,
1996        "mode": False,
1997        "partition": False,
1998        "expression": False,
1999        "properties": False,
2000    }
arg_types = {'kind': False, 'tables': False, 'options': False, 'mode': False, 'partition': False, 'expression': False, 'properties': False}
key: ClassVar[str] = 'analyze'
required_args: 't.ClassVar[set[str]]' = set()
class AnalyzeStatistics(sqlglot.expressions.core.Expression):
2003class AnalyzeStatistics(Expression):
2004    arg_types = {
2005        "kind": True,
2006        "option": False,
2007        "this": False,
2008        "expressions": False,
2009    }
arg_types = {'kind': True, 'option': False, 'this': False, 'expressions': False}
key: ClassVar[str] = 'analyzestatistics'
required_args: 't.ClassVar[set[str]]' = {'kind'}
class AnalyzeHistogram(sqlglot.expressions.core.Expression):
2012class AnalyzeHistogram(Expression):
2013    arg_types = {
2014        "this": True,
2015        "expressions": True,
2016        "expression": False,
2017        "update_options": False,
2018    }
arg_types = {'this': True, 'expressions': True, 'expression': False, 'update_options': False}
key: ClassVar[str] = 'analyzehistogram'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
class AnalyzeSample(sqlglot.expressions.core.Expression):
2021class AnalyzeSample(Expression):
2022    arg_types = {"kind": True, "sample": True}
arg_types = {'kind': True, 'sample': True}
key: ClassVar[str] = 'analyzesample'
required_args: 't.ClassVar[set[str]]' = {'sample', 'kind'}
class AnalyzeListChainedRows(sqlglot.expressions.core.Expression):
2025class AnalyzeListChainedRows(Expression):
2026    arg_types = {"expression": False}
arg_types = {'expression': False}
key: ClassVar[str] = 'analyzelistchainedrows'
required_args: 't.ClassVar[set[str]]' = set()
class AnalyzeDelete(sqlglot.expressions.core.Expression):
2029class AnalyzeDelete(Expression):
2030    arg_types = {"kind": False}
arg_types = {'kind': False}
key: ClassVar[str] = 'analyzedelete'
required_args: 't.ClassVar[set[str]]' = set()
class AnalyzeWith(sqlglot.expressions.core.Expression):
2033class AnalyzeWith(Expression):
2034    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'analyzewith'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class AnalyzeValidate(sqlglot.expressions.core.Expression):
2037class AnalyzeValidate(Expression):
2038    arg_types = {
2039        "kind": True,
2040        "this": False,
2041        "expression": False,
2042    }
arg_types = {'kind': True, 'this': False, 'expression': False}
key: ClassVar[str] = 'analyzevalidate'
required_args: 't.ClassVar[set[str]]' = {'kind'}
class AnalyzeColumns(sqlglot.expressions.core.Expression):
2045class AnalyzeColumns(Expression):
2046    pass
key: ClassVar[str] = 'analyzecolumns'
required_args: 't.ClassVar[set[str]]' = {'this'}
class UsingData(sqlglot.expressions.core.Expression):
2049class UsingData(Expression):
2050    pass
key: ClassVar[str] = 'usingdata'
required_args: 't.ClassVar[set[str]]' = {'this'}
class AddPartition(sqlglot.expressions.core.Expression):
2053class AddPartition(Expression):
2054    arg_types = {"this": True, "exists": False, "location": False}
arg_types = {'this': True, 'exists': False, 'location': False}
key: ClassVar[str] = 'addpartition'
required_args: 't.ClassVar[set[str]]' = {'this'}
class AttachOption(sqlglot.expressions.core.Expression):
2057class AttachOption(Expression):
2058    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key: ClassVar[str] = 'attachoption'
required_args: 't.ClassVar[set[str]]' = {'this'}
class DropPartition(sqlglot.expressions.core.Expression):
2061class DropPartition(Expression):
2062    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key: ClassVar[str] = 'droppartition'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class ReplaceColumns(sqlglot.expressions.core.Expression):
2065class ReplaceColumns(Expression):
2066    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'replacecolumns'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class ReplacePartition(sqlglot.expressions.core.Expression):
2069class ReplacePartition(Expression):
2070    arg_types = {"expression": True, "source": True}
arg_types = {'expression': True, 'source': True}
key: ClassVar[str] = 'replacepartition'
required_args: 't.ClassVar[set[str]]' = {'source', 'expression'}
class TranslateCharacters(sqlglot.expressions.core.Expression):
2073class TranslateCharacters(Expression):
2074    arg_types = {"this": True, "expression": True, "with_error": False}
arg_types = {'this': True, 'expression': True, 'with_error': False}
key: ClassVar[str] = 'translatecharacters'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class OverflowTruncateBehavior(sqlglot.expressions.core.Expression):
2077class OverflowTruncateBehavior(Expression):
2078    arg_types = {"this": False, "with_count": True}
arg_types = {'this': False, 'with_count': True}
key: ClassVar[str] = 'overflowtruncatebehavior'
required_args: 't.ClassVar[set[str]]' = {'with_count'}
class JSON(sqlglot.expressions.core.Expression):
2081class JSON(Expression):
2082    arg_types = {"this": False, "with_": False, "unique": False}
arg_types = {'this': False, 'with_': False, 'unique': False}
key: ClassVar[str] = 'json'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPath(sqlglot.expressions.core.Expression):
2085class JSONPath(Expression):
2086    arg_types = {"expressions": True}
2087
2088    @property
2089    def output_name(self) -> str:
2090        last_segment = self.expressions[-1].this
2091        return last_segment if isinstance(last_segment, str) else ""
arg_types = {'expressions': True}
output_name: str
2088    @property
2089    def output_name(self) -> str:
2090        last_segment = self.expressions[-1].this
2091        return last_segment if isinstance(last_segment, str) else ""

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'jsonpath'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class JSONPathPart(sqlglot.expressions.core.Expression):
2094class JSONPathPart(Expression):
2095    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'jsonpathpart'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathFilter(JSONPathPart):
2098class JSONPathFilter(JSONPathPart):
2099    arg_types = {"this": True}
2100    _hash_raw_args = True
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathfilter'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathKey(JSONPathPart):
2103class JSONPathKey(JSONPathPart):
2104    arg_types = {"this": True, "quoted": False}
2105    _hash_raw_args = True
arg_types = {'this': True, 'quoted': False}
key: ClassVar[str] = 'jsonpathkey'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathRecursive(JSONPathPart):
2108class JSONPathRecursive(JSONPathPart):
2109    arg_types = {"this": False}
2110    _hash_raw_args = True
arg_types = {'this': False}
key: ClassVar[str] = 'jsonpathrecursive'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathRoot(JSONPathPart):
2113class JSONPathRoot(JSONPathPart):
2114    pass
key: ClassVar[str] = 'jsonpathroot'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathScript(JSONPathPart):
2117class JSONPathScript(JSONPathPart):
2118    arg_types = {"this": True}
2119    _hash_raw_args = True
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathscript'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathSlice(JSONPathPart):
2122class JSONPathSlice(JSONPathPart):
2123    arg_types = {"start": False, "end": False, "step": False}
arg_types = {'start': False, 'end': False, 'step': False}
key: ClassVar[str] = 'jsonpathslice'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathSelector(JSONPathPart):
2126class JSONPathSelector(JSONPathPart):
2127    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathselector'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathSubscript(JSONPathPart):
2130class JSONPathSubscript(JSONPathPart):
2131    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathsubscript'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathUnion(JSONPathPart):
2134class JSONPathUnion(JSONPathPart):
2135    arg_types = {"expressions": True}
2136    _hash_raw_args = True
arg_types = {'expressions': True}
key: ClassVar[str] = 'jsonpathunion'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class JSONPathWildcard(JSONPathPart):
2139class JSONPathWildcard(JSONPathPart):
2140    pass
key: ClassVar[str] = 'jsonpathwildcard'
required_args: 't.ClassVar[set[str]]' = set()
class FormatJson(sqlglot.expressions.core.Expression):
2143class FormatJson(Expression):
2144    pass
key: ClassVar[str] = 'formatjson'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONKeyValue(sqlglot.expressions.core.Expression):
2147class JSONKeyValue(Expression):
2148    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'jsonkeyvalue'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class JSONColumnDef(sqlglot.expressions.core.Expression):
2151class JSONColumnDef(Expression):
2152    arg_types = {
2153        "this": False,
2154        "kind": False,
2155        "path": False,
2156        "nested_schema": False,
2157        "ordinality": False,
2158        "format_json": False,
2159    }
arg_types = {'this': False, 'kind': False, 'path': False, 'nested_schema': False, 'ordinality': False, 'format_json': False}
key: ClassVar[str] = 'jsoncolumndef'
required_args: 't.ClassVar[set[str]]' = set()
class JSONSchema(sqlglot.expressions.core.Expression):
2162class JSONSchema(Expression):
2163    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'jsonschema'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class JSONValue(sqlglot.expressions.core.Expression):
2166class JSONValue(Expression):
2167    arg_types = {
2168        "this": True,
2169        "path": True,
2170        "returning": False,
2171        "on_condition": False,
2172    }
arg_types = {'this': True, 'path': True, 'returning': False, 'on_condition': False}
key: ClassVar[str] = 'jsonvalue'
required_args: 't.ClassVar[set[str]]' = {'path', 'this'}
2175class JSONValueArray(Expression, Func):
2176    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key: ClassVar[str] = 'jsonvaluearray'
required_args: 't.ClassVar[set[str]]' = {'this'}
class OpenJSONColumnDef(sqlglot.expressions.core.Expression):
2179class OpenJSONColumnDef(Expression):
2180    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key: ClassVar[str] = 'openjsoncolumndef'
required_args: 't.ClassVar[set[str]]' = {'kind', 'this'}
class JSONExtractQuote(sqlglot.expressions.core.Expression):
2183class JSONExtractQuote(Expression):
2184    arg_types = {
2185        "option": True,
2186        "scalar": False,
2187    }
arg_types = {'option': True, 'scalar': False}
key: ClassVar[str] = 'jsonextractquote'
required_args: 't.ClassVar[set[str]]' = {'option'}
class ScopeResolution(sqlglot.expressions.core.Expression):
2190class ScopeResolution(Expression):
2191    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key: ClassVar[str] = 'scoperesolution'
required_args: 't.ClassVar[set[str]]' = {'expression'}
class Stream(sqlglot.expressions.core.Expression):
2194class Stream(Expression):
2195    pass
key: ClassVar[str] = 'stream'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ModelAttribute(sqlglot.expressions.core.Expression):
2198class ModelAttribute(Expression):
2199    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'modelattribute'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class XMLNamespace(sqlglot.expressions.core.Expression):
2202class XMLNamespace(Expression):
2203    pass
key: ClassVar[str] = 'xmlnamespace'
required_args: 't.ClassVar[set[str]]' = {'this'}
class XMLKeyValueOption(sqlglot.expressions.core.Expression):
2206class XMLKeyValueOption(Expression):
2207    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key: ClassVar[str] = 'xmlkeyvalueoption'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Semicolon(sqlglot.expressions.core.Expression):
2210class Semicolon(Expression):
2211    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'semicolon'
required_args: 't.ClassVar[set[str]]' = set()
class TableColumn(sqlglot.expressions.core.Expression):
2214class TableColumn(Expression):
2215    @property
2216    def output_name(self) -> str:
2217        return self.name
output_name: str
2215    @property
2216    def output_name(self) -> str:
2217        return self.name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'tablecolumn'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Variadic(sqlglot.expressions.core.Expression):
2220class Variadic(Expression):
2221    pass
key: ClassVar[str] = 'variadic'
required_args: 't.ClassVar[set[str]]' = {'this'}
class StoredProcedure(sqlglot.expressions.core.Expression):
2224class StoredProcedure(Expression):
2225    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key: ClassVar[str] = 'storedprocedure'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Block(sqlglot.expressions.core.Expression):
2228class Block(Expression):
2229    arg_types = {"expressions": True, "begin": False}
arg_types = {'expressions': True, 'begin': False}
key: ClassVar[str] = 'block'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class IfBlock(sqlglot.expressions.core.Expression):
2232class IfBlock(Expression):
2233    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key: ClassVar[str] = 'ifblock'
required_args: 't.ClassVar[set[str]]' = {'true', 'this'}
class CaseStatement(sqlglot.expressions.core.Expression):
2236class CaseStatement(Expression):
2237    arg_types = {"this": False, "ifs": True, "default": False}
arg_types = {'this': False, 'ifs': True, 'default': False}
key: ClassVar[str] = 'casestatement'
required_args: 't.ClassVar[set[str]]' = {'ifs'}
class WhileBlock(sqlglot.expressions.core.Expression):
2240class WhileBlock(Expression):
2241    arg_types = {"this": True, "body": True, "label": False}
arg_types = {'this': True, 'body': True, 'label': False}
key: ClassVar[str] = 'whileblock'
required_args: 't.ClassVar[set[str]]' = {'body', 'this'}
class LoopBlock(sqlglot.expressions.core.Expression):
2244class LoopBlock(Expression):
2245    arg_types = {"body": True, "label": False}
arg_types = {'body': True, 'label': False}
key: ClassVar[str] = 'loopblock'
required_args: 't.ClassVar[set[str]]' = {'body'}
class RepeatBlock(sqlglot.expressions.core.Expression):
2248class RepeatBlock(Expression):
2249    arg_types = {"body": True, "until": True, "label": False}
arg_types = {'body': True, 'until': True, 'label': False}
key: ClassVar[str] = 'repeatblock'
required_args: 't.ClassVar[set[str]]' = {'body', 'until'}
class Leave(sqlglot.expressions.core.Expression):
2252class Leave(Expression):
2253    pass
key: ClassVar[str] = 'leave'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Iterate(sqlglot.expressions.core.Expression):
2256class Iterate(Expression):
2257    pass
key: ClassVar[str] = 'iterate'
required_args: 't.ClassVar[set[str]]' = {'this'}
class EndStatement(sqlglot.expressions.core.Expression):
2260class EndStatement(Expression):
2261    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'endstatement'
required_args: 't.ClassVar[set[str]]' = set()
class FunctionSpecification(sqlglot.expressions.core.Expression):
2265class FunctionSpecification(Expression):
2266    arg_types = {
2267        "this": True,
2268        "characteristics": False,
2269        "properties": False,
2270        "expression": True,
2271    }
arg_types = {'this': True, 'characteristics': False, 'properties': False, 'expression': True}
key: ClassVar[str] = 'functionspecification'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
UNWRAPPED_QUERIES = (<class 'Select'>, <class 'SetOperation'>)
def union( *expressions: Union[int, str, sqlglot.expressions.core.Expr], distinct: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Union:
2277def union(
2278    *expressions: ExpOrStr,
2279    distinct: bool = True,
2280    dialect: DialectType = None,
2281    copy: bool = True,
2282    **opts: Unpack[ParserNoDialectArgs],
2283) -> Union:
2284    """
2285    Initializes a syntax tree for the `UNION` operation.
2286
2287    Example:
2288        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
2289        'SELECT * FROM foo UNION SELECT * FROM bla'
2290
2291    Args:
2292        expressions: the SQL code strings, corresponding to the `UNION`'s operands.
2293            If `Expr` instances are passed, they will be used as-is.
2294        distinct: set the DISTINCT flag if and only if this is true.
2295        dialect: the dialect used to parse the input expression.
2296        copy: whether to copy the expression.
2297        opts: other options to use to parse the input expressions.
2298
2299    Returns:
2300        The new Union instance.
2301    """
2302    assert len(expressions) >= 2, "At least two expressions are required by `union`."
2303    return _apply_set_operation(
2304        *expressions, set_operation=Union, distinct=distinct, dialect=dialect, copy=copy, **opts
2305    )

Initializes a syntax tree for the UNION operation.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expressions: the SQL code strings, corresponding to the UNION's operands. If Expr instances are passed, they will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( *expressions: Union[int, str, sqlglot.expressions.core.Expr], distinct: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Intersect:
2308def intersect(
2309    *expressions: ExpOrStr,
2310    distinct: bool = True,
2311    dialect: DialectType = None,
2312    copy: bool = True,
2313    **opts: Unpack[ParserNoDialectArgs],
2314) -> Intersect:
2315    """
2316    Initializes a syntax tree for the `INTERSECT` operation.
2317
2318    Example:
2319        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
2320        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
2321
2322    Args:
2323        expressions: the SQL code strings, corresponding to the `INTERSECT`'s operands.
2324            If `Expr` instances are passed, they will be used as-is.
2325        distinct: set the DISTINCT flag if and only if this is true.
2326        dialect: the dialect used to parse the input expression.
2327        copy: whether to copy the expression.
2328        opts: other options to use to parse the input expressions.
2329
2330    Returns:
2331        The new Intersect instance.
2332    """
2333    assert len(expressions) >= 2, "At least two expressions are required by `intersect`."
2334    return _apply_set_operation(
2335        *expressions, set_operation=Intersect, distinct=distinct, dialect=dialect, copy=copy, **opts
2336    )

Initializes a syntax tree for the INTERSECT operation.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expressions: the SQL code strings, corresponding to the INTERSECT's operands. If Expr instances are passed, they will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( *expressions: Union[int, str, sqlglot.expressions.core.Expr], distinct: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Except:
2339def except_(
2340    *expressions: ExpOrStr,
2341    distinct: bool = True,
2342    dialect: DialectType = None,
2343    copy: bool = True,
2344    **opts: Unpack[ParserNoDialectArgs],
2345) -> Except:
2346    """
2347    Initializes a syntax tree for the `EXCEPT` operation.
2348
2349    Example:
2350        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
2351        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
2352
2353    Args:
2354        expressions: the SQL code strings, corresponding to the `EXCEPT`'s operands.
2355            If `Expr` instances are passed, they will be used as-is.
2356        distinct: set the DISTINCT flag if and only if this is true.
2357        dialect: the dialect used to parse the input expression.
2358        copy: whether to copy the expression.
2359        opts: other options to use to parse the input expressions.
2360
2361    Returns:
2362        The new Except instance.
2363    """
2364    assert len(expressions) >= 2, "At least two expressions are required by `except_`."
2365    return _apply_set_operation(
2366        *expressions, set_operation=Except, distinct=distinct, dialect=dialect, copy=copy, **opts
2367    )

Initializes a syntax tree for the EXCEPT operation.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expressions: the SQL code strings, corresponding to the EXCEPT's operands. If Expr instances are passed, they will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.