Looking for performance improvements in the SQL - sql

Scenario:
There are 2 columns in the table with data as given in the sample below.
It is possible that the table has multiple rows for the same value of 'a' column.
In the example, Considering the 'a' column, There are three rows for '1' and one row for '2'.
Sample table 't1':
|a|b |
|1|1.1|
|1|1.2|
|1|2.2|
|2|3.1|
Requirement is to get following output:
Expected Query output:
|a|b |
|1|1.2|
|2|3.1|
Requirement:
Get the row if there is only one row for a given value for column 'a'.
If there are multiple rows for the same value for column 'a' and for all rows, FLOOR(b) == a, then get MIN(a) and MAX(b)
If there are multiple rows for column 'a' and for all rows, there is 1 row of column 'b' for which
FLOOR(b) > a, then ignore that row. from the remaining rows, get MIN(a) and MAX(b)
Query I used:
select distinct min(a) over(partition by table1.a) as a,
min(b) over(partition by table1.a) as b
from (
SELECT distinct Min(table2.a) OVER (PARTITION BY table2.a) AS a,
Max(table2.b) OVER (PARTITION BY table2.a) AS b
FROM t1 table2
union
SELECT distinct Min(table3.a) OVER (PARTITION BY table3.a) AS a,
Max(table3.b) OVER (PARTITION BY table3.a) AS b
FROM t1 table3
where table3.a = FLOOR(table3.b)
) table1;
This query is working and I am getting the desired output. Looking for inputs to improve by removing union and extra select from the above script.
Note: t1 is not a table but it's a procedure call in my case and there are additional columns that it returns. It would help if the extra call to the procedure can be avoided.

This is how I would get the data you need.
select t1.a, max(t1.b)
from (select a, b, count(1) over(partition by t1.a) cnt from t1) t1
where t1.a = floor(t1.b) or cnt = 1
group by t1.a ,cnt;
It has only one procedure call so it might run significantly faster
And please note that "union" clause not only appends two data sets, but removes duplicates as well. Removing duplicates causes additional checks between data sets and therefore is leading to performance issues.
It is in most cases better to use "union all" which doesn't check for duplicates

Related

Get rows in sequence from multiple table in SQL Server

I want to get all rows in sequence from 2 tables in SQL Server.
Output should be 1st row from 1st table, then 1st row from 2nd table,
2nd row from 1st table, 2nd row from 2nd table....etc
What #eshirvana suggested will not get you the desired. Instead, it'll be table1.row1, table2.row1, table2.row2, table1.row2
You can use UNION to join data from two tables when the column names and types match. I'm making an assumption on how to order the data based on your desired outcome.
SELECT RowID, Row, z
FROM table1
UNION
SELECT *
FROM table2
ORDER BY z, RowID
Here's the working code:
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=068c0fd2056cc48718345e85b74b7bba
probably something like that :
select * from
(
select rowID,Row,z from table1
union all
select rowID,Row,z from table2
) alltables
order by z
You can try with below approach:
SELECT * FROM
(
SELECT RowId,Row,Z,1 AS TableOrder From Table1
UNION ALL
SELECT RowId,Row,z,2 AS TableOrder From Table2
)
ORDER BY Z,TableOrder

What is the difference between Postgres DISTINCT vs DISTINCT ON?

