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

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

ctes: list[CTE]
115    @property
116    def ctes(self) -> list[CTE]:
117        with_ = self.args.get("with_")
118        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:
120    def select(
121        self: Q,
122        *expressions: ExpOrStr | None,
123        append: bool = True,
124        dialect: DialectType = None,
125        copy: bool = True,
126        **opts: Unpack[ParserNoDialectArgs],
127    ) -> Q:
128        raise NotImplementedError("Query objects must implement `select`")
def subquery( self, alias: Union[int, str, sqlglot.expressions.core.Expr, NoneType] = None, copy: bool = True) -> Subquery:
130    def subquery(self, alias: ExpOrStr | None = None, copy: bool = True) -> Subquery:
131        """
132        Returns a `Subquery` that wraps around this query.
133
134        Example:
135            >>> subquery = Select().select("x").from_("tbl").subquery()
136            >>> Select().select("x").from_(subquery).sql()
137            'SELECT x FROM (SELECT x FROM tbl)'
138
139        Args:
140            alias: an optional alias for the subquery.
141            copy: if `False`, modify this expression instance in-place.
142        """
143        instance = maybe_copy(self, copy)
144        if not isinstance(alias, Expr):
145            alias = TableAlias(this=to_identifier(alias)) if alias else None
146
147        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:
149    def limit(
150        self: Q,
151        expression: ExpOrStr | int,
152        dialect: DialectType = None,
153        copy: bool = True,
154        **opts: Unpack[ParserNoDialectArgs],
155    ) -> Q:
156        """
157        Adds a LIMIT clause to this query.
158
159        Example:
160            >>> Select().select("1").union(Select().select("1")).limit(1).sql()
161            'SELECT 1 UNION SELECT 1 LIMIT 1'
162
163        Args:
164            expression: the SQL code string to parse.
165                This can also be an integer.
166                If a `Limit` instance is passed, it will be used as-is.
167                If another `Expr` instance is passed, it will be wrapped in a `Limit`.
168            dialect: the dialect used to parse the input expression.
169            copy: if `False`, modify this expression instance in-place.
170            opts: other options to use to parse the input expressions.
171
172        Returns:
173            A limited Select expression.
174        """
175        return _apply_builder(
176            expression=expression,
177            instance=self,
178            arg="limit",
179            into=Limit,
180            prefix="LIMIT",
181            dialect=dialect,
182            copy=copy,
183            into_arg="expression",
184            **opts,
185        )

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

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

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

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

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:
353    def union(
354        self,
355        *expressions: ExpOrStr,
356        distinct: bool = True,
357        dialect: DialectType = None,
358        copy: bool = True,
359        **opts: Unpack[ParserNoDialectArgs],
360    ) -> Union:
361        """
362        Builds a UNION expression.
363
364        Example:
365            >>> import sqlglot
366            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
367            'SELECT * FROM foo UNION SELECT * FROM bla'
368
369        Args:
370            expressions: the SQL code strings.
371                If `Expr` instances are passed, they will be used as-is.
372            distinct: set the DISTINCT flag if and only if this is true.
373            dialect: the dialect used to parse the input expression.
374            opts: other options to use to parse the input expressions.
375
376        Returns:
377            The new Union expression.
378        """
379        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:
381    def intersect(
382        self,
383        *expressions: ExpOrStr,
384        distinct: bool = True,
385        dialect: DialectType = None,
386        copy: bool = True,
387        **opts: Unpack[ParserNoDialectArgs],
388    ) -> Intersect:
389        """
390        Builds an INTERSECT expression.
391
392        Example:
393            >>> import sqlglot
394            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
395            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
396
397        Args:
398            expressions: the SQL code strings.
399                If `Expr` instances are passed, they will be used as-is.
400            distinct: set the DISTINCT flag if and only if this is true.
401            dialect: the dialect used to parse the input expression.
402            opts: other options to use to parse the input expressions.
403
404        Returns:
405            The new Intersect expression.
406        """
407        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:
409    def except_(
410        self,
411        *expressions: ExpOrStr,
412        distinct: bool = True,
413        dialect: DialectType = None,
414        copy: bool = True,
415        **opts: Unpack[ParserNoDialectArgs],
416    ) -> Except:
417        """
418        Builds an EXCEPT expression.
419
420        Example:
421            >>> import sqlglot
422            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
423            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
424
425        Args:
426            expressions: the SQL code strings.
427                If `Expr` instance are passed, they will be used as-is.
428            distinct: set the DISTINCT flag if and only if this is true.
429            dialect: the dialect used to parse the input expression.
430            opts: other options to use to parse the input expressions.
431
432        Returns:
433            The new Except expression.
434        """
435        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):
438class QueryBand(Expression):
439    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):
442class RecursiveWithSearch(Expression):
443    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]]' = {'this', 'expression', 'kind'}
class With(sqlglot.expressions.core.Expression):
446class With(Expression):
447    arg_types = {"expressions": True, "recursive": False, "search": False}
448
449    @property
450    def recursive(self) -> bool:
451        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False, 'search': False}
recursive: bool
449    @property
450    def recursive(self) -> bool:
451        return bool(self.args.get("recursive"))
key: ClassVar[str] = 'with'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
454class CTE(Expression, DerivedTable):
455    arg_types = {
456        "this": True,
457        "alias": True,
458        "scalar": False,
459        "materialized": False,
460        "key_expressions": False,
461    }
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):
464class ProjectionDef(Expression):
465    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):
468class TableAlias(Expression):
469    arg_types = {"this": False, "columns": False}
470
471    @property
472    def columns(self) -> list[t.Any]:
473        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns: list[typing.Any]
471    @property
472    def columns(self) -> list[t.Any]:
473        return self.args.get("columns") or []
key: ClassVar[str] = 'tablealias'
required_args: 't.ClassVar[set[str]]' = set()
476class BitString(Expression, Condition):
477    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'bitstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
480class HexString(Expression, Condition):
481    arg_types = {"this": True, "is_integer": False}
482    is_primitive = True
arg_types = {'this': True, 'is_integer': False}
is_primitive = True
key: ClassVar[str] = 'hexstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
485class ByteString(Expression, Condition):
486    arg_types = {"this": True, "is_bytes": False}
487    is_primitive = True
arg_types = {'this': True, 'is_bytes': False}
is_primitive = True
key: ClassVar[str] = 'bytestring'
required_args: 't.ClassVar[set[str]]' = {'this'}
490class RawString(Expression, Condition):
491    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'rawstring'
required_args: 't.ClassVar[set[str]]' = {'this'}
494class UnicodeString(Expression, Condition):
495    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):
498class ColumnPosition(Expression):
499    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):
502class ColumnDef(Expression):
503    arg_types = {
504        "this": True,
505        "kind": False,
506        "constraints": False,
507        "exists": False,
508        "position": False,
509        "default": False,
510        "output": False,
511    }
512
513    @property
514    def constraints(self) -> list[ColumnConstraint]:
515        return self.args.get("constraints") or []
516
517    @property
518    def kind(self) -> DataType | None:
519        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]
513    @property
514    def constraints(self) -> list[ColumnConstraint]:
515        return self.args.get("constraints") or []
kind: sqlglot.expressions.datatypes.DataType | None
517    @property
518    def kind(self) -> DataType | None:
519        return self.args.get("kind")
key: ClassVar[str] = 'columndef'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Changes(sqlglot.expressions.core.Expression):
522class Changes(Expression):
523    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):
526class Connect(Expression):
527    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):
530class Prior(Expression):
531    pass
key: ClassVar[str] = 'prior'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Into(sqlglot.expressions.core.Expression):
534class Into(Expression):
535    arg_types = {
536        "this": False,
537        "temporary": False,
538        "unlogged": False,
539        "bulk_collect": False,
540        "expressions": False,
541    }
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):
544class From(Expression):
545    @property
546    def name(self) -> str:
547        return self.this.name
548
549    @property
550    def alias_or_name(self) -> str:
551        return self.this.alias_or_name
name: str
545    @property
546    def name(self) -> str:
547        return self.this.name
alias_or_name: str
549    @property
550    def alias_or_name(self) -> str:
551        return self.this.alias_or_name
key: ClassVar[str] = 'from'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Having(sqlglot.expressions.core.Expression):
554class Having(Expression):
555    pass
key: ClassVar[str] = 'having'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Index(sqlglot.expressions.core.Expression):
558class Index(Expression):
559    arg_types = {
560        "this": False,
561        "table": False,
562        "unique": False,
563        "primary": False,
564        "amp": False,  # teradata
565        "params": False,
566    }
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):
569class ConditionalInsert(Expression):
570    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):
573class MultitableInserts(Expression):
574    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', 'source', 'kind'}
class OnCondition(sqlglot.expressions.core.Expression):
577class OnCondition(Expression):
578    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):
581class Introducer(Expression):
582    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):
585class National(Expression):
586    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'national'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Partition(sqlglot.expressions.core.Expression):
589class Partition(Expression):
590    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):
593class PartitionRange(Expression):
594    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):
597class PartitionId(Expression):
598    pass
key: ClassVar[str] = 'partitionid'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Fetch(sqlglot.expressions.core.Expression):
601class Fetch(Expression):
602    arg_types = {
603        "direction": False,
604        "count": False,
605        "limit_options": False,
606    }
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):
609class Grant(Expression):
610    arg_types = {
611        "privileges": True,
612        "kind": False,
613        "securable": True,
614        "principals": True,
615        "grant_option": False,
616    }
arg_types = {'privileges': True, 'kind': False, 'securable': True, 'principals': True, 'grant_option': False}
key: ClassVar[str] = 'grant'
required_args: 't.ClassVar[set[str]]' = {'privileges', 'securable', 'principals'}
class Revoke(sqlglot.expressions.core.Expression):
619class Revoke(Expression):
620    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', 'securable', 'principals'}
class Group(sqlglot.expressions.core.Expression):
623class Group(Expression):
624    arg_types = {
625        "expressions": False,
626        "grouping_sets": False,
627        "cube": False,
628        "rollup": False,
629        "totals": False,
630        "all": False,
631    }
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):
634class Cube(Expression):
635    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):
638class Rollup(Expression):
639    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):
642class GroupingSets(Expression):
643    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):
646class Lambda(Expression):
647    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):
650class Limit(Expression):
651    arg_types = {
652        "this": False,
653        "expression": True,
654        "offset": False,
655        "limit_options": False,
656        "expressions": False,
657    }
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):
660class LimitOptions(Expression):
661    arg_types = {
662        "percent": False,
663        "rows": False,
664        "with_ties": False,
665    }
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):
668class Join(Expression):
669    arg_types = {
670        "this": True,
671        "on": False,
672        "side": False,
673        "kind": False,
674        "using": False,
675        "method": False,
676        "global_": False,
677        "hint": False,
678        "match_condition": False,  # Snowflake
679        "directed": False,  # Snowflake
680        "expressions": False,
681        "pivots": False,
682    }
683
684    @property
685    def method(self) -> str:
686        return self.text("method").upper()
687
688    @property
689    def kind(self) -> str:
690        return self.text("kind").upper()
691
692    @property
693    def side(self) -> str:
694        return self.text("side").upper()
695
696    @property
697    def hint(self) -> str:
698        return self.text("hint").upper()
699
700    @property
701    def alias_or_name(self) -> str:
702        return self.this.alias_or_name
703
704    @property
705    def is_semi_or_anti_join(self) -> bool:
706        return self.kind in ("SEMI", "ANTI")
707
708    def on(
709        self,
710        *expressions: ExpOrStr | None,
711        append: bool = True,
712        dialect: DialectType = None,
713        copy: bool = True,
714        **opts: Unpack[ParserNoDialectArgs],
715    ) -> Join:
716        """
717        Append to or set the ON expressions.
718
719        Example:
720            >>> import sqlglot
721            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
722            'JOIN x ON y = 1'
723
724        Args:
725            *expressions: the SQL code strings to parse.
726                If an `Expr` instance is passed, it will be used as-is.
727                Multiple expressions are combined with an AND operator.
728            append: if `True`, AND the new expressions to any existing expression.
729                Otherwise, this resets the expression.
730            dialect: the dialect used to parse the input expressions.
731            copy: if `False`, modify this expression instance in-place.
732            opts: other options to use to parse the input expressions.
733
734        Returns:
735            The modified Join expression.
736        """
737        join = _apply_conjunction_builder(
738            *expressions,
739            instance=self,
740            arg="on",
741            append=append,
742            dialect=dialect,
743            copy=copy,
744            **opts,
745        )
746
747        if join.kind == "CROSS":
748            join.set("kind", None)
749
750        return join
751
752    def using(
753        self,
754        *expressions: ExpOrStr | None,
755        append: bool = True,
756        dialect: DialectType = None,
757        copy: bool = True,
758        **opts: Unpack[ParserNoDialectArgs],
759    ) -> Join:
760        """
761        Append to or set the USING expressions.
762
763        Example:
764            >>> import sqlglot
765            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
766            'JOIN x USING (foo, bla)'
767
768        Args:
769            *expressions: the SQL code strings to parse.
770                If an `Expr` instance is passed, it will be used as-is.
771            append: if `True`, concatenate the new expressions to the existing "using" list.
772                Otherwise, this resets the expression.
773            dialect: the dialect used to parse the input expressions.
774            copy: if `False`, modify this expression instance in-place.
775            opts: other options to use to parse the input expressions.
776
777        Returns:
778            The modified Join expression.
779        """
780        join = _apply_list_builder(
781            *expressions,
782            instance=self,
783            arg="using",
784            append=append,
785            dialect=dialect,
786            copy=copy,
787            **opts,
788        )
789
790        if join.kind == "CROSS":
791            join.set("kind", None)
792
793        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
684    @property
685    def method(self) -> str:
686        return self.text("method").upper()
kind: str
688    @property
689    def kind(self) -> str:
690        return self.text("kind").upper()
side: str
692    @property
693    def side(self) -> str:
694        return self.text("side").upper()
hint: str
696    @property
697    def hint(self) -> str:
698        return self.text("hint").upper()
alias_or_name: str
700    @property
701    def alias_or_name(self) -> str:
702        return self.this.alias_or_name
is_semi_or_anti_join: bool
704    @property
705    def is_semi_or_anti_join(self) -> bool:
706        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:
708    def on(
709        self,
710        *expressions: ExpOrStr | None,
711        append: bool = True,
712        dialect: DialectType = None,
713        copy: bool = True,
714        **opts: Unpack[ParserNoDialectArgs],
715    ) -> Join:
716        """
717        Append to or set the ON expressions.
718
719        Example:
720            >>> import sqlglot
721            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
722            'JOIN x ON y = 1'
723
724        Args:
725            *expressions: the SQL code strings to parse.
726                If an `Expr` instance is passed, it will be used as-is.
727                Multiple expressions are combined with an AND operator.
728            append: if `True`, AND the new expressions to any existing expression.
729                Otherwise, this resets the expression.
730            dialect: the dialect used to parse the input expressions.
731            copy: if `False`, modify this expression instance in-place.
732            opts: other options to use to parse the input expressions.
733
734        Returns:
735            The modified Join expression.
736        """
737        join = _apply_conjunction_builder(
738            *expressions,
739            instance=self,
740            arg="on",
741            append=append,
742            dialect=dialect,
743            copy=copy,
744            **opts,
745        )
746
747        if join.kind == "CROSS":
748            join.set("kind", None)
749
750        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:
752    def using(
753        self,
754        *expressions: ExpOrStr | None,
755        append: bool = True,
756        dialect: DialectType = None,
757        copy: bool = True,
758        **opts: Unpack[ParserNoDialectArgs],
759    ) -> Join:
760        """
761        Append to or set the USING expressions.
762
763        Example:
764            >>> import sqlglot
765            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
766            'JOIN x USING (foo, bla)'
767
768        Args:
769            *expressions: the SQL code strings to parse.
770                If an `Expr` instance is passed, it will be used as-is.
771            append: if `True`, concatenate the new expressions to the existing "using" list.
772                Otherwise, this resets the expression.
773            dialect: the dialect used to parse the input expressions.
774            copy: if `False`, modify this expression instance in-place.
775            opts: other options to use to parse the input expressions.
776
777        Returns:
778            The modified Join expression.
779        """
780        join = _apply_list_builder(
781            *expressions,
782            instance=self,
783            arg="using",
784            append=append,
785            dialect=dialect,
786            copy=copy,
787            **opts,
788        )
789
790        if join.kind == "CROSS":
791            join.set("kind", None)
792
793        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):
796class Lateral(Expression, UDTF):
797    arg_types = {
798        "this": True,
799        "view": False,
800        "outer": False,
801        "alias": False,
802        "cross_apply": False,  # True -> CROSS APPLY, False -> OUTER APPLY
803        "ordinality": False,
804    }
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):
807class TableFromRows(Expression, UDTF):
808    arg_types = {
809        "this": True,
810        "alias": False,
811        "joins": False,
812        "pivots": False,
813        "sample": False,
814    }
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):
817class MatchRecognizeMeasure(Expression):
818    arg_types = {
819        "this": True,
820        "window_frame": False,
821    }
arg_types = {'this': True, 'window_frame': False}
key: ClassVar[str] = 'matchrecognizemeasure'
required_args: 't.ClassVar[set[str]]' = {'this'}
class MatchRecognize(sqlglot.expressions.core.Expression):
824class MatchRecognize(Expression):
825    arg_types = {
826        "partition_by": False,
827        "order": False,
828        "measures": False,
829        "rows": False,
830        "after": False,
831        "pattern": False,
832        "define": False,
833        "alias": False,
834    }
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):
837class Final(Expression):
838    pass
key: ClassVar[str] = 'final'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Offset(sqlglot.expressions.core.Expression):
841class Offset(Expression):
842    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):
845class Order(Expression):
846    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):
849class WithFill(Expression):
850    arg_types = {
851        "from_": False,
852        "to": False,
853        "step": False,
854        "interpolate": False,
855    }
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):
858class SkipJSONColumn(Expression):
859    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(Order):
862class Cluster(Order):
863    pass
key: ClassVar[str] = 'cluster'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Distribute(Order):
866class Distribute(Order):
867    pass
key: ClassVar[str] = 'distribute'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Sort(Order):
870class Sort(Order):
871    pass
key: ClassVar[str] = 'sort'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class Qualify(sqlglot.expressions.core.Expression):
874class Qualify(Expression):
875    pass
key: ClassVar[str] = 'qualify'
required_args: 't.ClassVar[set[str]]' = {'this'}
class InputOutputFormat(sqlglot.expressions.core.Expression):
878class InputOutputFormat(Expression):
879    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):
882class Return(Expression):
883    pass
key: ClassVar[str] = 'return'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Tuple(sqlglot.expressions.core.Expression):
886class Tuple(Expression):
887    arg_types = {"expressions": False}
888
889    def isin(
890        self,
891        *expressions: t.Any,
892        query: ExpOrStr | None = None,
893        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
894        copy: bool = True,
895        **opts: Unpack[ParserArgs],
896    ) -> In:
897        return In(
898            this=maybe_copy(self, copy),
899            expressions=[convert(e, copy=copy) for e in expressions],
900            query=maybe_parse(query, copy=copy, **opts) if query else None,
901            unnest=(
902                Unnest(
903                    expressions=[
904                        maybe_parse(e, copy=copy, **opts)
905                        for e in t.cast(list[ExpOrStr], ensure_list(unnest))
906                    ]
907                )
908                if unnest
909                else None
910            ),
911        )
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:
889    def isin(
890        self,
891        *expressions: t.Any,
892        query: ExpOrStr | None = None,
893        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
894        copy: bool = True,
895        **opts: Unpack[ParserArgs],
896    ) -> In:
897        return In(
898            this=maybe_copy(self, copy),
899            expressions=[convert(e, copy=copy) for e in expressions],
900            query=maybe_parse(query, copy=copy, **opts) if query else None,
901            unnest=(
902                Unnest(
903                    expressions=[
904                        maybe_parse(e, copy=copy, **opts)
905                        for e in t.cast(list[ExpOrStr], ensure_list(unnest))
906                    ]
907                )
908                if unnest
909                else None
910            ),
911        )
key: ClassVar[str] = 'tuple'
required_args: 't.ClassVar[set[str]]' = set()
class QueryOption(sqlglot.expressions.core.Expression):
914class QueryOption(Expression):
915    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key: ClassVar[str] = 'queryoption'
required_args: 't.ClassVar[set[str]]' = {'this'}
class WithTableHint(sqlglot.expressions.core.Expression):
918class WithTableHint(Expression):
919    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):
922class IndexTableHint(Expression):
923    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):
926class HistoricalData(Expression):
927    arg_types = {"this": True, "kind": True, "expression": True}
arg_types = {'this': True, 'kind': True, 'expression': True}
key: ClassVar[str] = 'historicaldata'
required_args: 't.ClassVar[set[str]]' = {'kind', 'expression', 'this'}
class Put(sqlglot.expressions.core.Expression):
930class Put(Expression):
931    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):
934class Get(Expression):
935    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):
 938class Table(Expression, Selectable):
 939    arg_types = {
 940        "this": False,
 941        "alias": False,
 942        "db": False,
 943        "catalog": False,
 944        "laterals": False,
 945        "joins": False,
 946        "pivots": False,
 947        "hints": False,
 948        "system_time": False,
 949        "version": False,
 950        "format": False,
 951        "pattern": False,
 952        "ordinality": False,
 953        "when": False,
 954        "only": False,
 955        "partition": False,
 956        "changes": False,
 957        "rows_from": False,
 958        "sample": False,
 959        "indexed": False,
 960    }
 961
 962    @property
 963    def name(self) -> str:
 964        if not self.this or isinstance(self.this, Func):
 965            return ""
 966        return self.this.name
 967
 968    @property
 969    def db(self) -> str:
 970        return self.text("db")
 971
 972    @property
 973    def catalog(self) -> str:
 974        return self.text("catalog")
 975
 976    @property
 977    def selects(self) -> list[Expr]:
 978        return []
 979
 980    @property
 981    def named_selects(self) -> list[str]:
 982        return []
 983
 984    @property
 985    def parts(self) -> list[Expr]:
 986        """Return the parts of a table in order catalog, db, table."""
 987        parts: list[Expr] = []
 988
 989        for arg in ("catalog", "db", "this"):
 990            part = self.args.get(arg)
 991
 992            if isinstance(part, Dot):
 993                parts.extend(part.flatten())
 994            elif isinstance(part, Expr):
 995                parts.append(part)
 996
 997        return parts
 998
 999    def to_column(self, copy: bool = True) -> Expr:
