Skip to main content

Posts

Showing posts with the label orderby

UPDATE with ORDER BY

The statement succeeds if it updates id values first by setting 2 to 1 and then 3 to 2. However, it fails if it  first tries to set 3 to 2. That would result in two records having an id value of 2, so a duplicate-key  violation occurs. To solve this problem, add an ORDER BY clause to cause the row updates to occur in a  particular order: UPDATE people SET id=id-1 ORDER BY id; Row contents will be as follows; +-------------------+ | id | name | age | +-------------------+ | 1 | Victor | 21 | | 2 | Susan | 15 | +-------------------+

SELECT with ORDER BY

          By default, the rows in the result set produced by a SELECT statement are returned by the server to the  client in no particular order.  When a query is issued, the server is free to return the rows in any convenient  order.  This order can be affected by factors such as the order in which the rows are actually stored in the  table, or which indexes are used to process the query.  If the output rows need to be returned in a specific  order, include an ORDER BY clause that indicates how to sort the results.  There is no guarantee about the order in which the server returns rows, unless the order is specified.  To do  so, add an ORDER BY clause to the statement that defines the sort order desired.  Single Column Sorts  The following example returns country names (in the Country table of the world database) alphabetically  by Country Name;  mysql> SELECT Name FROM Country ORDER BY Name;  +------------------------------+  | Name                            |  +--------