DB2 SQL Select All With Columns As - sql

I am working with some SQL queries on DB2. Is it possible to select all the columns in a table and also specify certain conditions using the "as" keyword within that select statement? For example, is this query possible:
select
*,
col1 + col2 as sum1,
col3 - col4 as dif1
from
table;
Whenever I attempt this, I am getting the SQL0104 error and it is saying "Token , was not valid. Valid tokens: FROM INTO".
Thank you for your help.
EDIT:
This query is running inside an SQLRPGLE program on an AS400.

Put your table alias in front of the *. So:
select
t.*,
col1 + col2 as sum1,
col3 - col4 as dif1
from
table t;

Related

SQL query to find columns having at least one non null value

I am developing a data validation framework where I have this requirement of checking that the table fields should have at least one non-null value i.e they shouldn't be completely empty having all values as null.
For a particular column, I can easily check using
select count(distinct column_name) from table_name;
If it's greater than 0 I can tell that the column is not empty. I already have a list of columns. So, I can execute this query in the loop for every column but this would mean a lot of requests and it is not the ideal way.
What is the better way of doing this? I am using Microsoft SQL Server.
I would not recommend using count(distinct) because it incurs overhead for removing duplicate values. You can just use count().
You can construct the query for counts using a query like this:
select count(col1) as col1_cnt, count(col2) as col2_cnt, . . .
from t;
If you have a list of columns you can do this as dynamic SQL. Something like this:
declare #sql nvarchar(max);
select #sql = concat('select ',
string_agg(concat('count(', quotename(s.value), ') as cnt_', s.value),
' from t'
)
from string_split(#list) s;
exec sp_executesql(#sql);
This might not quite work if your columns have special characters in them, but it illustrates the idea.
You should probably use exists since you aren't really needing a count of anything.
You don't indicate how you want to consume the results of multiple counts, however one thing you could do is use concat to return a list of the columns meeting your criteria:
The following sample table has 5 columns, 3 of which have a value on at least 1 row.
create table t (col1 int, col2 int, col3 int, col4 int, col5 int)
insert into t select null,null,null,null,null
insert into t select null,2,null,null,null
insert into t select null,null,null,null,5
insert into t select null,null,null,null,6
insert into t select null,4,null,null,null
insert into t select null,6,7,null,null
You can name the result of each case expression and concatenate, only the columns that have a non-null value are included as concat ignores nulls returned by the case expressions.
select Concat_ws(', ',
case when exists (select * from t where col1 is not null) then 'col1' end,
case when exists (select * from t where col2 is not null) then 'col2' end,
case when exists (select * from t where col3 is not null) then 'col3' end,
case when exists (select * from t where col4 is not null) then 'col4' end,
case when exists (select * from t where col5 is not null) then 'col5' end)
Result:
col2, col3, col5
I asked a similar question about a decade ago. The best way of doing this in my opinion would meet the following criteria.
Combine the requests for multiple columns together so they can all be calculated in a single scan.
If the scan encounters a not null value in every column under consideration allow it to exit early without reading the rest of the table/index as reading subsequent rows won't change the result.
This is quite a difficult combination to get in practice.
The following might give you the desired behaviour
SELECT DISTINCT TOP 2 ColumnWithoutNull
FROM YourTable
CROSS APPLY (VALUES(CASE WHEN b IS NOT NULL THEN 'b' END),
(CASE WHEN c IS NOT NULL THEN 'c' END)) V(ColumnWithoutNull)
WHERE ColumnWithoutNull IS NOT NULL
OPTION ( HASH GROUP, MAXDOP 1, FAST 1)
If it gives you a plan like this
Hash match usually reads all its build input first meaning that no shortcircuiting of the scan will happen. If the optimiser gives you an operator in "flow distinct" mode it won't do this however and the query execution can potentially stop as soon as TOP receives its first two rows signalling that a NOT NULL value has been found in both columns and query execution can stop.
But there is no hint to request the mode for hash aggregate so you are dependent on the whims of the optimiser as to whether you will get this in practice. The various hints I have added to the query above are an attempt to point it in that direction however.

Insert Statement for List

I'm not too sure how to describe my SQL Insert statement so I will describe the expected result.
I'm building a data extract list and have a table that I've put all my data into. It's called _MATTER_LIST
What I am trying to Achieve is to have the Client_Number + Col1 combination repeat after every unique COL1+COL2+COL3 combination but not duplicate when there is already a CLIENT_NUMBER+COL1. So the end result would be:
thanks in advance for any tips.
Simple ORDER BY should work for you if i understand. Try this :
select Client_Number, Col1, Col2, Col3 from _MATTER_LIST
order by Client_Number, Col1
I've managed to fix my own issue. I added a unique key for the col1 + col2 + col3 , then make col2 repeat over each combination for example.
The result is: select * from _MATTER_LIST order by COL4, COL5

SQL parametrised query containing multiple options

I would like to write a query
Select col1, col2
from table
where col1 = 'blah' or 'blah2' or 'blah3'
and col2 = 'blah' or 'blah2' or 'blah3'
I am used to writing them like this for a SINGLE option
select
col1, col2
from
table
where
col1 = :col1 and col2 = :col2
Parameters.AddWithValue(":col1", 'blah')
Parameters.AddWithValue(":col2", 'blah')
Now I want to add several options with OR between them and obviously the above code wont work. The SQL is for SQLite. Can anyone suggest how I could do this? I may potential have more then 3 different values for each parameter. I have tried searching but the answer is elusive.
You still have to use complete expressions, i.e., you need to write col1 = or col2 = every time.
Alternative, use IN:
SELECT ... WHERE col1 IN (:c11, :c12, :c13) AND col2 IN (:c21, :c22, :c23);

Access query doesn't work with DISTINCT and Val()

I have a query
SELECT col1, Val(col2)
FROM table1;
where col2 is a text data type.
I want to use DISTINCT here,
SELECT DISTINCT col1, Val(col2)
FROM table1;
but when I add it, I have an error
"Data type mismatch in criteria expression".
I have the same error when I try to sort the column2 (for the first query). Why?
The Val function doesn't process NULL values. Change your second column to Val(nz(col2,""))
I'm answering my question.
Because some of the rows have NULL value in col2 and SQL cannot compare two NULLs to find distinct rows, one should add WHERE col2 IS NOT NULL.
SELECT DISTINCT col1, Val(col2)
FROM table1
WHERE col2 IS NOT NULL;

SQL Replace duplicate entries with blanks

I have a SQL Table like this one:
and I want the output to be like this:
Basically:
replace duplicates with blanks but
if col6 value is different from the previous row for the same
col1
value, all the data fields should be included.
col10 values are blank.
col12 is removed.
I am struggling to create a query.
I found this: CTE answer
and tried to run the following:
;WITH CTE
AS
(
SELECT DBA.s12.*,
ROW_NUMBER() OVER(PARTITION BY DBA.s12.col6 ORDER BY(SELECT 1)) rownum
FROM DBA.s12
)
SELECT
DBA.s12.col1,
DBA.s12.col2,
DBA.s12.col3,
DBA.s12.col4,
DBA.s12.col5,
DBA.s12.col7,
DBA.s12.col8,
DBA.s12.col9,
DBA.s12.col10,
DBA.s12.col11,
DBA.s12.col12,
CASE rownum
WHEN 1 THEN DBA.s12.col6
ELSE ''
END AS col6
FROM CTE
ORDER BY DBA.s12.col1;
but I get an error "Could not execute statement. Syntax error or access violation"
Can anyone shed some light on where my query has a syntax error/access violation or have a better method to extract the data?
I am not entirely sure if this will work, but maybe try to replace
END AS col6
with
END AS DBA.s12.col6