ORDER BY column = value desc|asc - sql

I found this piece of code a while ago, and I don't seem to find any explanation about how it really works:
SELECT account_id from accounts order by account_id = 100;
So, I know what order by [column] desc|asc does to the result set. But I don't seem to find the explanation for giving a value to the [column] and how that affects the result set. It's clearly affected, but I don't seem to find a pattern.

Try rewriting your query using an explicit CASE expression in the ORDER BY clause:
SELECT account_id
FROM accounts
ORDER BY CASE WHEN account_id = 100 THEN 1 ELSE 0 END;
You will observe that all records having account_id != 100 will appear before all records where this is true. When you use:
ORDER BY account_id = 100
Then you are ordering by the boolean equality itself. So, when not true, it would evaluate to zero, and when true would evaluate to one.

Postgres supports boolean types, which take on two values "true" and "false" (plus NULL, of course). A boolean value is being used as the order by key.
The expression account_id = 100 evaluates to "true" for account_id 100 and false for others (or NULL).
What does this do? Well, "true" > "false" and the ordering is ascending. Hence, the true value is ordered after all other values; account_id 100 goes at the end. Well not quite the end. NULL values are lastest -- they would go at the very end.
More commonly, this is done with a descending sort:
order by (account_id = 100) desc
This puts account 100 first in the list.
Note: I put the expression in parentheses in such cases to make it clear that the intent really is to order by the expression. That is, there is no typo.

Basically ORDER BY is of two types ASC and DESC
By Default it is ASC
Let us take an example
SELECT * from Person
ORDER BY Age DESC
Above query returns the Age of Persons in Descending Order

Related

what is the use of AND with ORDER BY?

What does the AND do in a query like so
SELECT *
FROM table
WHERE SaleNo > 200,
ORDER BY EmployeeNo AND SaleNo;
How is it different from
SELECT *
FROM table
WHERE SaleNo > 200,
ORDER BY EmployeeNo, SaleNo;
Both queries actually return a table back but I don't understand the meaning of 1st query.
ORDER BY is usually used along with pipes and commas for additional filterings. TIA
ORDER BY EmployeeNo AND SaleNo;
The above becomes this:
ORDER BY (EmployeeNo AND SaleNo)
And then becomes:
ORDER BY (true/false AND true/false)
And then
ORDER BY (true/false)
So the expression is converted to a true/false expression.
If the 2 columns are number types, then
0 values = false, and any NON zero value = true
so, you have
ORDER BY ( (EmployeeNo <> 0) AND (SaleNo <> 0) )
So, if both EmplyeeNo and SaleNo have a value?
You get this
ORDER BY ( (true) AND (True))
ORDER BY True
The value is thus -1.
What this means is that if both values have a number, (not 0), then they will appear first in the list and all others if one of the two numbers are 0 or both are 0 will follow.
So, to order by a column, and then by a anohter, you use
col1, col2 - as you have.
if you go
col1 AND col2
Then this is Boolean (true/false) expression, and not a order by one column, and then on to the next.

How to get 0 if no row found from sql query in sql server

I am getting blank value with this query from sql server
SELECT TOP 1 Amount from PaymentDetails WHERE Id = '5678'
it has no row,that is why its returning blank,So I want if no row then it should return 0
I already tried with COALESCE ,but its not working
how to solve this?
You are selecting an arbitrary amount, so one method is aggregation:
SELECT COALESCE(MAX(Amount), 0)
FROM PaymentDetails
WHERE Id = '5678';
Note that if id is a number, then don't use single quotes for the comparison.
To be honest, I would expect SUM() to be more useful than an arbitrary value:
SELECT COALESCE(SUM(Amount), 0)
FROM PaymentDetails
WHERE Id = '5678';
You can wrap the subquery in an ISNULL:
SELECT ISNULL((SELECT TOP 1 Amount from PaymentDetails WHERE Id = '5678' ORDER BY ????),0) AS Amount;
Don't forget to add a column (or columns) to your ORDER BY as otherwise you will get inconsistent results when more than one row has the same value for Id. If Id is unique, however, then remove both the TOP and ORDER BY as they aren't needed.
You should never, however, use TOP without an ORDER BY unless you are "happy" with inconsistent results.

