You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs-parts/queries/03-Fetch_lang1.rst
+40Lines changed: 40 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -35,6 +35,46 @@ Primary key values
35
35
36
36
``KEY`` can also used when returning attribute values as separate variables, such that one of the returned variables contains the entire primary keys.
37
37
38
+
Sorting and limiting the results
39
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
40
+
41
+
To sort the result, use the ``order_by`` keyword argument.
42
+
43
+
.. code-block:: python
44
+
45
+
# ascending order:
46
+
data = query.fetch(order_by='name')
47
+
# descending order:
48
+
data = query.fetch(order_by='name desc')
49
+
# by name first, year second:
50
+
data = query.fetch(order_by=('name desc', 'year'))
51
+
# sort by the primary key:
52
+
data = query.fetch(order_by='KEY')
53
+
# sort by name but for same names order by primary key:
54
+
data = query.fetch(order_by=('name', 'KEY desc'))
55
+
56
+
The ``order_by`` argument can be a string specifying the attribute to sort by. By default the sort is in ascending order. Use ``'attr desc'`` to sort in descending order by attribute ``attr``. The value can also be a sequence of strings, in which case, the sort performed on all the attributes jointly in the order specified.
57
+
58
+
The special attribute name ``'KEY'`` represents the primary key attributes in order that they appear in the index. Otherwise, this name can be used as any other argument.
59
+
60
+
If an attribute happens to be a SQL reserved word, it needs to be enclosed in backquotes. For example:
61
+
62
+
.. code-block:: python
63
+
64
+
data = query.fetch(order_by='`select` desc')
65
+
66
+
The ``order_by`` value is eventually passed to the ``ORDER BY`` `clause <https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html>`_.
67
+
68
+
Similarly, the ``limit`` and ``offset`` arguments can be used to limit the result to a subset of entities.
69
+
70
+
For example, one could do the following:
71
+
72
+
.. code-block:: python
73
+
74
+
data = query.fetch(order_by='name', limit=10, offset=5)
75
+
76
+
Note that an ``offset`` cannot be used without specifying a ``limit`` as well.
0 commit comments