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

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

ctes: list[CTE]
117    @property
118    def ctes(self) -> list[CTE]:
119        with_ = self.args.get("with_")
120        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:
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`")
def subquery( self, alias: Union[int, str, sqlglot.expressions.core.Expr, NoneType] = None, copy: bool = True) -> Subquery:
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)

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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)

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:
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)

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:
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)

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):
440class QueryBand(Expression):
441    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):
444class RecursiveWithSearch(Expression):
445    arg_types = {"kind": True, "this": True, "expression": True, "using": False}
arg_types = {'kind': True, 'this': True, 'expression': True, 'using': False}
key: ClassVar[str] = 'recursivewithsearch'
required_args: 't.ClassVar[set[str]]' = {'expression', 'kind', 'this'}
class With(sqlglot.expressions.core.Expression):
448class With(Expression):
449    arg_types = {"expressions": False, "recursive": False, "search": False, "udfs": False}
450
451    @property
452    def recursive(self) -> bool:
453        return bool(self.args.get("recursive"))
arg_types = {'expressions': False, 'recursive': False, 'search': False, 'udfs': False}
recursive: bool
451    @property
452    def recursive(self) -> bool:
453        return bool(self.args.get("recursive"))
key: ClassVar[str] = 'with'
required_args: 't.ClassVar[set[str]]' = set()
456class CTE(Expression, DerivedTable):
457    arg_types = {
458        "this": True,
459        "alias": True,
460        "scalar": False,
461        "materialized": False,
462        "key_expressions": False,
463    }
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):
466class ProjectionDef(Expression):
467    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):
470class TableAlias(Expression):
471    arg_types = {"this": False, "columns": False}
472
473    @property
474    def columns(self) -> list[t.Any]:
475        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns: list[typing.Any]
473    @property
474    def columns(self) -> list[t.Any]:
475        return self.args.get("columns") or []
key: ClassVar[str] = 'tablealias'
required_args: 't.ClassVar[set[str]]' = set()
478class BitString(Expression, Condition):
479    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'bitstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
482class HexString(Expression, Condition):
483    arg_types = {"this": True, "is_integer": False}
484    is_primitive = True
arg_types = {'this': True, 'is_integer': False}
is_primitive = True
key: ClassVar[str] = 'hexstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
487class ByteString(Expression, Condition):
488    arg_types = {"this": True, "is_bytes": False}
489    is_primitive = True
arg_types = {'this': True, 'is_bytes': False}
is_primitive = True
key: ClassVar[str] = 'bytestring'
required_args: 't.ClassVar[set[str]]' = {'this'}
492class RawString(Expression, Condition):
493    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'rawstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
496class UnicodeString(Expression, Condition):
497    arg_types = {"this": True, "escape": False}
arg_types = {'this': True, 'escape': False}
key: ClassVar[str] = 'unicodestring'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ColumnPosition(sqlglot.expressions.core.Expression):
500class ColumnPosition(Expression):
501    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):
504class ColumnDef(Expression):
505    arg_types = {
506        "this": True,
507        "kind": False,
508        "constraints": False,
509        "exists": False,
510        "position": False,
511        "default": False,
512        "output": False,
513    }
514
515    @property
516    def constraints(self) -> list[ColumnConstraint]:
517        return self.args.get("constraints") or []
518
519    @property
520    def kind(self) -> DataType | None:
521        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]
515    @property
516    def constraints(self) -> list[ColumnConstraint]:
517        return self.args.get("constraints") or []
kind: sqlglot.expressions.datatypes.DataType | None
519    @property
520    def kind(self) -> DataType | None:
521        return self.args.get("kind")
key: ClassVar[str] = 'columndef'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Changes(sqlglot.expressions.core.Expression):
524class Changes(Expression):
525    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):
528class Connect(Expression):
529    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):
532class Prior(Expression):
533    pass
key: ClassVar[str] = 'prior'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Into(sqlglot.expressions.core.Expression):
536class Into(Expression):
537    arg_types = {
538        "this": False,
539        "temporary": False,
540        "unlogged": False,
541        "bulk_collect": False,
542        "expressions": False,
543    }
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):
546class From(Expression):
547    @property
548    def name(self) -> str:
549        return self.this.name
550
551    @property
552    def alias_or_name(self) -> str:
553        return self.this.alias_or_name
name: str
547    @property
548    def name(self) -> str:
549        return self.this.name
alias_or_name: str
551    @property
552    def alias_or_name(self) -> str:
553        return self.this.alias_or_name
key: ClassVar[str] = 'from'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Having(sqlglot.expressions.core.Expression):
556class Having(Expression):
557    pass
key: ClassVar[str] = 'having'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Index(sqlglot.expressions.core.Expression):
560class Index(Expression):
561    arg_types = {
562        "this": False,
563        "table": False,
564        "unique": False,
565        "primary": False,
566        "amp": False,  # teradata
567        "params": False,
568    }
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):
571class ConditionalInsert(Expression):
572    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):
575class MultitableInserts(Expression):
576    arg_types = {"expressions": True, "kind": True, "source": True}
arg_types = {'expressions': True, 'kind': True, 'source': True}
key: ClassVar[str] = 'multitableinserts'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'kind', 'source'}
class OnCondition(sqlglot.expressions.core.Expression):
579class OnCondition(Expression):
580    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):
583class Introducer(Expression):
584    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):
587class National(Expression):
588    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'national'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Partition(sqlglot.expressions.core.Expression):
591class Partition(Expression):
592    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):
595class PartitionRange(Expression):
596    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):
599class PartitionId(Expression):
600    pass
key: ClassVar[str] = 'partitionid'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Fetch(sqlglot.expressions.core.Expression):
603class Fetch(Expression):
604    arg_types = {
605        "direction": False,
606        "count": False,
607        "limit_options": False,
608    }
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):
611class Grant(Expression):
612    arg_types = {
613        "privileges": True,
614        "kind": False,
615        "securable": True,
616        "principals": True,
617        "grant_option": False,
618    }
arg_types = {'privileges': True, 'kind': False, 'securable': True, 'principals': True, 'grant_option': False}
key: ClassVar[str] = 'grant'
required_args: 't.ClassVar[set[str]]' = {'privileges', 'principals', 'securable'}
class Revoke(sqlglot.expressions.core.Expression):
621class Revoke(Expression):
622    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]]' = {'privileges', 'principals', 'securable'}
class Group(sqlglot.expressions.core.Expression):
625class Group(Expression):
626    arg_types = {
627        "expressions": False,
628        "grouping_sets": False,
629        "cube": False,
630        "rollup": False,
631        "totals": False,
632        "all": False,
633    }
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):
636class Cube(Expression):
637    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):
640class Rollup(Expression):
641    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):
644class GroupingSets(Expression):
645    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):
648class Lambda(Expression):
649    arg_types = {"this": True, "expressions": True, "colon": False}
arg_types = {'this': True, 'expressions': True, 'colon': False}
key: ClassVar[str] = 'lambda'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
class Limit(sqlglot.expressions.core.Expression):
652class Limit(Expression):
653    arg_types = {
654        "this": False,
655        "expression": True,
656        "offset": False,
657        "limit_options": False,
658        "expressions": False,
659    }
arg_types = {'this': False, 'expression': True, 'offset': False, 'limit_options': False, 'expressions': False}
key: ClassVar[str] = 'limit'
required_args: 't.ClassVar[set[str]]' = {'expression'}
class LimitOptions(sqlglot.expressions.core.Expression):
662class LimitOptions(Expression):
663    arg_types = {
664        "percent": False,
665        "rows": False,
666        "with_ties": False,
667    }
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):
670class Join(Expression):
671    arg_types = {
672        "this": True,
673        "on": False,
674        "side": False,
675        "kind": False,
676        "using": False,
677        "method": False,
678        "global_": False,
679        "hint": False,
680        "match_condition": False,  # Snowflake
681        "directed": False,  # Snowflake
682        "expressions": False,
683        "pivots": False,
684    }
685
686    @property
687    def method(self) -> str:
688        return self.text("method").upper()
689
690    @property
691    def kind(self) -> str:
692        return self.text("kind").upper()
693
694    @property
695    def side(self) -> str:
696        return self.text("side").upper()
697
698    @property
699    def hint(self) -> str:
700        return self.text("hint").upper()
701
702    @property
703    def alias_or_name(self) -> str:
704        return self.this.alias_or_name
705
706    @property
707    def is_semi_or_anti_join(self) -> bool:
708        return self.kind in ("SEMI", "ANTI")
709
710    def on(
711        self,
712        *expressions: ExpOrStr | None,
713        append: bool = True,
714        dialect: DialectType = None,
715        copy: bool = True,
716        **opts: Unpack[ParserNoDialectArgs],
717    ) -> Join:
718        """
719        Append to or set the ON expressions.
720
721        Example:
722            >>> import sqlglot
723            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
724            'JOIN x ON y = 1'
725
726        Args:
727            *expressions: the SQL code strings to parse.
728                If an `Expr` instance is passed, it will be used as-is.
729                Multiple expressions are combined with an AND operator.
730            append: if `True`, AND the new expressions to any existing expression.
731                Otherwise, this resets the expression.
732            dialect: the dialect used to parse the input expressions.
733            copy: if `False`, modify this expression instance in-place.
734            opts: other options to use to parse the input expressions.
735
736        Returns:
737            The modified Join expression.
738        """
739        join = _apply_conjunction_builder(
740            *expressions,
741            instance=self,
742            arg="on",
743            append=append,
744            dialect=dialect,
745            copy=copy,
746            **opts,
747        )
748
749        if join.kind == "CROSS":
750            join.set("kind", None)
751
752        return join
753
754    def using(
755        self,
756        *expressions: ExpOrStr | None,
757        append: bool = True,
758        dialect: DialectType = None,
759        copy: bool = True,
760        **opts: Unpack[ParserNoDialectArgs],
761    ) -> Join:
762        """
763        Append to or set the USING expressions.
764
765        Example:
766            >>> import sqlglot
767            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
768            'JOIN x USING (foo, bla)'
769
770        Args:
771            *expressions: the SQL code strings to parse.
772                If an `Expr` instance is passed, it will be used as-is.
773            append: if `True`, concatenate the new expressions to the existing "using" list.
774                Otherwise, this resets the expression.
775            dialect: the dialect used to parse the input expressions.
776            copy: if `False`, modify this expression instance in-place.
777            opts: other options to use to parse the input expressions.
778
779        Returns:
780            The modified Join expression.
781        """
782        join = _apply_list_builder(
783            *expressions,
784            instance=self,
785            arg="using",
786            append=append,
787            dialect=dialect,
788            copy=copy,
789            **opts,
790        )
791
792        if join.kind == "CROSS":
793            join.set("kind", None)
794
795        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global_': False, 'hint': False, 'match_condition': False, 'directed': False, 'expressions': False, 'pivots': False}
method: str
686    @property
687    def method(self) -> str:
688        return self.text("method").upper()
kind: str
690    @property
691    def kind(self) -> str:
692        return self.text("kind").upper()
side: str
694    @property
695    def side(self) -> str:
696        return self.text("side").upper()
hint: str
698    @property
699    def hint(self) -> str:
700        return self.text("hint").upper()
alias_or_name: str
702    @property
703    def alias_or_name(self) -> str:
704        return self.this.alias_or_name
is_semi_or_anti_join: bool
706    @property
707    def is_semi_or_anti_join(self) -> bool:
708        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:
710    def on(
711        self,
712        *expressions: ExpOrStr | None,
713        append: bool = True,
714        dialect: DialectType = None,
715        copy: bool = True,
716        **opts: Unpack[ParserNoDialectArgs],
717    ) -> Join:
718        """
719        Append to or set the ON expressions.
720
721        Example:
722            >>> import sqlglot
723            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
724            'JOIN x ON y = 1'
725
726        Args:
727            *expressions: the SQL code strings to parse.
728                If an `Expr` instance is passed, it will be used as-is.
729                Multiple expressions are combined with an AND operator.
730            append: if `True`, AND the new expressions to any existing expression.
731                Otherwise, this resets the expression.
732            dialect: the dialect used to parse the input expressions.
733            copy: if `False`, modify this expression instance in-place.
734            opts: other options to use to parse the input expressions.
735
736        Returns:
737            The modified Join expression.
738        """
739        join = _apply_conjunction_builder(
740            *expressions,
741            instance=self,
742            arg="on",
743            append=append,
744            dialect=dialect,
745            copy=copy,
746            **opts,
747        )
748
749        if join.kind == "CROSS":
750            join.set("kind", None)
751
752        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:
754    def using(
755        self,
756        *expressions: ExpOrStr | None,
757        append: bool = True,
758        dialect: DialectType = None,
759        copy: bool = True,
760        **opts: Unpack[ParserNoDialectArgs],
761    ) -> Join:
762        """
763        Append to or set the USING expressions.
764
765        Example:
766            >>> import sqlglot
767            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
768            'JOIN x USING (foo, bla)'
769
770        Args:
771            *expressions: the SQL code strings to parse.
772                If an `Expr` instance is passed, it will be used as-is.
773            append: if `True`, concatenate the new expressions to the existing "using" list.
774                Otherwise, this resets the expression.
775            dialect: the dialect used to parse the input expressions.
776            copy: if `False`, modify this expression instance in-place.
777            opts: other options to use to parse the input expressions.
778
779        Returns:
780            The modified Join expression.
781        """
782        join = _apply_list_builder(
783            *expressions,
784            instance=self,
785            arg="using",
786            append=append,
787            dialect=dialect,
788            copy=copy,
789            **opts,
790        )
791
792        if join.kind == "CROSS":
793            join.set("kind", None)
794
795        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 Lateral(sqlglot.expressions.core.Expression, UDTF):
798class Lateral(Expression, UDTF):
799    arg_types = {
800        "this": True,
801        "view": False,
802        "outer": False,
803        "alias": False,
804        "cross_apply": False,  # True -> CROSS APPLY, False -> OUTER APPLY
805        "ordinality": False,
806    }
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False, 'cross_apply': False, 'ordinality': False}
key: ClassVar[str] = 'lateral'
required_args: 't.ClassVar[set[str]]' = {'this'}
class TableFromRows(sqlglot.expressions.core.Expression, UDTF):
809class TableFromRows(Expression, UDTF):
810    arg_types = {
811        "this": True,
812        "alias": False,
813        "joins": False,
814        "pivots": False,
815        "sample": False,
816    }
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):
819class MatchRecognizeMeasure(Expression):
820    arg_types = {
821        "this": True,
822        "window_frame": False,
823    }
arg_types = {'this': True, 'window_frame': False}
key: ClassVar[str] = 'matchrecognizemeasure'
required_args: 't.ClassVar[set[str]]' = {'this'}
class MatchRecognize(sqlglot.expressions.core.Expression):
826class MatchRecognize(Expression):
827    arg_types = {
828        "partition_by": False,
829        "order": False,
830        "measures": False,
831        "rows": False,
832        "after": False,
833        "pattern": False,
834        "define": False,
835        "alias": False,
836    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key: ClassVar[str] = 'matchrecognize'
required_args: 't.ClassVar[set[str]]' = set()
class Final(sqlglot.expressions.core.Expression):
839class Final(Expression):
840    pass
key: ClassVar[str] = 'final'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Offset(sqlglot.expressions.core.Expression):
843class Offset(Expression):
844    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):
847class Order(Expression):
848    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):
851class WithFill(Expression):
852    arg_types = {
853        "from_": False,
854        "to": False,
855        "step": False,
856        "interpolate": False,
857    }
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):
860class SkipJSONColumn(Expression):
861    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):
864class Cluster(Expression):
865    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'cluster'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Distribute(Order):
868class Distribute(Order):
869    pass
key: ClassVar[str] = 'distribute'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Sort(Order):
872class Sort(Order):
873    pass
key: ClassVar[str] = 'sort'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Qualify(sqlglot.expressions.core.Expression):
876class Qualify(Expression):
877    pass
key: ClassVar[str] = 'qualify'
required_args: 't.ClassVar[set[str]]' = {'this'}
class InputOutputFormat(sqlglot.expressions.core.Expression):
880class InputOutputFormat(Expression):
881    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):
884class Return(Expression):
885    pass
key: ClassVar[str] = 'return'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Tuple(sqlglot.expressions.core.Expression):
888class Tuple(Expression):
889    arg_types = {"expressions": False}
890
891    def isin(
892        self,
893        *expressions: t.Any,
894        query: ExpOrStr | None = None,
895        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
896        copy: bool = True,
897        **opts: Unpack[ParserArgs],
898    ) -> In:
899        return In(
900            this=maybe_copy(self, copy),
901            expressions=[convert(e, copy=copy) for e in expressions],
902            query=maybe_parse(query, copy=copy, **opts) if query else None,
903            unnest=(
904                Unnest(
905                    expressions=[
906                        maybe_parse(e, copy=copy, **opts)
907                        for e in t.cast(list[ExpOrStr], ensure_list(unnest))
908                    ]
909                )
910                if unnest
911                else None
912            ),
913        )
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:
891    def isin(
892        self,
893        *expressions: t.Any,
894        query: ExpOrStr | None = None,
895        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
896        copy: bool = True,
897        **opts: Unpack[ParserArgs],
898    ) -> In:
899        return In(
900            this=maybe_copy(self, copy),
901            expressions=[convert(e, copy=copy) for e in expressions],
902            query=maybe_parse(query, copy=copy, **opts) if query else None,
903            unnest=(
904                Unnest(
905                    expressions=[
906                        maybe_parse(e, copy=copy, **opts)
907                        for e in t.cast(list[ExpOrStr], ensure_list(unnest))
908                    ]
909                )
910                if unnest
911                else None
912            ),
913        )
key: ClassVar[str] = 'tuple'
required_args: 't.ClassVar[set[str]]' = set()
class QueryOption(sqlglot.expressions.core.Expression):
916class QueryOption(Expression):
917    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):
921class ForClause(Expression):
922    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):
925class WithTableHint(Expression):
926    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):
929class IndexTableHint(Expression):
930    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):
933class HistoricalData(Expression):
934    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]]' = {'expression', 'kind', 'this'}
class Put(sqlglot.expressions.core.Expression):
937class Put(Expression):
938    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):
941class Get(Expression):
942    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 Table(sqlglot.expressions.core.Expression, Selectable):
 945class Table(Expression, Selectable):
 946    arg_types = {
 947        "this": False,
 948        "alias": False,
 949        "db": False,
 950        "catalog": False,
 951        "laterals": False,
 952        "joins": False,
 953        "pivots": False,
 954        "hints": False,
 955        "system_time": False,
 956        "version": False,
 957        "format": False,
 958        "pattern": False,
 959        "ordinality": False,
 960        "when": False,
 961        "only": False,
 962        "partition": False,
 963        "changes": False,
 964        "rows_from": False,
 965        "sample": False,
 966        "indexed": False,
 967    }
 968
 969    @property
 970    def name(self) -> str:
 971        this = self.this
 972        if not this or (isinstance(this, Func) and not isinstance(this, DynamicIdentifier)):
 973            return ""
 974        return this.name
 975
 976    @property
 977    def db(self) -> str:
 978        return self.text("db")
 979
 980    @property
 981    def catalog(self) -> str:
 982        return self.text("catalog")
 983
 984    @property
 985    def selects(self) -> list[Expr]:
 986        return []
 987
 988    @property
 989    def named_selects(self) -> list[str]:
 990        return []
 991
 992    @property
 993    def parts(self) -> list[Expr]:
 994        """Return the parts of a table in order catalog, db, table."""
 995        parts: list[Expr] = []
 996
 997        for arg in ("catalog", "db", "this"):
 998            part = self.args.get(arg)
 999
1000            if isinstance(part, Dot):
1001                parts.extend(part.flatten())
1002            elif isinstance(part, Expr):
1003                parts.append(part)
1004
1005        return parts
1006
1007    def to_column(self, copy: bool = True) -> Expr:
1008        parts = self.parts
1009        last_part = parts[-1]
1010
1011        if isinstance(last_part, Identifier):
1012            col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy)  # type: ignore
1013        else:
1014            # This branch will be reached if a function or array is wrapped in a `Table`
1015            col = last_part
1016
1017        alias = self.args.get("alias")
1018        if alias:
1019            col = alias_(col, alias.this, copy=copy)
1020
1021        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
969    @property
970    def name(self) -> str:
971        this = self.this
972        if not this or (isinstance(this, Func) and not isinstance(this, DynamicIdentifier)):
973            return ""
974        return this.name
db: str
976    @property
977    def db(self) -> str:
978        return self.text("db")
catalog: str
980    @property
981    def catalog(self) -> str:
982        return self.text("catalog")
selects: list[sqlglot.expressions.core.Expr]
984    @property
985    def selects(self) -> list[Expr]:
986        return []
named_selects: list[str]
988    @property
989    def named_selects(self) -> list[str]:
990        return []
parts: list[sqlglot.expressions.core.Expr]
 992    @property
 993    def parts(self) -> list[Expr]:
 994        """Return the parts of a table in order catalog, db, table."""
 995        parts: list[Expr] = []
 996
 997        for arg in ("catalog", "db", "this"):
 998            part = self.args.get(arg)
 999
1000            if isinstance(part, Dot):
1001                parts.extend(part.flatten())
1002            elif isinstance(part, Expr):
1003                parts.append(part)
1004
1005        return parts

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

def to_column(self, copy: bool = True) -> sqlglot.expressions.core.Expr:
1007    def to_column(self, copy: bool = True) -> Expr:
1008        parts = self.parts
1009        last_part = parts[-1]
1010
1011        if isinstance(last_part, Identifier):
1012            col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy)  # type: ignore
1013        else:
1014            # This branch will be reached if a function or array is wrapped in a `Table`
1015            col = last_part
1016
1017        alias = self.args.get("alias")
1018        if alias:
1019            col = alias_(col, alias.this, copy=copy)
1020
1021        return col
key: ClassVar[str] = 'table'
required_args: 't.ClassVar[set[str]]' = set()
class SetOperation(sqlglot.expressions.core.Expression, Query):
1038class SetOperation(Expression, Query):
1039    arg_types = {
1040        "with_": False,
1041        "this": True,
1042        "expression": True,
1043        "distinct": False,
1044        "by_name": False,
1045        "side": False,
1046        "kind": False,
1047        "on": False,
1048        **QUERY_MODIFIERS,
1049    }
1050
1051    def select(
1052        self: S,
1053        *expressions: ExpOrStr | None,
1054        append: bool = True,
1055        dialect: DialectType = None,
1056        copy: bool = True,
1057        **opts: Unpack[ParserNoDialectArgs],
1058    ) -> S:
1059        this = maybe_copy(self, copy)
1060        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1061        this.expression.unnest().select(
1062            *expressions, append=append, dialect=dialect, copy=False, **opts
1063        )
1064        return this
1065
1066    @property
1067    def named_selects(self) -> list[str]:
1068        expr: Expr = self
1069        while isinstance(expr, SetOperation):
1070            if expr.args.get("by_name"):
1071                left = t.cast(Selectable, expr.this.unnest()).named_selects
1072                right = t.cast(Selectable, expr.expression.unnest()).named_selects
1073                return list(dict.fromkeys(left + right))
1074
1075            expr = expr.this.unnest()
1076        return _named_selects(expr)
1077
1078    @property
1079    def is_star(self) -> bool:
1080        return _is_star(self)
1081
1082    @property
1083    def selects(self) -> list[Expr]:
1084        expr: Expr = self
1085        while isinstance(expr, SetOperation):
1086            expr = expr.this.unnest()
1087        return getattr(expr, "selects", [])
1088
1089    @property
1090    def left(self) -> Query:
1091        return self.this
1092
1093    @property
1094    def right(self) -> Query:
1095        return self.expression
1096
1097    @property
1098    def kind(self) -> str:
1099        return self.text("kind").upper()
1100
1101    @property
1102    def side(self) -> str:
1103        return self.text("side").upper()
arg_types = {'with_': False, 'this': True, 'expression': True, 'distinct': False, 'by_name': False, 'side': False, 'kind': False, 'on': False, 'match': 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:
1051    def select(
1052        self: S,
1053        *expressions: ExpOrStr | None,
1054        append: bool = True,
1055        dialect: DialectType = None,
1056        copy: bool = True,
1057        **opts: Unpack[ParserNoDialectArgs],
1058    ) -> S:
1059        this = maybe_copy(self, copy)
1060        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1061        this.expression.unnest().select(
1062            *expressions, append=append, dialect=dialect, copy=False, **opts
1063        )
1064        return this
named_selects: list[str]
1066    @property
1067    def named_selects(self) -> list[str]:
1068        expr: Expr = self
1069        while isinstance(expr, SetOperation):
1070            if expr.args.get("by_name"):
1071                left = t.cast(Selectable, expr.this.unnest()).named_selects
1072                right = t.cast(Selectable, expr.expression.unnest()).named_selects
1073                return list(dict.fromkeys(left + right))
1074
1075            expr = expr.this.unnest()
1076        return _named_selects(expr)
is_star: bool
1078    @property
1079    def is_star(self) -> bool:
1080        return _is_star(self)

Checks whether an expression is a star.

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

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:
1200    def group_by(
1201        self,
1202        *expressions: ExpOrStr | None,
1203        append: bool = True,
1204        dialect: DialectType = None,
1205        copy: bool = True,
1206        **opts: Unpack[ParserNoDialectArgs],
1207    ) -> Select:
1208        """
1209        Set the GROUP BY expression.
1210
1211        Example:
1212            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
1213            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
1214
1215        Args:
1216            *expressions: the SQL code strings to parse.
1217                If a `Group` instance is passed, this is used as-is.
1218                If another `Expr` instance is passed, it will be wrapped in a `Group`.
1219                If nothing is passed in then a group by is not applied to the expression
1220            append: if `True`, add to any existing expressions.
1221                Otherwise, this flattens all the `Group` expression into a single expression.
1222            dialect: the dialect used to parse the input expression.
1223            copy: if `False`, modify this expression instance in-place.
1224            opts: other options to use to parse the input expressions.
1225
1226        Returns:
1227            The modified Select expression.
1228        """
1229        if not expressions:
1230            return self if not copy else self.copy()
1231
1232        return _apply_child_list_builder(
1233            *expressions,
1234            instance=self,
1235            arg="group",
1236            append=append,
1237            copy=copy,
1238            prefix="GROUP BY",
1239            into=Group,
1240            dialect=dialect,
1241            **opts,
1242        )

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:
1244    def sort_by(
1245        self,
1246        *expressions: ExpOrStr | None,
1247        append: bool = True,
1248        dialect: DialectType = None,
1249        copy: bool = True,
1250        **opts: Unpack[ParserNoDialectArgs],
1251    ) -> Select:
1252        """
1253        Set the SORT BY expression.
1254
1255        Example:
1256            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
1257            'SELECT x FROM tbl SORT BY x DESC'
1258
1259        Args:
1260            *expressions: the SQL code strings to parse.
1261                If a `Group` instance is passed, this is used as-is.
1262                If another `Expr` instance is passed, it will be wrapped in a `SORT`.
1263            append: if `True`, add to any existing expressions.
1264                Otherwise, this flattens all the `Order` expression into a single expression.
1265            dialect: the dialect used to parse the input expression.
1266            copy: if `False`, modify this expression instance in-place.
1267            opts: other options to use to parse the input expressions.
1268
1269        Returns:
1270            The modified Select expression.
1271        """
1272        return _apply_child_list_builder(
1273            *expressions,
1274            instance=self,
1275            arg="sort",
1276            append=append,
1277            copy=copy,
1278            prefix="SORT BY",
1279            into=Sort,
1280            dialect=dialect,
1281            **opts,
1282        )

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:
1284    def cluster_by(
1285        self,
1286        *expressions: ExpOrStr | None,
1287        append: bool = True,
1288        dialect: DialectType = None,
1289        copy: bool = True,
1290        **opts: Unpack[ParserNoDialectArgs],
1291    ) -> Select:
1292        """
1293        Set the CLUSTER BY expression.
1294
1295        Example:
1296            >>> Select().from_("tbl").select("x").cluster_by("x").sql(dialect="hive")
1297            'SELECT x FROM tbl CLUSTER BY x'
1298
1299        Args:
1300            *expressions: the SQL code strings to parse.
1301                If a `Group` instance is passed, this is used as-is.
1302                If another `Expr` instance is passed, it will be wrapped in a `Cluster`.
1303            append: if `True`, add to any existing expressions.
1304                Otherwise, this flattens all the `Order` expression into a single expression.
1305            dialect: the dialect used to parse the input expression.
1306            copy: if `False`, modify this expression instance in-place.
1307            opts: other options to use to parse the input expressions.
1308
1309        Returns:
1310            The modified Select expression.
1311        """
1312        return _apply_child_list_builder(
1313            *expressions,
1314            instance=self,
1315            arg="cluster",
1316            append=append,
1317            copy=copy,
1318            prefix="CLUSTER BY",
1319            into=Cluster,
1320            dialect=dialect,
1321            **opts,
1322        )

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:
1324    def select(
1325        self,
1326        *expressions: ExpOrStr | None,
1327        append: bool = True,
1328        dialect: DialectType = None,
1329        copy: bool = True,
1330        **opts: Unpack[ParserNoDialectArgs],
1331    ) -> Select:
1332        return _apply_list_builder(
1333            *expressions,
1334            instance=self,
1335            arg="expressions",
1336            append=append,
1337            dialect=dialect,
1338            into=Expr,
1339            copy=copy,
1340            **opts,
1341        )
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:
1343    def lateral(
1344        self,
1345        *expressions: ExpOrStr | None,
1346        append: bool = True,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        **opts: Unpack[ParserNoDialectArgs],
1350    ) -> Select:
1351        """
1352        Append to or set the LATERAL expressions.
1353
1354        Example:
1355            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
1356            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
1357
1358        Args:
1359            *expressions: the SQL code strings to parse.
1360                If an `Expr` instance is passed, it will be used as-is.
1361            append: if `True`, add to any existing expressions.
1362                Otherwise, this resets the expressions.
1363            dialect: the dialect used to parse the input expressions.
1364            copy: if `False`, modify this expression instance in-place.
1365            opts: other options to use to parse the input expressions.
1366
1367        Returns:
1368            The modified Select expression.
1369        """
1370        return _apply_list_builder(
1371            *expressions,
1372            instance=self,
1373            arg="laterals",
1374            append=append,
1375            into=Lateral,
1376            prefix="LATERAL VIEW",
1377            dialect=dialect,
1378            copy=copy,
1379            **opts,
1380        )

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:
1382    def join(
1383        self,
1384        expression: ExpOrStr,
1385        on: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1386        using: ExpOrStr | list[ExpOrStr] | tuple[ExpOrStr, ...] | None = None,
1387        append: bool = True,
1388        join_type: str | None = None,
1389        join_alias: Identifier | str | None = None,
1390        dialect: DialectType = None,
1391        copy: bool = True,
1392        **opts: Unpack[ParserNoDialectArgs],
1393    ) -> Select:
1394        """
1395        Append to or set the JOIN expressions.
1396
1397        Example:
1398            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
1399            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
1400
1401            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
1402            'SELECT 1 FROM a JOIN b USING (x, y, z)'
1403
1404            Use `join_type` to change the type of join:
1405
1406            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
1407            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
1408
1409        Args:
1410            expression: the SQL code string to parse.
1411                If an `Expr` instance is passed, it will be used as-is.
1412            on: optionally specify the join "on" criteria as a SQL string.
1413                If an `Expr` instance is passed, it will be used as-is.
1414            using: optionally specify the join "using" criteria as a SQL string.
1415                If an `Expr` instance is passed, it will be used as-is.
1416            append: if `True`, add to any existing expressions.
1417                Otherwise, this resets the expressions.
1418            join_type: if set, alter the parsed join type.
1419            join_alias: an optional alias for the joined source.
1420            dialect: the dialect used to parse the input expressions.
1421            copy: if `False`, modify this expression instance in-place.
1422            opts: other options to use to parse the input expressions.
1423
1424        Returns:
1425            Select: the modified expression.
1426        """
1427        parse_args: ParserArgs = {"dialect": dialect, **opts}
1428        try:
1429            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
1430        except ParseError:
1431            expression = maybe_parse(expression, into=(Join, Expr), **parse_args)
1432
1433        join = expression if isinstance(expression, Join) else Join(this=expression)
1434
1435        if isinstance(join.this, Select):
1436            join.this.replace(join.this.subquery())
1437
1438        if join_type:
1439            new_join: Join = maybe_parse(f"FROM _ {join_type} JOIN _", **parse_args).find(Join)
1440            method = new_join.method
1441            side = new_join.side
1442            kind = new_join.kind
1443
1444            if method:
1445                join.set("method", method)
1446            if side:
1447                join.set("side", side)
1448            if kind:
1449                join.set("kind", kind)
1450
1451        if on:
1452            on_exprs: list[ExpOrStr] = ensure_list(on)
1453            on = and_(*on_exprs, dialect=dialect, copy=copy, **opts)
1454            join.set("on", on)
1455
1456        if using:
1457            using_exprs: list[ExpOrStr] = ensure_list(using)
1458            join = _apply_list_builder(
1459                *using_exprs,
1460                instance=join,
1461                arg="using",
1462                append=append,
1463                copy=copy,
1464                into=Identifier,
1465                **opts,
1466            )
1467
1468        if join_alias:
1469            join.set("this", alias_(join.this, join_alias, table=True))
1470
1471        return _apply_list_builder(
1472            join,
1473            instance=self,
1474            arg="joins",
1475            append=append,
1476            copy=copy,
1477            **opts,
1478        )

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:
1480    def having(
1481        self,
1482        *expressions: ExpOrStr | None,
1483        append: bool = True,
1484        dialect: DialectType = None,
1485        copy: bool = True,
1486        **opts: Unpack[ParserNoDialectArgs],
1487    ) -> Select:
1488        """
1489        Append to or set the HAVING expressions.
1490
1491        Example:
1492            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
1493            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
1494
1495        Args:
1496            *expressions: the SQL code strings to parse.
1497                If an `Expr` instance is passed, it will be used as-is.
1498                Multiple expressions are combined with an AND operator.
1499            append: if `True`, AND the new expressions to any existing expression.
1500                Otherwise, this resets the expression.
1501            dialect: the dialect used to parse the input expressions.
1502            copy: if `False`, modify this expression instance in-place.
1503            opts: other options to use to parse the input expressions.
1504
1505        Returns:
1506            The modified Select expression.
1507        """
1508        return _apply_conjunction_builder(
1509            *expressions,
1510            instance=self,
1511            arg="having",
1512            append=append,
1513            into=Having,
1514            dialect=dialect,
1515            copy=copy,
1516            **opts,
1517        )

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:
1519    def window(
1520        self,
1521        *expressions: ExpOrStr | None,
1522        append: bool = True,
1523        dialect: DialectType = None,
1524        copy: bool = True,
1525        **opts: Unpack[ParserNoDialectArgs],
1526    ) -> Select:
1527        return _apply_list_builder(
1528            *expressions,
1529            instance=self,
1530            arg="windows",
1531            append=append,
1532            into=Window,
1533            dialect=dialect,
1534            copy=copy,
1535            **opts,
1536        )
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:
1538    def qualify(
1539        self,
1540        *expressions: ExpOrStr | None,
1541        append: bool = True,
1542        dialect: DialectType = None,
1543        copy: bool = True,
1544        **opts: Unpack[ParserNoDialectArgs],
1545    ) -> Select:
1546        return _apply_conjunction_builder(
1547            *expressions,
1548            instance=self,
1549            arg="qualify",
1550            append=append,
1551            into=Qualify,
1552            dialect=dialect,
1553            copy=copy,
1554            **opts,
1555        )
def distinct( self, *ons: Union[int, str, sqlglot.expressions.core.Expr, NoneType], distinct: bool = True, copy: bool = True) -> Select:
1557    def distinct(self, *ons: ExpOrStr | None, distinct: bool = True, copy: bool = True) -> Select:
1558        """
1559        Set the OFFSET expression.
1560
1561        Example:
1562            >>> Select().from_("tbl").select("x").distinct().sql()
1563            'SELECT DISTINCT x FROM tbl'
1564
1565        Args:
1566            ons: the expressions to distinct on
1567            distinct: whether the Select should be distinct
1568            copy: if `False`, modify this expression instance in-place.
1569
1570        Returns:
1571            Select: the modified expression.
1572        """
1573        instance = maybe_copy(self, copy)
1574        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
1575        instance.set("distinct", Distinct(on=on) if distinct else None)
1576        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:
1578    def ctas(
1579        self,
1580        table: ExpOrStr,
1581        properties: dict | None = None,
1582        dialect: DialectType = None,
1583        copy: bool = True,
1584        **opts: Unpack[ParserNoDialectArgs],
1585    ) -> Create:
1586        """
1587        Convert this expression to a CREATE TABLE AS statement.
1588
1589        Example:
1590            >>> Select().select("*").from_("tbl").ctas("x").sql()
1591            'CREATE TABLE x AS SELECT * FROM tbl'
1592
1593        Args:
1594            table: the SQL code string to parse as the table name.
1595                If another `Expr` instance is passed, it will be used as-is.
1596            properties: an optional mapping of table properties
1597            dialect: the dialect used to parse the input table.
1598            copy: if `False`, modify this expression instance in-place.
1599            opts: other options to use to parse the input table.
1600
1601        Returns:
1602            The new Create expression.
1603        """
1604        instance = maybe_copy(self, copy)
1605        table_expression = maybe_parse(table, into=Table, dialect=dialect, **opts)
1606
1607        properties_expression = None
1608        if properties:
1609            from sqlglot.expressions.properties import Properties as _Properties
1610
1611            properties_expression = _Properties.from_dict(properties)
1612
1613        from sqlglot.expressions.ddl import Create as _Create
1614
1615        return _Create(
1616            this=table_expression,
1617            kind="TABLE",
1618            expression=instance,
1619            properties=properties_expression,
1620        )

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:
1622    def lock(self, update: bool = True, copy: bool = True) -> Select:
1623        """
1624        Set the locking read mode for this expression.
1625
1626        Examples:
1627            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
1628            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
1629
1630            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
1631            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
1632
1633        Args:
1634            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
1635            copy: if `False`, modify this expression instance in-place.
1636
1637        Returns:
1638            The modified expression.
1639        """
1640        inst = maybe_copy(self, copy)
1641        inst.set("locks", [Lock(update=update)])
1642
1643        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:
1645    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
1646        """
1647        Set hints for this expression.
1648
1649        Examples:
1650            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
1651            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
1652
1653        Args:
1654            hints: The SQL code strings to parse as the hints.
1655                If an `Expr` instance is passed, it will be used as-is.
1656            dialect: The dialect used to parse the hints.
1657            copy: If `False`, modify this expression instance in-place.
1658
1659        Returns:
1660            The modified expression.
1661        """
1662        inst = maybe_copy(self, copy)
1663        inst.set(
1664            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
1665        )
1666
1667        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]
1669    @property
1670    def named_selects(self) -> list[str]:
1671        selects = []
1672
1673        for e in self.expressions:
1674            if e.alias_or_name:
1675                selects.append(e.output_name)
1676            elif isinstance(e, Aliases):
1677                selects.extend([a.name for a in e.aliases])
1678        return selects
is_star: bool
1680    @property
1681    def is_star(self) -> bool:
1682        return any(expression.is_star for expression in self.expressions)

Checks whether an expression is a star.

selects: list[sqlglot.expressions.core.Expr]
1684    @property
1685    def selects(self) -> list[Expr]:
1686        return self.expressions
key: ClassVar[str] = 'select'
required_args: 't.ClassVar[set[str]]' = set()
class Subquery(sqlglot.expressions.core.Expression, DerivedTable, Query):
1689class Subquery(Expression, DerivedTable, Query):
1690    is_subquery: t.ClassVar[bool] = True
1691    arg_types = {
1692        "this": True,
1693        "alias": False,
1694        "with_": False,
1695        **QUERY_MODIFIERS,
1696    }
1697
1698    def unnest(self) -> Expr:
1699        """Returns the first non subquery."""
1700        expression: Expr = self
1701        while isinstance(expression, Subquery):
1702            expression = expression.this
1703        return expression
1704
1705    def unwrap(self) -> Subquery:
1706        expression = self
1707        while expression.same_parent and expression.is_wrapper:
1708            expression = t.cast(Subquery, expression.parent)
1709        return expression
1710
1711    def select(
1712        self,
1713        *expressions: ExpOrStr | None,
1714        append: bool = True,
1715        dialect: DialectType = None,
1716        copy: bool = True,
1717        **opts: Unpack[ParserNoDialectArgs],
1718    ) -> Subquery:
1719        this = maybe_copy(self, copy)
1720        inner = this.unnest()
1721        if hasattr(inner, "select"):
1722            inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1723        return this
1724
1725    @property
1726    def is_wrapper(self) -> bool:
1727        """
1728        Whether this Subquery acts as a simple wrapper around another expression.
1729
1730        SELECT * FROM (((SELECT * FROM t)))
1731                      ^
1732                      This corresponds to a "wrapper" Subquery node
1733        """
1734        return all(v is None for k, v in self.args.items() if k != "this")
1735
1736    @property
1737    def is_star(self) -> bool:
1738        return _is_star(self)
1739
1740    @property
1741    def output_name(self) -> str:
1742        return self.alias
is_subquery: ClassVar[bool] = True
arg_types = {'this': True, 'alias': False, 'with_': False, 'match': 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:
1698    def unnest(self) -> Expr:
1699        """Returns the first non subquery."""
1700        expression: Expr = self
1701        while isinstance(expression, Subquery):
1702            expression = expression.this
1703        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
1705    def unwrap(self) -> Subquery:
1706        expression = self
1707        while expression.same_parent and expression.is_wrapper:
1708            expression = t.cast(Subquery, expression.parent)
1709        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:
1711    def select(
1712        self,
1713        *expressions: ExpOrStr | None,
1714        append: bool = True,
1715        dialect: DialectType = None,
1716        copy: bool = True,
1717        **opts: Unpack[ParserNoDialectArgs],
1718    ) -> Subquery:
1719        this = maybe_copy(self, copy)
1720        inner = this.unnest()
1721        if hasattr(inner, "select"):
1722            inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1723        return this
is_wrapper: bool
1725    @property
1726    def is_wrapper(self) -> bool:
1727        """
1728        Whether this Subquery acts as a simple wrapper around another expression.
1729
1730        SELECT * FROM (((SELECT * FROM t)))
1731                      ^
1732                      This corresponds to a "wrapper" Subquery node
1733        """
1734        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
1736    @property
1737    def is_star(self) -> bool:
1738        return _is_star(self)

Checks whether an expression is a star.

output_name: str
1740    @property
1741    def output_name(self) -> str:
1742        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):
1745class TableSample(Expression):
1746    arg_types = {
1747        "expressions": False,
1748        "method": False,
1749        "bucket_numerator": False,
1750        "bucket_denominator": False,
1751        "bucket_field": False,
1752        "percent": False,
1753        "rows": False,
1754        "size": False,
1755        "seed": False,
1756    }
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):
1759class Tag(Expression):
1760    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
1761
1762    arg_types = {
1763        "this": False,
1764        "prefix": False,
1765        "postfix": False,
1766    }

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):
1769class Pivot(Expression):
1770    arg_types = {
1771        "this": False,
1772        "alias": False,
1773        "expressions": False,
1774        "fields": False,
1775        "unpivot": False,
1776        "using": False,
1777        "group": False,
1778        "columns": False,
1779        "include_nulls": False,
1780        "default_on_null": False,
1781        "into": False,
1782        "with_": False,
1783        "identify_pivot_strings": False,
1784        "prefixed_pivot_columns": False,
1785        "pivot_column_naming": False,
1786        "value_columns_first": False,
1787    }
1788
1789    @property
1790    def unpivot(self) -> bool:
1791        return bool(self.args.get("unpivot"))
1792
1793    @property
1794    def fields(self) -> list[Expr]:
1795        return self.args.get("fields", [])
1796
1797    def output_columns(self, pre_pivot_columns: t.Iterable[str]) -> dict[str, str]:
1798        """
1799        Returns an ordered map of post-rename output column name -> pre-rename
1800        source-side name, in the order the (UN)PIVOT produces them.
1801
1802        For callers that just want the names, iterate the dict (or call .keys()):
1803            >>> from sqlglot import parse_one, exp
1804            >>> piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot)
1805            >>> list(piv.output_columns(["a", "b", "c"]))
1806            ['c', 'name', 'val']
1807
1808        AST shape:
1809            PIVOT(SUM(val) FOR name IN ('a', 'b')):
1810                expressions: aggregate(s), e.g. [Sum(this=Column(val))]
1811                fields:      [In(this=Column(name), expressions=[Literal('a'), Literal('b')])]
1812                columns:     optional explicit output identifiers (e.g. set by Snowflake)
1813
1814            UNPIVOT(val FOR name IN (a, b)):
1815                expressions: value Identifier(s), or Tuple(Identifiers) for multi-value
1816                fields:      [In(this=Identifier(name), expressions=[Column(a), Column(b)])]
1817                             For literal-aliased entries (`a AS 'x'`) the IN expressions
1818                             are wrapped in PivotAlias(this=Column, alias=Literal).
1819
1820        Args:
1821            pre_pivot_columns: Columns visible to the operator before it runs
1822                (e.g. the source table or subquery's projections).
1823        """
1824        if self.unpivot:
1825            excluded: set[str] = set()
1826            name_columns: list[Identifier] = []
1827            for field in self.fields:
1828                if not isinstance(field, In):
1829                    continue
1830                if isinstance(field.this, Identifier):
1831                    name_columns.append(field.this)
1832                for e in field.expressions:
1833                    excluded.update(c.output_name for c in e.find_all(Column))
1834            value_columns = [
1835                ident
1836                for e in self.expressions
1837                for ident in (e.expressions if isinstance(e, Tuple) else [e])
1838                if isinstance(ident, Identifier)
1839            ]
1840            # T-SQL emits the value column(s) ahead of the name column, everyone else emits them after it
1841            ordered = (
1842                value_columns + name_columns
1843                if self.args.get("value_columns_first")
1844                else name_columns + value_columns
1845            )
1846            outputs = [i.name for i in ordered]
1847        else:
1848            excluded = {c.output_name for c in self.find_all(Column)}
1849            outputs = [c.output_name for c in self.args.get("columns") or []]
1850            if not outputs:
1851                outputs = [c.alias_or_name for c in self.expressions]
1852
1853        if not excluded or not outputs:
1854            return {}
1855
1856        pre_rename = [c for c in pre_pivot_columns if c not in excluded] + outputs
1857
1858        alias = self.args.get("alias")
1859        renames = alias.args.get("columns") if alias else None
1860
1861        # `PIVOT(...) AS alias(c1, c2, ...)` renames the operator's output columns
1862        # positionally from the front (DuckDB, Snowflake): the user's names cover
1863        # the leading N output columns, remaining columns keep their auto names.
1864        if renames:
1865            rename_names = [r.name for r in renames]
1866            post_rename = rename_names + pre_rename[len(rename_names) :]
1867        else:
1868            post_rename = pre_rename
1869
1870        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
1789    @property
1790    def unpivot(self) -> bool:
1791        return bool(self.args.get("unpivot"))
fields: list[sqlglot.expressions.core.Expr]
1793    @property
1794    def fields(self) -> list[Expr]:
1795        return self.args.get("fields", [])
def output_columns(self, pre_pivot_columns: Iterable[str]) -> dict[str, str]:
1797    def output_columns(self, pre_pivot_columns: t.Iterable[str]) -> dict[str, str]:
1798        """
1799        Returns an ordered map of post-rename output column name -> pre-rename
1800        source-side name, in the order the (UN)PIVOT produces them.
1801
1802        For callers that just want the names, iterate the dict (or call .keys()):
1803            >>> from sqlglot import parse_one, exp
1804            >>> piv = parse_one("SELECT * FROM t UNPIVOT(val FOR name IN (a, b))").find(exp.Pivot)
1805            >>> list(piv.output_columns(["a", "b", "c"]))
1806            ['c', 'name', 'val']
1807
1808        AST shape:
1809            PIVOT(SUM(val) FOR name IN ('a', 'b')):
1810                expressions: aggregate(s), e.g. [Sum(this=Column(val))]
1811                fields:      [In(this=Column(name), expressions=[Literal('a'), Literal('b')])]
1812                columns:     optional explicit output identifiers (e.g. set by Snowflake)
1813
1814            UNPIVOT(val FOR name IN (a, b)):
1815                expressions: value Identifier(s), or Tuple(Identifiers) for multi-value
1816                fields:      [In(this=Identifier(name), expressions=[Column(a), Column(b)])]
1817                             For literal-aliased entries (`a AS 'x'`) the IN expressions
1818                             are wrapped in PivotAlias(this=Column, alias=Literal).
1819
1820        Args:
1821            pre_pivot_columns: Columns visible to the operator before it runs
1822                (e.g. the source table or subquery's projections).
1823        """
1824        if self.unpivot:
1825            excluded: set[str] = set()
1826            name_columns: list[Identifier] = []
1827            for field in self.fields:
1828                if not isinstance(field, In):
1829                    continue
1830                if isinstance(field.this, Identifier):
1831                    name_columns.append(field.this)
1832                for e in field.expressions:
1833                    excluded.update(c.output_name for c in e.find_all(Column))
1834            value_columns = [
1835                ident
1836                for e in self.expressions
1837                for ident in (e.expressions if isinstance(e, Tuple) else [e])
1838                if isinstance(ident, Identifier)
1839            ]
1840            # T-SQL emits the value column(s) ahead of the name column, everyone else emits them after it
1841            ordered = (
1842                value_columns + name_columns
1843                if self.args.get("value_columns_first")
1844                else name_columns + value_columns
1845            )
1846            outputs = [i.name for i in ordered]
1847        else:
1848            excluded = {c.output_name for c in self.find_all(Column)}
1849            outputs = [c.output_name for c in self.args.get("columns") or []]
1850            if not outputs:
1851                outputs = [c.alias_or_name for c in self.expressions]
1852
1853        if not excluded or not outputs:
1854            return {}
1855
1856        pre_rename = [c for c in pre_pivot_columns if c not in excluded] + outputs
1857
1858        alias = self.args.get("alias")
1859        renames = alias.args.get("columns") if alias else None
1860
1861        # `PIVOT(...) AS alias(c1, c2, ...)` renames the operator's output columns
1862        # positionally from the front (DuckDB, Snowflake): the user's names cover
1863        # the leading N output columns, remaining columns keep their auto names.
1864        if renames:
1865            rename_names = [r.name for r in renames]
1866            post_rename = rename_names + pre_rename[len(rename_names) :]
1867        else:
1868            post_rename = pre_rename
1869
1870        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):
1873class UnpivotColumns(Expression):
1874    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key: ClassVar[str] = 'unpivotcolumns'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
1877class Window(Expression, Condition):
1878    arg_types = {
1879        "this": True,
1880        "partition_by": False,
1881        "order": False,
1882        "spec": False,
1883        "alias": False,
1884        "over": False,
1885        "first": False,
1886    }
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):
1889class WindowSpec(Expression):
1890    arg_types = {
1891        "kind": False,
1892        "start": False,
1893        "start_side": False,
1894        "end": False,
1895        "end_side": False,
1896        "exclude": False,
1897    }
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 PreWhere(sqlglot.expressions.core.Expression):
1900class PreWhere(Expression):
1901    pass
key: ClassVar[str] = 'prewhere'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Where(sqlglot.expressions.core.Expression):
1904class Where(Expression):
1905    pass
key: ClassVar[str] = 'where'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Analyze(sqlglot.expressions.core.Expression):
1908class Analyze(Expression):
1909    arg_types = {
1910        "kind": False,
1911        "tables": False,
1912        "options": False,
1913        "mode": False,
1914        "partition": False,
1915        "expression": False,
1916        "properties": False,
1917    }
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):
1920class AnalyzeStatistics(Expression):
1921    arg_types = {
1922        "kind": True,
1923        "option": False,
1924        "this": False,
1925        "expressions": False,
1926    }
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):
1929class AnalyzeHistogram(Expression):
1930    arg_types = {
1931        "this": True,
1932        "expressions": True,
1933        "expression": False,
1934        "update_options": False,
1935    }
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):
1938class AnalyzeSample(Expression):
1939    arg_types = {"kind": True, "sample": True}
arg_types = {'kind': True, 'sample': True}
key: ClassVar[str] = 'analyzesample'
required_args: 't.ClassVar[set[str]]' = {'kind', 'sample'}
class AnalyzeListChainedRows(sqlglot.expressions.core.Expression):
1942class AnalyzeListChainedRows(Expression):
1943    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):
1946class AnalyzeDelete(Expression):
1947    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):
1950class AnalyzeWith(Expression):
1951    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):
1954class AnalyzeValidate(Expression):
1955    arg_types = {
1956        "kind": True,
1957        "this": False,
1958        "expression": False,
1959    }
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):
1962class AnalyzeColumns(Expression):
1963    pass
key: ClassVar[str] = 'analyzecolumns'
required_args: 't.ClassVar[set[str]]' = {'this'}
class UsingData(sqlglot.expressions.core.Expression):
1966class UsingData(Expression):
1967    pass
key: ClassVar[str] = 'usingdata'
required_args: 't.ClassVar[set[str]]' = {'this'}
class AddPartition(sqlglot.expressions.core.Expression):
1970class AddPartition(Expression):
1971    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):
1974class AttachOption(Expression):
1975    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):
1978class DropPartition(Expression):
1979    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key: ClassVar[str] = 'droppartition'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class ReplacePartition(sqlglot.expressions.core.Expression):
1982class ReplacePartition(Expression):
1983    arg_types = {"expression": True, "source": True}
arg_types = {'expression': True, 'source': True}
key: ClassVar[str] = 'replacepartition'
required_args: 't.ClassVar[set[str]]' = {'expression', 'source'}
class TranslateCharacters(sqlglot.expressions.core.Expression):
1986class TranslateCharacters(Expression):
1987    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):
1990class OverflowTruncateBehavior(Expression):
1991    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):
1994class JSON(Expression):
1995    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):
1998class JSONPath(Expression):
1999    arg_types = {"expressions": True}
2000
2001    @property
2002    def output_name(self) -> str:
2003        last_segment = self.expressions[-1].this
2004        return last_segment if isinstance(last_segment, str) else ""
arg_types = {'expressions': True}
output_name: str
2001    @property
2002    def output_name(self) -> str:
2003        last_segment = self.expressions[-1].this
2004        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):
2007class JSONPathPart(Expression):
2008    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'jsonpathpart'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathFilter(JSONPathPart):
2011class JSONPathFilter(JSONPathPart):
2012    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathfilter'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathKey(JSONPathPart):
2015class JSONPathKey(JSONPathPart):
2016    arg_types = {"this": True, "quoted": False}
arg_types = {'this': True, 'quoted': False}
key: ClassVar[str] = 'jsonpathkey'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathRecursive(JSONPathPart):
2019class JSONPathRecursive(JSONPathPart):
2020    arg_types = {"this": False}
arg_types = {'this': False}
key: ClassVar[str] = 'jsonpathrecursive'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathRoot(JSONPathPart):
2023class JSONPathRoot(JSONPathPart):
2024    pass
key: ClassVar[str] = 'jsonpathroot'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathScript(JSONPathPart):
2027class JSONPathScript(JSONPathPart):
2028    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathscript'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathSlice(JSONPathPart):
2031class JSONPathSlice(JSONPathPart):
2032    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):
2035class JSONPathSelector(JSONPathPart):
2036    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathselector'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathSubscript(JSONPathPart):
2039class JSONPathSubscript(JSONPathPart):
2040    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathsubscript'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathUnion(JSONPathPart):
2043class JSONPathUnion(JSONPathPart):
2044    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'jsonpathunion'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class JSONPathWildcard(JSONPathPart):
2047class JSONPathWildcard(JSONPathPart):
2048    pass
key: ClassVar[str] = 'jsonpathwildcard'
required_args: 't.ClassVar[set[str]]' = set()
class FormatJson(sqlglot.expressions.core.Expression):
2051class FormatJson(Expression):
2052    pass
key: ClassVar[str] = 'formatjson'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONKeyValue(sqlglot.expressions.core.Expression):
2055class JSONKeyValue(Expression):
2056    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):
2059class JSONColumnDef(Expression):
2060    arg_types = {
2061        "this": False,
2062        "kind": False,
2063        "path": False,
2064        "nested_schema": False,
2065        "ordinality": False,
2066        "format_json": False,
2067    }
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):
2070class JSONSchema(Expression):
2071    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):
2074class JSONValue(Expression):
2075    arg_types = {
2076        "this": True,
2077        "path": True,
2078        "returning": False,
2079        "on_condition": False,
2080    }
arg_types = {'this': True, 'path': True, 'returning': False, 'on_condition': False}
key: ClassVar[str] = 'jsonvalue'
required_args: 't.ClassVar[set[str]]' = {'path', 'this'}
2083class JSONValueArray(Expression, Func):
2084    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):
2087class OpenJSONColumnDef(Expression):
2088    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):
2091class JSONExtractQuote(Expression):
2092    arg_types = {
2093        "option": True,
2094        "scalar": False,
2095    }
arg_types = {'option': True, 'scalar': False}
key: ClassVar[str] = 'jsonextractquote'
required_args: 't.ClassVar[set[str]]' = {'option'}
class ScopeResolution(sqlglot.expressions.core.Expression):
2098class ScopeResolution(Expression):
2099    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):
2102class Stream(Expression):
2103    pass
key: ClassVar[str] = 'stream'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ModelAttribute(sqlglot.expressions.core.Expression):
2106class ModelAttribute(Expression):
2107    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):
2110class XMLNamespace(Expression):
2111    pass
key: ClassVar[str] = 'xmlnamespace'
required_args: 't.ClassVar[set[str]]' = {'this'}
class XMLKeyValueOption(sqlglot.expressions.core.Expression):
2114class XMLKeyValueOption(Expression):
2115    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):
2118class Semicolon(Expression):
2119    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'semicolon'
required_args: 't.ClassVar[set[str]]' = set()
class TableColumn(sqlglot.expressions.core.Expression):
2122class TableColumn(Expression):
2123    @property
2124    def output_name(self) -> str:
2125        return self.name
output_name: str
2123    @property
2124    def output_name(self) -> str:
2125        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):
2128class Variadic(Expression):
2129    pass
key: ClassVar[str] = 'variadic'
required_args: 't.ClassVar[set[str]]' = {'this'}
class StoredProcedure(sqlglot.expressions.core.Expression):
2132class StoredProcedure(Expression):
2133    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):
2136class Block(Expression):
2137    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):
2140class IfBlock(Expression):
2141    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):
2144class CaseStatement(Expression):
2145    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):
2148class WhileBlock(Expression):
2149    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):
2152class LoopBlock(Expression):
2153    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):
2156class RepeatBlock(Expression):
2157    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):
2160class Leave(Expression):
2161    pass
key: ClassVar[str] = 'leave'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Iterate(sqlglot.expressions.core.Expression):
2164class Iterate(Expression):
2165    pass
key: ClassVar[str] = 'iterate'
required_args: 't.ClassVar[set[str]]' = {'this'}
class EndStatement(sqlglot.expressions.core.Expression):
2168class EndStatement(Expression):
2169    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'endstatement'
required_args: 't.ClassVar[set[str]]' = set()
class FunctionSpecification(sqlglot.expressions.core.Expression):
2173class FunctionSpecification(Expression):
2174    arg_types = {
2175        "this": True,
2176        "characteristics": False,
2177        "properties": False,
2178        "expression": True,
2179    }
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:
2185def union(
2186    *expressions: ExpOrStr,
2187    distinct: bool = True,
2188    dialect: DialectType = None,
2189    copy: bool = True,
2190    **opts: Unpack[ParserNoDialectArgs],
2191) -> Union:
2192    """
2193    Initializes a syntax tree for the `UNION` operation.
2194
2195    Example:
2196        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
2197        'SELECT * FROM foo UNION SELECT * FROM bla'
2198
2199    Args:
2200        expressions: the SQL code strings, corresponding to the `UNION`'s operands.
2201            If `Expr` instances are passed, they will be used as-is.
2202        distinct: set the DISTINCT flag if and only if this is true.
2203        dialect: the dialect used to parse the input expression.
2204        copy: whether to copy the expression.
2205        opts: other options to use to parse the input expressions.
2206
2207    Returns:
2208        The new Union instance.
2209    """
2210    assert len(expressions) >= 2, "At least two expressions are required by `union`."
2211    return _apply_set_operation(
2212        *expressions, set_operation=Union, distinct=distinct, dialect=dialect, copy=copy, **opts
2213    )

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:
2216def intersect(
2217    *expressions: ExpOrStr,
2218    distinct: bool = True,
2219    dialect: DialectType = None,
2220    copy: bool = True,
2221    **opts: Unpack[ParserNoDialectArgs],
2222) -> Intersect:
2223    """
2224    Initializes a syntax tree for the `INTERSECT` operation.
2225
2226    Example:
2227        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
2228        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
2229
2230    Args:
2231        expressions: the SQL code strings, corresponding to the `INTERSECT`'s operands.
2232            If `Expr` instances are passed, they will be used as-is.
2233        distinct: set the DISTINCT flag if and only if this is true.
2234        dialect: the dialect used to parse the input expression.
2235        copy: whether to copy the expression.
2236        opts: other options to use to parse the input expressions.
2237
2238    Returns:
2239        The new Intersect instance.
2240    """
2241    assert len(expressions) >= 2, "At least two expressions are required by `intersect`."
2242    return _apply_set_operation(
2243        *expressions, set_operation=Intersect, distinct=distinct, dialect=dialect, copy=copy, **opts
2244    )

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:
2247def except_(
2248    *expressions: ExpOrStr,
2249    distinct: bool = True,
2250    dialect: DialectType = None,
2251    copy: bool = True,
2252    **opts: Unpack[ParserNoDialectArgs],
2253) -> Except:
2254    """
2255    Initializes a syntax tree for the `EXCEPT` operation.
2256
2257    Example:
2258        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
2259        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
2260
2261    Args:
2262        expressions: the SQL code strings, corresponding to the `EXCEPT`'s operands.
2263            If `Expr` instances are passed, they will be used as-is.
2264        distinct: set the DISTINCT flag if and only if this is true.
2265        dialect: the dialect used to parse the input expression.
2266        copy: whether to copy the expression.
2267        opts: other options to use to parse the input expressions.
2268
2269    Returns:
2270        The new Except instance.
2271    """
2272    assert len(expressions) >= 2, "At least two expressions are required by `except_`."
2273    return _apply_set_operation(
2274        *expressions, set_operation=Except, distinct=distinct, dialect=dialect, copy=copy, **opts
2275    )

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.