I have a Postgres table created with the following statement. This table is filled by as dump of data from another service.
CREATE TABLE data_table (
date date DEFAULT NULL,
dimension1 varchar(64) DEFAULT NULL,
dimension2 varchar(128) DEFAULT NULL
) TABLESPACE pg_default;
One of the steps in a ETL I'm building is extracting the unique values of dimension1 and inserting them in another intermediary table.
However, during some tests I found out that the 2 commands below do not return the same results. I would expect for both to return the same sum.
The first command returns more results compared with the second (1466 rows vs. 1504.
-- command 1
SELECT DISTINCT count(dimension1)
FROM data_table;
-- command 2
SELECT count(*)
FROM (SELECT DISTINCT ON (dimension1) dimension1
FROM data_table
GROUP BY dimension1) AS tmp_table;
Any obvious explanations for this? Alternatively to an explanation, is there any suggestion of any check on the data I should do?
EDIT: The following queries both return 1504 (same as the "simple" DISTINCT)
SELECT count(*)
FROM data_table WHERE dimension1 IS NOT NULL;
SELECT count(dimension1)
FROM data_table;
Thank you!
DISTINCT and DISTINCT ON have completely different semantics.
First the theory
DISTINCT applies to an entire tuple. Once the result of the query is computed, DISTINCT removes any duplicate tuples from the result.
For example, assume a table R with the following contents:
#table r;
a | b
---+---
1 | a
2 | b
3 | c
3 | d
2 | e
1 | a
(6 rows)
SELECT distinct * from R will result:
# select distinct * from r;
a | b
---+---
1 | a
3 | d
2 | e
2 | b
3 | c
(5 rows)
Note that distinct applies to the entire list of projected attributes: thus
select distinct * from R
is semantically equivalent to
select distinct a,b from R
You cannot issue
select a, distinct b From R
DISTINCT must follow SELECT. It applies to the entire tuple, not to an attribute of the result.
DISTINCT ON is a postgresql addition to the language. It is similar, but not identical, to group by.
Its syntax is:
SELECT DISTINCT ON (attributeList) <rest as any query>
For example:
SELECT DISTINCT ON (a) * from R
It semantics can be described as follows. Compute the as usual--without the DISTINCT ON (a)---but before the projection of the result, sort the current result and group it according to the attribute list in DISTINCT ON (similar to group by). Now, do the projection using the first tuple in each group and ignore the other tuples.
Example:
select * from r order by a;
a | b
---+---
1 | a
2 | e
2 | b
3 | c
3 | d
(5 rows)
Then for every different value of a (in this case, 1, 2 and 3), take the first tuple. Which is the same as:
SELECT DISTINCT on (a) * from r;
a | b
---+---
1 | a
2 | b
3 | c
(3 rows)
Some DBMS (most notably sqlite) will allow you to run this query:
SELECT a,b from R group by a;
And this give you a similar result.
Postgresql will allow this query, if and only if there is a functional dependency from a to b. In other words, this query will be valid if for any instance of the relation R, there is only one unique tuple for every value or a (thus selecting the first tuple is deterministic: there is only one tuple).
For instance, if the primary key of R is a, then a->b and:
SELECT a,b FROM R group by a
is identical to:
SELECT DISTINCT on (a) a, b from r;
Now, back to your problem:
First query:
SELECT DISTINCT count(dimension1)
FROM data_table;
computes the count of dimension1 (number of tuples in data_table that where dimension1 is not null). This query
returns one tuple, which is always unique (hence DISTINCT
is redundant).
Query 2:
SELECT count(*)
FROM (SELECT DISTINCT ON (dimension1) dimension1
FROM data_table
GROUP BY dimension1) AS tmp_table;
This is query in a query. Let me rewrite it for clarity:
WITH tmp_table AS (
SELECT DISTINCT ON (dimension1)
dimension1 FROM data_table
GROUP by dimension1)
SELECT count(*) from tmp_table
Let us compute first tmp_table. As I mentioned above,
let us first ignore the DISTINCT ON and do the rest of the
query. This is a group by by dimension1. Hence this part of the query
will result in one tuple per different value of dimension1.
Now, the DISTINCT ON. It uses dimension1 again. But dimension1 is unique already (due to the group by). Hence
this makes the DISTINCT ON superflouos (it does nothing).
The final count is simply a count of all the tuples in the group by.
As you can see, there is an equivalence in the following query (it applies to any relation with an attribute a):
SELECT (DISTINCT ON a) a
FROM R
and
SELECT a FROM R group by a
and
SELECT DISTINCT a FROM R
Warning
Using DISTINCT ON results in a query might be non-deterministic for a given instance of the database.
In other words, the query might return different results for the same tables.
One interesting aspect
Distinct ON emulates a bad behaviour of sqlite in a much cleaner way. Assume that R has two attributes a and b:
SELECT a, b FROM R group by a
is an illegal statement in SQL. Yet, it runs on sqlite. It simply takes a random value of b from any of the tuples in the group of same values of a.
In Postgresql this statement is illegal. Instead, you must use DISTINCT ON and write:
SELECT DISTINCT ON (a) a,b from R
Corollary
DISTINCT ON is useful in a group by when you want to access a value that is functionally dependent on the group by attributes. In other words, if you know that for every group of attributes they always have the same value of the third attribute, then use DISTINCT ON that group of attributes. Otherwise you would have to make a JOIN to retrieve that third attribute.
The first query gives the number of not null values of dimension1, while the second one returns the number of distinct values of the column. These numbers obviously are not equal if the column contains duplicates or nulls.
The word DISTINCT in
SELECT DISTINCT count(dimension1)
FROM data_table;
makes no sense, as the query returns a single row. Maybe you wanted
SELECT count(DISTINCT dimension1)
FROM data_table;
which returns the number of distinct not null values of dimension1. Note, that it is not the same as
SELECT count(*)
FROM (
SELECT DISTINCT ON (dimension1) dimension1
FROM data_table
-- GROUP BY dimension1 -- redundant
) AS tmp_table;
The last query yields the number of all (null or not) distinct values of the column.
To learn and understand what happens by visual example.
Here's a bit of SQL to execute on a PostgreSQL:
DROP TABLE IF EXISTS test_table;
CREATE TABLE test_table (
id int NOT NULL primary key,
col1 varchar(64) DEFAULT NULL
);
INSERT INTO test_table (id, col1) VALUES
(1,'foo'), (2,'foo'), (3,'bar'), (4,null);
select count(*) as total1 from test_table;
-- returns: 4
-- Because the table has 4 records.
select distinct count(*) as total2 from test_table;
-- returns: 4
-- The count(*) is just one value. Making 1 total unique can only result in 1 total.
-- So the distinct is useless here.
select col1, count(*) as total3 from test_table group by col1 order by col1;
-- returns 3 rows: ('bar',1),('foo',2),(NULL,1)
-- Since there are 3 unique col1 values. NULL's are included.
select distinct col1, count(*) as total4 from test_table group by col1 order by col1;
-- returns 3 rows: ('bar',1),('foo',2),(NULL,1)
-- The result is already grouped, and therefor already unique.
-- So again, the distinct does nothing extra here.
select count(distinct col1) as total5 from test_table;
-- returns 2
-- NULL's aren't counted in a count by value. So only 'foo' & 'bar' are counted
select distinct on (col1) id, col1 from test_table order by col1 asc, id desc;
-- returns 3 rows: (2,'a'),(3,'b'),(4,NULL)
-- So it gets the records with the maximum id per unique col1
-- Note that the "order by" matters here. Changing that DESC to ASC would get the minumum id.
select count(*) as total6 from (select distinct on (col1) id, col1 from test_table order by col1 asc, id desc) as q;
-- returns 3.
-- After seeing the previous query, what else would one expect?
select distinct col1 from test_table order by col1;
-- returns 3 unique values : ('bar'),('foo'),(null)
select distinct id, col1 from test_table order by col1;
-- returns all records.
-- Because id is the primary key and therefore makes each returned row unique
Here's a more direct summary that might useful for Googlers, answering the title but not the intricacies of the full post:
SELECT DISTINCT
availability: ISO
behaviour:
SELECT DISTINCT col1, col2, col3 FROM mytable
returns col1, col2 and col3 and omits any rows in which all of the tuple (col1, col2, col3) are the same. E.g. you could get a result like:
1 2 3
1 2 4
because those two rows are not identical due to the 4. But you could never get:
1 2 3
1 2 4
1 2 3
because 1 2 3 appears twice, and both rows are exactly the same. That is what DISTINCT prevents.
vs GROUP BY: SELECT DISTINCT is basically a subset of GROUP BY where you can't use aggregate functions: Is there any difference between GROUP BY and DISTINCT
SELECT DISTINCT ON
availability: PostgreSQL extension, WONTFIXED by SQLite
behavior: unlike DISTINCT, DISTINCT ON allows you to separate
what you want to be unique
from what you want to return
E.g.:
SELECT DISTINCT ON(col1) col2, col3 FROM mytable
returns col2 and col3, and does not return any two rows with the same col1. E.g.:
1 2 3
1 4 5
could not happen, because we have 1 twice on col1.
And e.g.:
SELECT DISTINCT ON(col1, col2) col2, col3 FROM mytable
would prevent any duplicated (col1, col2) tuples, e.g. you could get:
1 2 3
1 4 3
as it has different (1, 2) and (1, 4) tuples, but not:
1 2 3
1 2 4
where (1, 2) happens twice, only one of those two could appear.
We can uniquely determine which one of the possible rows will be selected with ORDER BY which guarantees that the first match is taken, e.g.:
SELECT DISTINCT ON(col1, col2) col2, col3 FROM mytable
ORDER BY col1 DESC, col2 DESC, col3 DESC
would ensure that among:
1 2 3
1 2 4
only 1 2 4 would be picked as it happens first on our DESC sorting.
vs GROUP BY: DISTINCT ON is not a subset of GROUP BY because it allows you to access extra rows not present in the GROUP BY, which is generally not allowed in GROUP BY, unless:
you group by primary key in Postgres (unique not null is a TODO for them)
or if that is allows as an ISO extension as in SQLite/MySQL
This makes DISTINCT ON extremely useful to fulfill the common use case of "find the full row that reaches the maximum/minimum of some column": Is there any difference between GROUP BY and DISTINCT
E.g. to find the city of each country that has the most sales:
SELECT DISTINCT ON ("country") "country", "city", "amount"
FROM "Sales"
ORDER BY "country" ASC, "amount" DESC, "city" ASC
or equivalently with * if we want all columns:
SELECT DISTINCT ON ("country") *
FROM "Sales"
ORDER BY "country" ASC, "amount" DESC, "city" ASC
Here each country appears only once, within each country we then sort by amount DESC and take the first, and therefore highest, amount.
RANK and ROW_NUMBER window functions
These can be used basically as supersets of DISTINCT ON, and implemented tested as of both SQLite 3.34 and PostgreSQL 14.3. I highly recommend also looking into them, see e.g.: How to SELECT DISTINCT of one column and get the others?
This is how the above "city with the highest amount of each country" query would look like with ROW_NUMBER:
SELECT *
FROM (
SELECT
ROW_NUMBER() OVER (
PARTITION BY "country"
ORDER BY "amount" DESC, "city" ASC
) AS "rnk",
*
FROM "Sales"
) sub
WHERE
"sub"."rnk" = 1
ORDER BY
"sub"."country" ASC
Try
SELECT count(dimension1a)
FROM (SELECT DISTINCT ON (dimension1) dimension1a
FROM data_table
ORDER BY dimension1) AS tmp_table;
DISTINCT ON appears to be synonymous with GROUP BY.

How to select multiple columns while keeping one of them distinct

I want to select two columns (A & B) from a table and only keep the distinct values of one of them (A). However single value of A can map to multiple values of B. So the following query won't work
select distinct A, B from table1
I am thinking of something like this:
select A, agg(B) from table1 group by A
I want the agg function to just randomly pick a single value from B while grouping A. How to do it in Postgres?
If you want an arbitrary value ("any old value"), then min() and max() are arbitrary values:
select a, min(b) as b
from table1
group by a;
If you want an indeterminate value ("value from any row that matches"), then:
select distinct on (a) a, b
from table1
order by a;
If you want a random value ("value from a random matching row chosen from a uniform distribution"), then:
select distinct on (a) a, b
from table1
order by a, random();
In other words, the definition of "random" is different from "arbitrary" and "indeterminate". However, distinct on is probably what you want along.
Use string_agg with comma :
select A, string_agg(distinct B,',') from table1 group by A;

Retrieve rows based on multiple data patterns

I have the following table data:
Qns: How do I retrieve only the rows highlighted in Yellow?
Thoughts: What I did try was to do a SUM(A), SUM(B), SUM(C) columns and group by ID_2 column. After which, filter using a WHERE clause on B=1 OR A=1 to retrieve the records. However, I am getting also getting the first record (A23,C1) too based on the select criteria. This is what I would like to avoid retrieving.
1) The first criteria is always to retrieve B=1 as priority for the same ID_2.
2) The second criteria is to retrieve those with A=1 only taking into account that of the first criteria. Hence, based on ID_2, if there is a valid B=1 records that has already been retrieved, it should not retrieve twice.
In this case, A34 is preferred rather than A23
(For instance, if based on ID_2, A or B both have 1, I would ONLY want
the row
whereby B=1. In addition, A67,A89 are retrieved too.
Appreciate the help in the generation of this SELECT statement.
I think this is what you want:
Select rows with B = 1
Select also rows with A = 1 provided that there is no other row
for the same ID_2 that has B = 1
If so, then this can be accomplished with this SQL:
SELECT ID_1, ID_2, A, B, C
FROM tableName t1
WHERE B = 1
OR ( A = 1
AND Not Exists (
SELECT 1
FROM tableName t2
WHERE t1.ID_2 = t2.ID_2
AND B = 1)
)
You can make an aggregated version as follows:
SELECT ID_2, SUM(A), SUM(B), SUM(C)
FROM tableName t1
WHERE B = 1
OR ( A = 1
AND Not Exists (
SELECT 1
FROM tableName t2
WHERE t1.ID_2 = t2.ID_2
AND B = 1)
)
GROUP BY ID_2

Combine 2 result sets in SQL?

How do I combine the resultsets to return a single result in SQL? For example -
SELECT * FROM Table1
SELECT * FROM Table2
I want to combine the two resultsets with the columns from the second resultset appended to the first.
Table 1 and Table 2 are not related to each other in any way. If Table 1 has 2 columns and Table 2 has 4 columns, I wanted 6 columns returned total in a single resultset. And if Table 1 has 4 rows and Table 2 has only 2 rows, I want NULLS in Table 2 rows for 3rd and 4th row.
Is it possible?
Edit: I do not know how many columns are present in Table1 and Table2, so cannot use UNION with nulls.
If your RDBMS supports ROW_NUMBER() you could do something like this.
WITH T1 AS
(
SELECT *, ROW_NUMBER() OVER ( ORDER BY T1id) AS RN1 FROM Table1
),
T2 AS
(
SELECT *, ROW_NUMBER() OVER ( ORDER BY T2id) AS RN2 FROM Table2
)
SELECT * FROM T1 FULL OUTER JOIN T2 ON RN1 =RN2
It's possible but it's probably quite a bad idea to do this. Why not just run two queries?
If you really want to do it, join the two result sets on a ROW_NUMBER() field.
Not a general solution, but works if you know your schema:
select a1, a2, null as b1, null as b2 from table1
union
select null as a1, null as a2, b1, b2 from table2