1000        parts = self.parts
1001        last_part = parts[-1]
1002
1003        if isinstance(last_part, Identifier):
1004            col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy)  # type: ignore
1005        else:
1006            # This branch will be reached if a function or array is wrapped in a `Table`
1007            col = last_part
1008
1009        alias = self.args.get("alias")
1010        if alias:
1011            col = alias_(col, alias.this, copy=copy)
1012
1013        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
962    @property
963    def name(self) -> str:
964        if not self.this or isinstance(self.this, Func):
965            return ""
966        return self.this.name
db: str
968    @property
969    def db(self) -> str:
970        return self.text("db")
catalog: str
972    @property
973    def catalog(self) -> str:
974        return self.text("catalog")
selects: list[sqlglot.expressions.core.Expr]
976    @property
977    def selects(self) -> list[Expr]:
978        return []
named_selects: list[str]
980    @property
981    def named_selects(self) -> list[str]:
982        return []
parts: list[sqlglot.expressions.core.Expr]
984    @property
985    def parts(self) -> list[Expr]:
986        """Return the parts of a table in order catalog, db, table."""
987        parts: list[Expr] = []
988
989        for arg in ("catalog", "db", "this"):
990            part = self.args.get(arg)
991
992            if isinstance(part, Dot):
993                parts.extend(part.flatten())
994            elif isinstance(part, Expr):
995                parts.append(part)
996
997        return parts

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

