SQL Server 2005: Order with NULL values at the end [duplicate] - sql

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Case Order by using Null
I'm looking to get a list of records ordered by an "ordernum" field. The ordernum field is an int field. This field starts as NULL until set by a user. I would like the NULL entries to appear at the end of the list.
I am building a query as follows:
select *, case when (ordernum is null) then [largestInt] else ordernum end as newordernum
from tableName
order by newordernum
I know I could enter the value for the largest possible int for [largestInt], but I would like to replace [largestInt] with a variable. Is this possible?

I found a way to order NULL values on the bottom.
http://sqlblog.com/blogs/denis_gobo/archive/2007/10/19/3048.aspx
It meets my needs quite nicely. My query is now:
select *
from tableName
order by case when ordernum is null then 1 else 0 end, ordernum

Related

Updating postgres column with sequence of integers [duplicate]

This question already has answers here:
SQL update records with ROW_NUMBER()
(2 answers)
Closed 1 year ago.
I have a postgres table bar that contains 130 rows. I would like to auto-populate the id column with a sequence of incrementing integers from 1 to 130. When I try the following code:
update bar
set id = t.num FROM (
SELECT *
FROM generate_series(1, 130) num) t
The column is updated but every row contains 1. What I am doing wrong here and what is the correct syntax for this procedure?
You need a primary key to identify each row. Then you can use:
update bar b
set id = b2.new_id
from (select b.*, row_number() over (order by id) as new_id
from bar
) b2;
where b.pk = b2.pk;
Your version is attempting to update each row 130 times. Only one update is kept -- seemingly the first one but you cannot depend on that.

How to best check integrity of nvarchar fields that have been exported to xlsx files comparing to the view results?

I am using this code to check for data integrity of nvarchar/string data fields. Taking the sum from the view using code below, and comparing that to similar formula in EXCEL to see if I get the same total. Is there a better way? I am new at this.
--Aggregate Boolean fields e.g. nvarchar.
With table1 AS
(
Select
CASE WHEN (field_name) = 'Y' Then 1
WHEN field_name = 'N' Then 2
When field_name IS NULL THEN 3
ELSE field_name
END AS field_name_count
From mysqlview
)
Select SUM(field_name) AS Count
From table1
;
Or this approach
--Count characters in nvarchar column
Select
SUM(LEN(field_name)) AS Count
From mysqlview
;
I can't comment so I'll add my 2 cents here.
you seems to sum a Nvarchar field - can you update your question with the reasoning for this?
Also - in the first example you have sum on 'field_name' while the column name is 'field_name_count'
Do you try to see how many fields contain text and compare this number to your Excel data?
in that case you can count them easily by doing:
select count(1) from mysqlview where fieldname != '' and not fieldname is null
Hope I helped

