Order By a field being equal to a specific value? - sql

Let's say I have this MySQL query:
SELECT * FROM A WHERE x='abc' OR y=0;
How can I prioritize the rows so that cases where x='abc' are ordered FIRST? If y=0 but x!='abc', I want those rows to come after cases where x='abc'.
Can this be accomplished with a simple ORDER BY clause?
Thanks!

SELECT *
FROM A
WHERE x='abc'
OR y=0
order by case when x='abc' then 0 else 1 end;

I would do it with a case statement:
SELECT *,
CASE WHEN column_one = 0 THEN 0
WHEN column_two = 'ADMIN' THEN 1
END AS multi_column
FROM sometable
ORDER BY multi_column;

ORDER BY FIELD(x,'abc',x)

Related

How to COUNT a value in a column?

I have a column where I flag two values (0 and 1). How can I select all from the table but only counting the value 1 from the flag column?
SQL Server
You need a COUNT with CASE expression, like this:
COUNT(CASE WHEN flag = 1 then 1 END)
If you want to return all of your values and also have a total count (using sort of logic) you could use a window function aggregation using over like so:
select
t.*
, count(case when flag = 1 then 1 end) over(partition by 1) as flag_1_count
from t
Err, are you asking how to perform a simple select statement or am I missing something...
Like this?
SELECT *
FROM [YourTableName]
WHERE FlagColumnName = 1
This should do it
Select count(0)
from YourTableName
where ValueField = 1
I think, you mean something like this:
SELECT COUNT(*) FROM [YOUR_TABLE] WHERE [FLAGCOLUMN] = 1;
Not quite sure I understand the question, but wouldn't it be something like:
SELECT * FROM your_table WHERE flag = 1

Null value in order by clause

I have a weird scenario, in which I need to keep all the rows at top in which X column has NULL value else sort by Y column. Can you help me in writing query.
ORDER BY CASE WHEN X IS NULL THEN 0 ELSE 1 END, Y
You can use a CASE statement in ORDER BY:
ORDER BY
CASE WHEN X IS NULL THEN 0 ELSE 1 END ASC, Y
Here you go, this will work with any sql platform -- for a specific platform there might be a better way to do it.
SELECT * FROM
(
SELECT 1 AS orderC, *
FROM tableName
WHERE Xcolumn is null
UNION ALL
SELECT 2 AS orderC, *
FROM tableName
WHERE Xcolumn is not null
)
ORDER BY orderC ASC, columnY
Note, if you don't want orderC to be in the output, just specify all the other columns in the outer select.
Sharing what I learned before using:
ORDER BY FIELD(Xcolumn, NULL) DESC, Ycolumn DESC
SELECT * FROM TABLENAME ORDER BY X ,Y
You can use query like below:
SELECT * FROM Emp WHERE empId= 6 AND DELETED = 0
ORDER BY CASE WHEN DOB IS NULL THEN 0 ELSE 1 END
, CREATETIMESTAMP.
for more details you can see here

Adjust SQL Query to force a record to appear first?

How can the below query be adjusted to return always the member with MemberID = 'xxx' as the first row
SELECT * FROM Members
select * from Members
order by case when MemberID = XXX then 0 else 1 end
This should work and it will also allow you to order the remaining items by MemberID (Assuming xxx=12 in this example)
SELECT *
FROM Members
ORDER BY CASE WHEN MemberID=12 THEN NULL ELSE isnull(MemberID,0) END
If the memberID column can't contain nulls, you can get away with this which might perform slightly better.
SELECT *
FROM Members
ORDER BY CASE WHEN MemberID=12 THEN NULL ELSE MemberID END
SELECT
CASE WHEN MemberID = 'xxx' AS 1 ELSE 0 END CASE AS magic,
*
FROM Members
ORDER BY magic DESC
The syntax might vary depending on yr db, but I hope you get the idea.
SELECT * FROM `Members` WHERE `MemberID` = '[ID]' LIMIT 1 UNION SELECT * FROM `Members`
This should work. Tested on my database instance. Chosen ID is always first.
A more robust solution, if you have more than one record that has to be floated to the top, or if you have a specific order for multiple records, is to add a ResultsOrder column to your table, or even another table MemberOrder(memberid, resultorder). Fill resultorder with big numbers and ...
Select m.*
From Members m
Left Join MemberOrder mo on m.MemberID=mo.MemberID
Order by coalesce(mo.resultorder, 0) DESC
try this:
SELECT * FROM Members
ORDER BY IF(x.MemberId = XXX, -1, ABS(x.MemberId))

SQl Query with order by

Can you please help me to form a sql query (MySQL) that allows me to sort the results by order ascending / descending (A- Z / Z - A) and putting in the last lines that have no value.
Less error prone than altering the column of order is:
SELECT
columnOfInterest
FROM
theTable
ORDER BY
CASE WHEN columnOfInterest IS NULL THEN 1 ELSE 0 END CASE
, columnOfInterest
select stateName
from stateTable
order by coalesce(stateName, 'ZZZZZZZZZZZZZZZZZZZZZZZZZ')
You're looking for the 'order by' statement tacked on to your select query.
http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
SELECT HEADER FROM TABLE ORDER BY ELEMENTTOORDER

Order by Maximum condition match

Please help me to create a select query which contains 10 'where' clause and the order should be like that:
the results should be displayed in order of most keywords(where conditions) matched down to least matched.
NOTE: all 10 condition are with "OR".
Please help me to create this query.
i am using ms-sql server 2005
Like:
Select *
from employee
where empid in (1,2,4,332,434)
or empname like 'raj%'
or city = 'jodhpur'
or salary >5000
In above query all those record which matches maximum conditions should be on top and less matching condition record should be at bottom.
SELECT *
FROM (SELECT (CASE WHEN cond1 THEN 1 ELSE 0 END +
CASE WHEN cond2 THEN 1 ELSE 0 END +
CASE WHEN cond2 THEN 1 ELSE 0 END +
...
CASE WHEN cond10 THEN 1 ELSE 0 END
) AS numMatches,
other_columns...
FROM mytable
) xxx
WHERE numMatches > 0
ORDER BY numMatches DESC
EDIT: This answer was posted before the question was modified with a concrete example. Marcelo's solution addresses the actual problem. On the other hand, my answer was giving priority to matches of specific fields.
You may want to try something like the following, using the same expressions in the ORDER BY clause as in your WHERE clause:
SELECT *
FROM your_table
WHERE field_1 = 100 OR
field_2 = 200 OR
field_3 = 300
ORDER BY field_1 = 100 DESC,
field_2 = 200 DESC,
field_3 = 300 DESC;
I've recently answered a similar question on Stack Overflow which you might be interested in checking out:
Is there a SQL technique for ordering by matching multiple criteria?
There are many options/answers possible. Best answer depends on size of the data, non-functional requirements, etc.
That said, what I would do is something like this (easy to read / debug):
Select * from
(Select *, iif(condition1 = bla, 1, 0) as match1, ..... , match1+match2...+match10 as totalmatchscore from sourcetable
where
condition1 = bla or
condition2 = bla2
....) as helperquery
order by helperquery.totalmatchscore desc
I could not get this to work for me on Oracle.
If using oracle, then this Order by Maximum condition match is a good solution.
Utilizes the case when language feature