def to_column(self, copy: bool = True) -> sqlglot.expressions.core.Expr:
 999    def to_column(self, copy: bool = True) -> Expr:
1000        parts = self.parts
1001        last_part = parts[-1]
1002
1003        if isinstance(last_part, Identifier):
1004            col: Expr = column(*reversed(parts[0:4]), fields=parts[4:], copy=copy)  # type: ignore
1005        else:
1006            # This branch will be reached if a function or array is wrapped in a `Table`
1007            col = last_part
1008
1009        alias = self.args.get("alias")
1010        if alias:
1011            col = alias_(col, alias.this, copy=copy)
1012
1013        return col
key: ClassVar[str] = 'table'
required_args: 't.ClassVar[set[str]]' = set()
class SetOperation(sqlglot.expressions.core.Expression, Query):
1016class SetOperation(Expression, Query):
1017    arg_types = {
1018        "with_": False,
1019        "this": True,
1020        "expression": True,
1021        "distinct": False,
1022        "by_name": False,
1023        "side": False,
1024        "kind": False,
1025        "on": False,
1026        **QUERY_MODIFIERS,
1027    }
1028
1029    def select(
1030        self: S,
1031        *expressions: ExpOrStr | None,
1032        append: bool = True,
1033        dialect: DialectType = None,
1034        copy: bool = True,
1035        **opts: Unpack[ParserNoDialectArgs],
1036    ) -> S:
1037        this = maybe_copy(self, copy)
1038        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1039        this.expression.unnest().select(
1040            *expressions, append=append, dialect=dialect, copy=False, **opts
1041        )
1042        return this
1043
1044    @property
1045    def named_selects(self) -> list[str]:
1046        expr: Expr = self
1047        while isinstance(expr, SetOperation):
1048            expr = expr.this.unnest()
1049        return _named_selects(expr)
1050
1051    @property
1052    def is_star(self) -> bool:
1053        return self.this.is_star or self.expression.is_star
1054
1055    @property
1056    def selects(self) -> list[Expr]:
1057        expr: Expr = self
1058        while isinstance(expr, SetOperation):
1059            expr = expr.this.unnest()
1060        return getattr(expr, "selects", [])
1061
1062    @property
1063    def left(self) -> Query:
1064        return self.this
1065
1066    @property
1067    def right(self) -> Query:
1068        return self.expression
1069
1070    @property
1071    def kind(self) -> str:
1072        return self.text("kind").upper()
1073
1074    @property
1075    def side(self) -> str:
1076        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}
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:
1029    def select(
1030        self: S,
1031        *expressions: ExpOrStr | None,
1032        append: bool = True,
1033        dialect: DialectType = None,
1034        copy: bool = True,
1035        **opts: Unpack[ParserNoDialectArgs],
1036    ) -> S:
1037        this = maybe_copy(self, copy)
1038        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1039        this.expression.unnest().select(
1040            *expressions, append=append, dialect=dialect, copy=False, **opts
1041        )
1042        return this
named_selects: list[str]
1044    @property
1045    def named_selects(self) -> list[str]:
1046        expr: Expr = self
1047        while isinstance(expr, SetOperation):
1048            expr = expr.this.unnest()
1049        return _named_selects(expr)
is_star: bool
1051    @property
1052    def is_star(self) -> bool:
1053        return self.this.is_star or self.expression.is_star