Reference a variable created with a case Statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have my database up and running and can do some basic selects using SQL Server 2017 Management Studio. The problem I'm running into now is a have a table that depending on the values within a row, a certain outcome is generated. I have the below code which currently works.
I'm running into issues what I try to reference Master_Status when I'm writing another case.
Basically I need do say if Master_Status is null after the first check then allow it to go into the second criteria, etc. Have about 10 outcomes I need to build this out for.
Is this possible? Should I be using reference tables?
EDIT
Below better represents my problem: I'm trying to loop through a bunch of critera to determine the end status of a sale. The sale can only have a unique status which is why I'd like to check if master_status is null.
WITH MasterStatus AS
(
SELECT
[Name]
,case WHEN saleDate is not Null then 'outcome1'
else NULL end as 'Master_Status'
,case when SaleSize is not NULL and Master_Status is Null then
'Outcome2'
else NULL end as 'Master_status'
from [AllNames]
)
select
[Name]
from MasterStatus where Master_Status is not null
Based on the current iteration of your query, it seems you're struggling with how CASE expressions work. Rather than trying to use multiple CASE expressions to assign values to the same column (which won't work), you need one CASE expression with multiple WHEN conditions.
WITH MasterStatus AS
(
SELECT
Name
,CASE
WHEN saleDate IS NOT NULL
THEN 'Outcome1'
WHEN SaleSize IS NOT NULL
THEN 'Outcome2'
--...
WHEN ColumnN IS NOT NULL
THEN 'OutcomeN'
ELSE NULL
END AS Master_Status
FROM
AllNames
)
SELECT
Name
FROM
MasterStatus
WHERE
Master_Status IS NOT NULL;
The WHEN conditions will be evaluated in order, and on the first WHEN that evaluates to TRUE, the corresponding THEN value will be assigned to the column alias, Master_Status.
What you have actually already works, I believe your case statement is just ALWAYS true (so Master_Status is always not null.
See below:
declare #allnames as table ([name] int);
insert into #allnames([name])
values (1),(0)
;WITH MasterStatus as (
select
[name]
,case WHEN [name] = 1 then 'outcome1'
else NULL end as 'Master_Status'
from #allnames
)
select
[name]
from MasterStatus where Master_Status is not null

SQL Query : should return Single Record if Search Condition met, otherwise return Multiple Records

I have table with Billions of Records, Table structure is like :
ID NUMBER PRIMARY KEY,
MY_SEARCH_COLUMN NUMBER,
MY_SEARCH_COLUMN will have Numeric value upto 15 Digit in length.
What I want is, if any specific record is matched, I will have to get that matched value only,
i.e. : If I enter WHERE MY_SEARCH_COLUMN = 123454321 and table has value 123454321 then this only should be returned.
But if exact value is not matched, I will have to get next 10 values from the table.
i.e. : if I enter WHERE MY_SEARCH_COLUMN = 123454321 and column does not have the value 123454321 then it should return 10 values from the table which is greater than 123454321
Both the case should be covered in single SQL Query, and I have have to keep in mind the Performance of the Query. I have already created Index on the MY_SEARCH_COLUMN columns, so other suggestions are welcome to improve the Performance.
This could be tricky to do without using a proc or maybe some dynamic SQL, but we can try using ROW_NUMBER here:
WITH cte AS (
SELECT ID, MY_SEARCH_COLUMN,
ROW_NUMBER() OVER (ORDER BY MY_SEARCH_COLUMN) rn
FROM yourTable
WHERE MY_SEARCH_COLUMN >= 123454321
)
SELECT *
FROM cte
WHERE rn <= CASE WHEN EXISTS (SELECT 1 FROM yourTable WHERE MY_SEARCH_COLUMN = 123454321)
THEN 1
ELSE 10 END;
The basic idea of the above query is that we assign a row number to all records matching the target or greater. Then, we query using either a row number of 1, in case of an exact match, or all row numbers up to 10 in case of no match.
SELECT *
FROM your_table AS src
WHERE src.MY_SEARCH_COLUMN = CASE WHEN EXISTS (SELECT 1 FROM your_table AS src2 WITH(NOLOCK) WHERE src2.MY_SEARCH_COLUMN = 123456321)
THEN 123456321
ELSE src.MY_SEARCH_COLUMN
END

Finding Null values in multiple columns in SQL [duplicate]

This question already has answers here:
How to count in SQL all fields with null values in one record?
(4 answers)
Closed 7 years ago.
What are the best and the most efficient way of finding null values in multiple columns. For example:
Name Location Age Address
Mike CLT 19 Null
Null NY 28 Null
and so on...
I just need to find out if there is any NULL value in any of these columns.
Check this query. Hope this gives you desired result.
Select * from YourTableName
where Name is null
or location is null
or age is null
or address is null
if you want to know if there are nulls in any column, this could be a good trick to generate an XML file from the rows containing those nulls; it should work for almost any table, just replace 'yourtable' with the name of the relevant table:
SELECT
CAST (
(SELECT * FROM yourtable FOR XML path('x'),ELEMENTS XSINIL)
AS XML)
.query('//.[#xsi:nil="true"]/..')
Try using IS NULL in where clause:
SELECT *
FROM mytable
WHERE name IS NULL OR address IS NULL
Try this:
select *
from YourTable yt
where yt.Name+yt.Location+CONVERT(varchar(20),yt.Age)+yt.Address is null
Remember to convert all column to the same datatype.