Two Level Grouping in SQL

Need Help on this SQL query..
Table has just 3 columns - Name, Check(Yes / No), Post (true /false)
The result gets ordered by Check and then further grouped by Post value....
Simply - All Records with Check Yes and Post true first, then those with Check Yes and Post false. And so on those with Check No and Post true and at last those with Check No and Post false
May be Simpler then it sounds but just can't get this one to work :)
Well the actual table schema is larger then this dummy table but we can assume all these columns to be nvarchars
From my understanding of the question, this seem to be what you want.
SELECT *
FROM dummyTable
ORDER BY [Check] DESC,
[Post] DESC
Will work with BIT and VARCHAR, because T > F AND Y > N.
In case it is VARCHAR with denormalize data, a good idea would be to use
ORDER BY UPPER([Check]) DESC,
UPPER([Post]) DESC
to avoid bad result due to case sensitivity (T < f AND Y < n)

SQL Order By Except When You Don't

I want to retrieve a full table with some of the values sorted. The sorted values should all appear before the unsorted values. I though I could pull this off with a UNION but order by is only valid to use after unioning the table and my set of data isn't set up such that that is useful in this case. I want rows with a column value of 0-6 to show up sorted in DESC order and then the rest of the results to show up after that. Is there some way to specify a condition in the order by clause? I saw something that looked close to what I wanted to so but I couldn't get the equality condition working in sql. I'm going to try to make a query using WHEN cases but I'm not sure if there's a way to specify a case like currentValue <= 6. If anyone has any suggestions that would be awesome.
You could do something like this:
order by (case when currentValue <= 6 then 1 else 0 end) desc,
(case when currentValue <= 6 then column end) desc
The first puts the values you care about first. The second puts them in sorted order. The rest will be ordered arbitrarily.
Try this:
SELECT *
FROM yourdata
ORDER BY CASE WHEN yourColumn BETWEEN 0 AND 6 THEN yourColumn ELSE -1 End Desc
One RDBMS-agnostic solution would be to add a second field that takes the same value as the field you wish to sort when that field is less than or equal to six. Then just sort by that field.

SQL (Mysql) order problem

I have the following query:
SELECT a.field_eventid_key_value, a.field_showdate_value, b.nid , c.nid AS CNID
FROM content_type_vorfuehrung AS a
LEFT JOIN content_type_movies as b ON a.field_eventid_key_value = b.field_eventid_value
LEFT JOIN content_type_sonderveranstaltung as c ON a.field_eventid_key_value = c.field_sonderveranstaltungid_value
WHERE /* something */
GROUP BY a.field_eventid_key_value, a.field_showdate_value,
ORDER BY a.field_showdate_value ASC,a.field_showtime_value ASC
(where clause removed since it's irrelevant to the question)
This pulls data from 3 different tables and sorts it according to the "showdate" field in the first table. This is used in a PHP function that returns an array with the results.
Now there is a new requirement: The table "content_type_movies" in this query has a field that's supposed to be a boolean (actually it's an int with a value of either "0" oder "1"). This field is supposed to override the chronological ordering - that is, results where the field is "true" (or "1" respectively) should appear at the beginning of the result array (with the remaining entries ordered chronologically as before).
Is this at all possible with a single query ?
Thank you in advance for your time,
eike
You can use:
ORDER BY b.MyIntField DESC,
a.field_showdate_value,
a.field_showtime_value
where MyIntField is the field that is either 1 or 0 that you want to sort first.
ORDER BY a.content_type_movies DESC, /*then other fields*/ a.field_showdate_value ASC,a.field_showtime_value ASC
that should place all rows with content_type_movies=1 first then others.