Checks whether an expression is a star.

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

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:
1173    def group_by(
1174        self,
1175        *expressions: ExpOrStr | None,
1176        append: bool = True,
1177        dialect: DialectType = None,
1178        copy: bool = True,
1179        **opts: Unpack[ParserNoDialectArgs],
1180    ) -> Select:
1181        """
1182        Set the GROUP BY expression.
1183
1184        Example:
1185            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
1186            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
1187
1188        Args:
1189            *expressions: the SQL code strings to parse.
1190                If a `Group` instance is passed, this is used as-is.
1191                If another `Expr` instance is passed, it will be wrapped in a `Group`.
1192                If nothing is passed in then a group by is not applied to the expression
1193            append: if `True`, add to any existing expressions.
1194                Otherwise, this flattens all the `Group` expression into a single expression.
1195            dialect: the dialect used to parse the input expression.
1196            copy: if `False`, modify this expression instance in-place.
1197            opts: other options to use to parse the input expressions.
1198
1199        Returns:
1200            The modified Select expression.
1201        """
1202        if not expressions:
1203            return self if not copy else self.copy()
1204
1205        return _apply_child_list_builder(
1206            *expressions,
1207            instance=self,
1208            arg="group",
1209            append=append,
1210            copy=copy,
1211            prefix="GROUP BY",
1212            into=Group,
1213            dialect=dialect,
1214            **opts,
1215        )

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:
1217    def sort_by(
1218        self,
1219        *expressions: ExpOrStr | None,
1220        append: bool = True,
1221        dialect: DialectType = None,
1222        copy: bool = True,
1223        **opts: Unpack[ParserNoDialectArgs],
1224    ) -> Select:
1225        """
1226        Set the SORT BY expression.
1227
1228        Example:
1229            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
1230            'SELECT x FROM tbl SORT BY x DESC'
1231
1232        Args:
1233            *expressions: the SQL code strings to parse.
1234                If a `Group` instance is passed, this is used as-is.
1235                If another `Expr` instance is passed, it will be wrapped in a `SORT`.
1236            append: if `True`, add to any existing expressions.
1237                Otherwise, this flattens all the `Order` expression into a single expression.
1238            dialect: the dialect used to parse the input expression.
1239            copy: if `False`, modify this expression instance in-place.
1240            opts: other options to use to parse the input expressions.
1241
1242        Returns:
1243            The modified Select expression.
1244        """
1245        return _apply_child_list_builder(
1246            *expressions,
1247            instance=self,
1248            arg="sort",
1249            append=append,
1250            copy=copy,
1251            prefix="SORT BY",
1252            into=Sort,
1253            dialect=dialect,
1254            **opts,
1255        )

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:
1257    def cluster_by(
1258        self,
1259        *expressions: ExpOrStr | None,
1260        append: bool = True,
1261        dialect: DialectType = None,
1262        copy: bool = True,
1263        **opts: Unpack[ParserNoDialectArgs],
1264    ) -> Select:
1265        """
1266        Set the CLUSTER BY expression.
1267
1268        Example:
1269            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
1270            'SELECT x FROM tbl CLUSTER BY x DESC'
1271
1272        Args:
1273            *expressions: the SQL code strings to parse.
1274                If a `Group` instance is passed, this is used as-is.
1275                If another `Expr` instance is passed, it will be wrapped in a `Cluster`.
1276            append: if `True`, add to any existing expressions.
1277                Otherwise, this flattens all the `Order` expression into a single expression.
1278            dialect: the dialect used to parse the input expression.
1279            copy: if `False`, modify this expression instance in-place.
1280            opts: other options to use to parse the input expressions.
1281
1282        Returns:
1283            The modified Select expression.
1284        """
1285        return _apply_child_list_builder(
1286            *expressions,
1287            instance=self,
1288            arg="cluster",
1289            append=append,
1290            copy=copy,
1291            prefix="CLUSTER BY",
1292            into=Cluster,
1293            dialect=dialect,
1294            **opts,
1295        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER 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 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:
1297    def select(
1298        self,
1299        *expressions: ExpOrStr | None,
1300        append: bool = True,
1301        dialect: DialectType = None,
1302        copy: bool = True,
1303        **opts: Unpack[ParserNoDialectArgs],
1304    ) -> Select:
1305        return _apply_list_builder(
1306            *expressions,
1307            instance=self,
1308            arg="expressions",
1309            append=append,
1310            dialect=dialect,
1311            into=Expr,
1312            copy=copy,
1313            **opts,
1314        )
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:
1316    def lateral(
1317        self,
1318        *expressions: ExpOrStr | None,
1319        append: bool = True,
1320        dialect: DialectType = None,
1321        copy: bool = True,
1322        **opts: Unpack[ParserNoDialectArgs],
1323    ) -> Select:
1324        """
1325        Append to or set the LATERAL expressions.
1326
1327        Example:
1328            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
1329            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
1330
1331        Args:
1332            *expressions: the SQL code strings to parse.
1333                If an `Expr` instance is passed, it will be used as-is.
1334            append: if `True`, add to any existing expressions.
1335                Otherwise, this resets the expressions.
1336            dialect: the dialect used to parse the input expressions.
1337            copy: if `False`, modify this expression instance in-place.
1338            opts: other options to use to parse the input expressions.
1339
1340        Returns:
1341            The modified Select expression.
1342        """
1343        return _apply_list_builder(
1344            *expressions,
1345            instance=self,
1346            arg="laterals",
1347            append=append,
1348            into=Lateral,
1349            prefix="LATERAL VIEW",
1350            dialect=dialect,
1351            copy=copy,
1352            **opts,
1353        )

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

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:
1453    def having(
1454        self,
1455        *expressions: ExpOrStr | None,
1456        append: bool = True,
1457        dialect: DialectType = None,
1458        copy: bool = True,
1459        **opts: Unpack[ParserNoDialectArgs],
1460    ) -> Select:
1461        """
1462        Append to or set the HAVING expressions.
1463
1464        Example:
1465            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
1466            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
1467
1468        Args:
1469            *expressions: the SQL code strings to parse.
1470                If an `Expr` instance is passed, it will be used as-is.
1471                Multiple expressions are combined with an AND operator.
1472            append: if `True`, AND the new expressions to any existing expression.
1473                Otherwise, this resets the expression.
1474            dialect: the dialect used to parse the input expressions.
1475            copy: if `False`, modify this expression instance in-place.
1476            opts: other options to use to parse the input expressions.
1477
1478        Returns:
1479            The modified Select expression.
1480        """
1481        return _apply_conjunction_builder(
1482            *expressions,
1483            instance=self,
1484            arg="having",
1485            append=append,
1486            into=Having,
1487            dialect=dialect,
1488            copy=copy,
1489            **opts,
1490        )

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:
1492    def window(
1493        self,
1494        *expressions: ExpOrStr | None,
1495        append: bool = True,
1496        dialect: DialectType = None,
1497        copy: bool = True,
1498        **opts: Unpack[ParserNoDialectArgs],
1499    ) -> Select:
1500        return _apply_list_builder(
1501            *expressions,
1502            instance=self,
1503            arg="windows",
1504            append=append,
1505            into=Window,
1506            dialect=dialect,
1507            copy=copy,
1508            **opts,
1509        )
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:
1511    def qualify(
1512        self,
1513        *expressions: ExpOrStr | None,
1514        append: bool = True,
1515        dialect: DialectType = None,
1516        copy: bool = True,
1517        **opts: Unpack[ParserNoDialectArgs],
1518    ) -> Select:
1519        return _apply_conjunction_builder(
1520            *expressions,
1521            instance=self,
1522            arg="qualify",
1523            append=append,
1524            into=Qualify,
1525            dialect=dialect,
1526            copy=copy,
1527            **opts,
1528        )
def distinct( self, *ons: Union[int, str, sqlglot.expressions.core.Expr, NoneType], distinct: bool = True, copy: bool = True) -> Select:
1530    def distinct(self, *ons: ExpOrStr | None, distinct: bool = True, copy: bool = True) -> Select:
1531        """
1532        Set the OFFSET expression.
1533
1534        Example:
1535            >>> Select().from_("tbl").select("x").distinct().sql()
1536            'SELECT DISTINCT x FROM tbl'
1537
1538        Args:
1539            ons: the expressions to distinct on
1540            distinct: whether the Select should be distinct
1541            copy: if `False`, modify this expression instance in-place.
1542
1543        Returns:
1544            Select: the modified expression.
1545        """
1546        instance = maybe_copy(self, copy)
1547        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
1548        instance.set("distinct", Distinct(on=on) if distinct else None)
1549        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:
1551    def ctas(
1552        self,
1553        table: ExpOrStr,
1554        properties: dict | None = None,
1555        dialect: DialectType = None,
1556        copy: bool = True,
1557        **opts: Unpack[ParserNoDialectArgs],
1558    ) -> Create:
1559        """
1560        Convert this expression to a CREATE TABLE AS statement.
1561
1562        Example:
1563            >>> Select().select("*").from_("tbl").ctas("x").sql()
1564            'CREATE TABLE x AS SELECT * FROM tbl'
1565
1566        Args:
1567            table: the SQL code string to parse as the table name.
1568                If another `Expr` instance is passed, it will be used as-is.
1569            properties: an optional mapping of table properties
1570            dialect: the dialect used to parse the input table.
1571            copy: if `False`, modify this expression instance in-place.
1572            opts: other options to use to parse the input table.
1573
1574        Returns:
1575            The new Create expression.
1576        """
1577        instance = maybe_copy(self, copy)
1578        table_expression = maybe_parse(table, into=Table, dialect=dialect, **opts)
1579
1580        properties_expression = None
1581        if properties:
1582            from sqlglot.expressions.properties import Properties as _Properties
1583
1584            properties_expression = _Properties.from_dict(properties)
1585
1586        from sqlglot.expressions.ddl import Create as _Create
1587
1588        return _Create(
1589            this=table_expression,
1590            kind="TABLE",
1591            expression=instance,
1592            properties=properties_expression,
1593        )

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:
1595    def lock(self, update: bool = True, copy: bool = True) -> Select:
1596        """
1597        Set the locking read mode for this expression.
1598
1599        Examples:
1600            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
1601            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
1602
1603            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
1604            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
1605
1606        Args:
1607            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
1608            copy: if `False`, modify this expression instance in-place.
1609
1610        Returns:
1611            The modified expression.
1612        """
1613        inst = maybe_copy(self, copy)
1614        inst.set("locks", [Lock(update=update)])
1615
1616        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:
1618    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
1619        """
1620        Set hints for this expression.
1621
1622        Examples:
1623            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
1624            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
1625
1626        Args:
1627            hints: The SQL code strings to parse as the hints.
1628                If an `Expr` instance is passed, it will be used as-is.
1629            dialect: The dialect used to parse the hints.
1630            copy: If `False`, modify this expression instance in-place.
1631
1632        Returns:
1633            The modified expression.
1634        """
1635        inst = maybe_copy(self, copy)
1636        inst.set(
1637            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
1638        )
1639
1640        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]
1642    @property
1643    def named_selects(self) -> list[str]:
1644        selects = []
1645
1646        for e in self.expressions:
1647            if e.alias_or_name:
1648                selects.append(e.output_name)
1649            elif isinstance(e, Aliases):
1650                selects.extend([a.name for a in e.aliases])
1651        return selects
is_star: bool
1653    @property
1654    def is_star(self) -> bool:
1655        return any(expression.is_star for expression in self.expressions)

