<!--
{
  "availability" : [
    "iOS: 17.0.0 -",
    "iPadOS: 17.0.0 -",
    "macCatalyst: 17.0.0 -",
    "macOS: 14.0.0 -",
    "tvOS: 17.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 10.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftData",
  "identifier" : "/documentation/SwiftData/Query(filter:sort:order:transaction:)-8tk8u",
  "metadataVersion" : "0.1.0",
  "role" : "Macro",
  "symbol" : {
    "kind" : "Macro",
    "modules" : [
      "SwiftData",
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:011_SwiftData_A2UI5Query6filter4sort5order11transactiony10Foundation9PredicateVyq__QPGSg_s7KeyPathCyq_xSgGAG9SortOrderO0aC011TransactionVSgtcSLRz0aB015PersistentModelR_r0_lufm"
  },
  "title" : "Query(filter:sort:order:transaction:)"
}
-->

# Query(filter:sort:order:transaction:)

Fetches a subset of the attached model type, in a specific order, by sorting on
an optional attribute.

```
@attached(accessor) @attached(peer, names: prefixed(`_`)) macro Query<Value, Element>(filter: Predicate<Element>? = nil, sort keyPath: KeyPath<Element, Value?>, order: SortOrder = .forward, transaction: Transaction? = nil) where Value : Comparable, Element : PersistentModel
```

## Parameters

`filter`

The logical condition the query uses to determine if it returns a specific model instance.

`keyPath`

The keypath of the optional attribute to sort by.

`order`

The order of the sort.

`transaction`

The transaction to use when updates to the fetched models trigger user interface changes.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)