Checks whether an expression is a star.

selects: list[sqlglot.expressions.core.Expr]
1657    @property
1658    def selects(self) -> list[Expr]:
1659        return self.expressions
key: ClassVar[str] = 'select'
required_args: 't.ClassVar[set[str]]' = set()
class Subquery(sqlglot.expressions.core.Expression, DerivedTable, Query):
1662class Subquery(Expression, DerivedTable, Query):
1663    is_subquery: t.ClassVar[bool] = True
1664    arg_types = {
1665        "this": True,
1666        "alias": False,
1667        "with_": False,
1668        **QUERY_MODIFIERS,
1669    }
1670
1671    def unnest(self) -> Expr:
1672        """Returns the first non subquery."""
1673        expression: Expr = self
1674        while isinstance(expression, Subquery):
1675            expression = expression.this
1676        return expression
1677
1678    def unwrap(self) -> Subquery:
1679        expression = self
1680        while expression.same_parent and expression.is_wrapper:
1681            expression = t.cast(Subquery, expression.parent)
1682        return expression
1683
1684    def select(
1685        self,
1686        *expressions: ExpOrStr | None,
1687        append: bool = True,
1688        dialect: DialectType = None,
1689        copy: bool = True,
1690        **opts: Unpack[ParserNoDialectArgs],
1691    ) -> Subquery:
1692        this = maybe_copy(self, copy)
1693        inner = this.unnest()
1694        if hasattr(inner, "select"):
1695            inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1696        return this
1697
1698    @property
1699    def is_wrapper(self) -> bool:
1700        """
1701        Whether this Subquery acts as a simple wrapper around another expression.
1702
1703        SELECT * FROM (((SELECT * FROM t)))
1704                      ^
1705                      This corresponds to a "wrapper" Subquery node
1706        """
1707        return all(v is None for k, v in self.args.items() if k != "this")
1708
1709    @property
1710    def is_star(self) -> bool:
1711        return self.this.is_star
1712
1713    @property
1714    def output_name(self) -> str:
1715        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}
def unnest(self) -> sqlglot.expressions.core.Expr:
1671    def unnest(self) -> Expr:
1672        """Returns the first non subquery."""
1673        expression: Expr = self
1674        while isinstance(expression, Subquery):
1675            expression = expression.this
1676        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
1678    def unwrap(self) -> Subquery:
1679        expression = self
1680        while expression.same_parent and expression.is_wrapper:
1681            expression = t.cast(Subquery, expression.parent)
1682        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:
1684    def select(
1685        self,
1686        *expressions: ExpOrStr | None,
1687        append: bool = True,
1688        dialect: DialectType = None,
1689        copy: bool = True,
1690        **opts: Unpack[ParserNoDialectArgs],
1691    ) -> Subquery:
1692        this = maybe_copy(self, copy)
1693        inner = this.unnest()
1694        if hasattr(inner, "select"):
1695            inner.select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1696        return this
is_wrapper: bool
1698    @property
1699    def is_wrapper(self) -> bool:
1700        """
1701        Whether this Subquery acts as a simple wrapper around another expression.
1702
1703        SELECT * FROM (((SELECT * FROM t)))
1704                      ^
1705                      This corresponds to a "wrapper" Subquery node
1706        """
1707        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
1709    @property
1710    def is_star(self) -> bool:
1711        return self.this.is_star

Checks whether an expression is a star.

output_name: str
1713    @property
1714    def output_name(self) -> str:
1715        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):
1718class TableSample(Expression):
1719    arg_types = {
1720        "expressions": False,
1721        "method": False,
1722        "bucket_numerator": False,
1723        "bucket_denominator": False,
1724        "bucket_field": False,
1725        "percent": False,
1726        "rows": False,
1727        "size": False,
1728        "seed": False,
1729    }
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):
1732class Tag(Expression):
1733    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
1734
1735    arg_types = {
1736        "this": False,
1737        "prefix": False,
1738        "postfix": False,
1739    }

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):
1742class Pivot(Expression):
1743    arg_types = {
1744        "this": False,
1745        "alias": False,
1746        "expressions": False,
1747        "fields": False,
1748        "unpivot": False,
1749        "using": False,
1750        "group": False,
1751        "columns": False,
1752        "include_nulls": False,
1753        "default_on_null": False,
1754        "into": False,
1755        "with_": False,
1756    }
1757
1758    @property
1759    def unpivot(self) -> bool:
1760        return bool(self.args.get("unpivot"))
1761
1762    @property
1763    def fields(self) -> list[Expr]:
1764        return self.args.get("fields", [])
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}
unpivot: bool
1758    @property
1759    def unpivot(self) -> bool:
1760        return bool(self.args.get("unpivot"))
fields: list[sqlglot.expressions.core.Expr]
1762    @property
1763    def fields(self) -> list[Expr]:
1764        return self.args.get("fields", [])
key: ClassVar[str] = 'pivot'
required_args: 't.ClassVar[set[str]]' = set()
class UnpivotColumns(sqlglot.expressions.core.Expression):
1767class UnpivotColumns(Expression):
1768    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key: ClassVar[str] = 'unpivotcolumns'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
1771class Window(Expression, Condition):
1772    arg_types = {
1773        "this": True,
1774        "partition_by": False,
1775        "order": False,
1776        "spec": False,
1777        "alias": False,
1778        "over": False,
1779        "first": False,
1780    }
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):
1783class WindowSpec(Expression):
1784    arg_types = {
1785        "kind": False,
1786        "start": False,
1787        "start_side": False,
1788        "end": False,
1789        "end_side": False,
1790        "exclude": False,
1791    }
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):
1794class PreWhere(Expression):
1795    pass
key: ClassVar[str] = 'prewhere'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Where(sqlglot.expressions.core.Expression):
1798class Where(Expression):
1799    pass
key: ClassVar[str] = 'where'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Analyze(sqlglot.expressions.core.Expression):
1802class Analyze(Expression):
1803    arg_types = {
1804        "kind": False,
1805        "this": False,
1806        "options": False,
1807        "mode": False,
1808        "partition": False,
1809        "expression": False,
1810        "properties": False,
1811    }
arg_types = {'kind': False, 'this': 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):
1814class AnalyzeStatistics(Expression):
1815    arg_types = {
1816        "kind": True,
1817        "option": False,
1818        "this": False,
1819        "expressions": False,
1820    }
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):
1823class AnalyzeHistogram(Expression):
1824    arg_types = {
1825        "this": True,
1826        "expressions": True,
1827        "expression": False,
1828        "update_options": False,
1829    }
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):
1832class AnalyzeSample(Expression):
1833    arg_types = {"kind": True, "sample": True}
arg_types = {'kind': True, 'sample': True}
key: ClassVar[str] = 'analyzesample'
required_args: 't.ClassVar[set[str]]' = {'sample', 'kind'}
class AnalyzeListChainedRows(sqlglot.expressions.core.Expression):
1836class AnalyzeListChainedRows(Expression):
1837    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):
1840class AnalyzeDelete(Expression):
1841    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):
1844class AnalyzeWith(Expression):
1845    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):
1848class AnalyzeValidate(Expression):
1849    arg_types = {
1850        "kind": True,
1851        "this": False,
1852        "expression": False,
1853    }
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):
1856class AnalyzeColumns(Expression):
1857    pass
key: ClassVar[str] = 'analyzecolumns'
required_args: 't.ClassVar[set[str]]' = {'this'}
class UsingData(sqlglot.expressions.core.Expression):
1860class UsingData(Expression):
1861    pass
key: ClassVar[str] = 'usingdata'
required_args: 't.ClassVar[set[str]]' = {'this'}
class AddPartition(sqlglot.expressions.core.Expression):
1864class AddPartition(Expression):
1865    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):
1868class AttachOption(Expression):
1869    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):
1872class DropPartition(Expression):
1873    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):
1876class ReplacePartition(Expression):
1877    arg_types = {"expression": True, "source": True}
arg_types = {'expression': True, 'source': True}
key: ClassVar[str] = 'replacepartition'
required_args: 't.ClassVar[set[str]]' = {'source', 'expression'}
class TranslateCharacters(sqlglot.expressions.core.Expression):
1880class TranslateCharacters(Expression):
1881    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):
1884class OverflowTruncateBehavior(Expression):
1885    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):
1888class JSON(Expression):
1889    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):
1892class JSONPath(Expression):
1893    arg_types = {"expressions": True, "escape": False}
1894
1895    @property
1896    def output_name(self) -> str:
1897        last_segment = self.expressions[-1].this
1898        return last_segment if isinstance(last_segment, str) else ""
arg_types = {'expressions': True, 'escape': False}
output_name: str
1895    @property
1896    def output_name(self) -> str:
1897        last_segment = self.expressions[-1].this
1898        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):
1901class JSONPathPart(Expression):
1902    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'jsonpathpart'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathFilter(JSONPathPart):
1905class JSONPathFilter(JSONPathPart):
1906    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathfilter'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathKey(JSONPathPart):
1909class JSONPathKey(JSONPathPart):
1910    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathkey'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathRecursive(JSONPathPart):
1913class JSONPathRecursive(JSONPathPart):
1914    arg_types = {"this": False}
arg_types = {'this': False}
key: ClassVar[str] = 'jsonpathrecursive'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathRoot(JSONPathPart):
1917class JSONPathRoot(JSONPathPart):
1918    pass
key: ClassVar[str] = 'jsonpathroot'
required_args: 't.ClassVar[set[str]]' = set()
class JSONPathScript(JSONPathPart):
1921class JSONPathScript(JSONPathPart):
1922    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathscript'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathSlice(JSONPathPart):
1925class JSONPathSlice(JSONPathPart):
1926    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):
1929class JSONPathSelector(JSONPathPart):
1930    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathselector'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathSubscript(JSONPathPart):
1933class JSONPathSubscript(JSONPathPart):
1934    arg_types = {"this": True}
arg_types = {'this': True}
key: ClassVar[str] = 'jsonpathsubscript'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONPathUnion(JSONPathPart):
1937class JSONPathUnion(JSONPathPart):
1938    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'jsonpathunion'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class JSONPathWildcard(JSONPathPart):
1941class JSONPathWildcard(JSONPathPart):
1942    pass
key: ClassVar[str] = 'jsonpathwildcard'
required_args: 't.ClassVar[set[str]]' = set()
class FormatJson(sqlglot.expressions.core.Expression):
1945class FormatJson(Expression):
1946    pass
key: ClassVar[str] = 'formatjson'
required_args: 't.ClassVar[set[str]]' = {'this'}
class JSONKeyValue(sqlglot.expressions.core.Expression):
1949class JSONKeyValue(Expression):
1950    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):
1953class JSONColumnDef(Expression):
1954    arg_types = {
1955        "this": False,
1956        "kind": False,
1957        "path": False,
1958        "nested_schema": False,
1959        "ordinality": False,
1960    }
arg_types = {'this': False, 'kind': False, 'path': False, 'nested_schema': False, 'ordinality': False}
key: ClassVar[str] = 'jsoncolumndef'
required_args: 't.ClassVar[set[str]]' = set()
class JSONSchema(sqlglot.expressions.core.Expression):
1963class JSONSchema(Expression):
1964    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):
1967class JSONValue(Expression):
1968    arg_types = {
1969        "this": True,
1970        "path": True,
1971        "returning": False,
1972        "on_condition": False,
1973    }
arg_types = {'this': True, 'path': True, 'returning': False, 'on_condition': False}
key: ClassVar[str] = 'jsonvalue'
required_args: 't.ClassVar[set[str]]' = {'path', 'this'}
1976class JSONValueArray(Expression, Func):
1977    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):
1980class OpenJSONColumnDef(Expression):
1981    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):
1984class JSONExtractQuote(Expression):
1985    arg_types = {
1986        "option": True,
1987        "scalar": False,
1988    }
arg_types = {'option': True, 'scalar': False}
key: ClassVar[str] = 'jsonextractquote'
required_args: 't.ClassVar[set[str]]' = {'option'}
class ScopeResolution(sqlglot.expressions.core.Expression):
1991class ScopeResolution(Expression):
1992    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):
1995class Stream(Expression):
1996    pass
key: ClassVar[str] = 'stream'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ModelAttribute(sqlglot.expressions.core.Expression):
1999class ModelAttribute(Expression):
2000    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):
2003class XMLNamespace(Expression):
2004    pass
key: ClassVar[str] = 'xmlnamespace'
required_args: 't.ClassVar[set[str]]' = {'this'}
class XMLKeyValueOption(sqlglot.expressions.core.Expression):
2007class XMLKeyValueOption(Expression):
2008    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):
2011class Semicolon(Expression):
2012    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'semicolon'
required_args: 't.ClassVar[set[str]]' = set()
class TableColumn(sqlglot.expressions.core.Expression):
2015class TableColumn(Expression):
2016    pass
key: ClassVar[str] = 'tablecolumn'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Variadic(sqlglot.expressions.core.Expression):
2019class Variadic(Expression):
2020    pass
key: ClassVar[str] = 'variadic'
required_args: 't.ClassVar[set[str]]' = {'this'}
class StoredProcedure(sqlglot.expressions.core.Expression):
2023class StoredProcedure(Expression):
2024    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):
2027class Block(Expression):
2028    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'block'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class IfBlock(sqlglot.expressions.core.Expression):
2031class IfBlock(Expression):
2032    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 WhileBlock(sqlglot.expressions.core.Expression):
2035class WhileBlock(Expression):
2036    arg_types = {"this": True, "body": True}
arg_types = {'this': True, 'body': True}
key: ClassVar[str] = 'whileblock'
required_args: 't.ClassVar[set[str]]' = {'body', 'this'}
class EndStatement(sqlglot.expressions.core.Expression):
2039class EndStatement(Expression):
2040    arg_types = {}
arg_types = {}
key: ClassVar[str] = 'endstatement'
required_args: 't.ClassVar[set[str]]' = set()
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:
2046def union(
2047    *expressions: ExpOrStr,
2048    distinct: bool = True,
2049    dialect: DialectType = None,
2050    copy: bool = True,
2051    **opts: Unpack[ParserNoDialectArgs],
2052) -> Union:
2053    """
2054    Initializes a syntax tree for the `UNION` operation.
2055
2056    Example:
2057        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
2058        'SELECT * FROM foo UNION SELECT * FROM bla'
2059
2060    Args:
2061        expressions: the SQL code strings, corresponding to the `UNION`'s operands.
2062            If `Expr` instances are passed, they will be used as-is.
2063        distinct: set the DISTINCT flag if and only if this is true.
2064        dialect: the dialect used to parse the input expression.
2065        copy: whether to copy the expression.
2066        opts: other options to use to parse the input expressions.
2067
2068    Returns:
2069        The new Union instance.
2070    """
2071    assert len(expressions) >= 2, "At least two expressions are required by `union`."
2072    return _apply_set_operation(
2073        *expressions, set_operation=Union, distinct=distinct, dialect=dialect, copy=copy, **opts
2074    )

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:
2077def intersect(
2078    *expressions: ExpOrStr,
2079    distinct: bool = True,
2080    dialect: DialectType = None,
2081    copy: bool = True,
2082    **opts: Unpack[ParserNoDialectArgs],
2083) -> Intersect:
2084    """
2085    Initializes a syntax tree for the `INTERSECT` operation.
2086
2087    Example:
2088        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
2089        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
2090
2091    Args:
2092        expressions: the SQL code strings, corresponding to the `INTERSECT`'s operands.
2093            If `Expr` instances are passed, they will be used as-is.
2094        distinct: set the DISTINCT flag if and only if this is true.
2095        dialect: the dialect used to parse the input expression.
2096        copy: whether to copy the expression.
2097        opts: other options to use to parse the input expressions.
2098
2099    Returns:
2100        The new Intersect instance.
2101    """
2102    assert len(expressions) >= 2, "At least two expressions are required by `intersect`."
2103    return _apply_set_operation(
2104        *expressions, set_operation=Intersect, distinct=distinct, dialect=dialect, copy=copy, **opts
2105    )

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:
2108def except_(
2109    *expressions: ExpOrStr,
2110    distinct: bool = True,
2111    dialect: DialectType = None,
2112    copy: bool = True,
2113    **opts: Unpack[ParserNoDialectArgs],
2114) -> Except:
2115    """
2116    Initializes a syntax tree for the `EXCEPT` operation.
2117
2118    Example:
2119        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
2120        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
2121
2122    Args:
2123        expressions: the SQL code strings, corresponding to the `EXCEPT`'s operands.
2124            If `Expr` instances are passed, they will be used as-is.
2125        distinct: set the DISTINCT flag if and only if this is true.
2126        dialect: the dialect used to parse the input expression.
2127        copy: whether to copy the expression.
2128        opts: other options to use to parse the input expressions.
2129
2130    Returns:
2131        The new Except instance.
2132    """
2133    assert len(expressions) >= 2, "At least two expressions are required by `except_`."
2134    return _apply_set_operation(
2135        *expressions, set_operation=Except, distinct=distinct, dialect=dialect, copy=copy, **opts
2136    )

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.