How to remove duplicate rows in Google BigQuery based on a unique identifier - google-bigquery

In SQL, I use the following code to remove duplicates from a table based on a unique ID:
1. SELECT Unique_ID INTO holdkey FROM [Origination] GROUP BY Unique_ID HAVING count(*) > 1
2. SELECT DISTINCT Origination.*
INTO holddups
FROM [Origination], holdkey
WHERE [Origination].Unique_ID = holdkey.Unique_ID
3. DELETE Origination
FROM Origination, holdkey
WHERE Origination.Unique_ID = holdkey.Unique_ID
4. INSERT Origination SELECT * FROM holddups
The second process does not work on BigQuery. Regardless of how I change the query, I get errors for unrecognized columns and tables.
I obviously take out "select into" queries and just set the destination tables manually. I have SQL experience, and I know the process works. Does anyone have a sample of syntax that they use for the process of removing duplicate records based on a unique ID for BQ? Or a way to modify this that would make it run?

So, the trick is in having proper SELECT here
Below example is for BigQuery Standard SQL
#standardSQL
SELECT row[OFFSET(0)].* FROM (
SELECT ARRAY_AGG(t ORDER BY value DESC LIMIT 1) row
FROM `project.dataset.table_with_dups` t
GROUP BY id
)
you can test / play with above using dummy data as below
#standardSQL
WITH `project.dataset.table_with_dups` AS (
SELECT 1 id, 2 value UNION ALL SELECT 1,3 UNION ALL SELECT 1,4 UNION ALL
SELECT 2,5 UNION ALL
SELECT 3,6 UNION ALL SELECT 3,7 UNION ALL
SELECT 4,8 UNION ALL
SELECT 5,9 UNION ALL SELECT 5,10
)
SELECT row[OFFSET(0)].* FROM (
SELECT ARRAY_AGG(t ORDER BY value DESC LIMIT 1) row
FROM `project.dataset.table_with_dups` t
GROUP BY id
)
with result as
Row id value
1 1 4
2 2 5
3 3 7
4 4 8
5 5 10
As you can see it easily dedups table by id leaving row with largest value. Does not matter how many more other columns in that table - above still works (it does not care of schema rather than id and value)
So, now, you can just use above SELECT and insert result into new table or overwrite original, etc. - all in one shot!

Related

Trying to create Row number for Distinct values in BigQuery

On BigQuery, I'm trying to get the row count of the distinct values to display for easy reference.
Assuming I have 1000 distinct values and I'm trying to get the 340th row of distinct value, how should i code it.
I tried to run
SELECT
DISTINCT column_2
FROM
table
and sure it turns out all the DISTINCT values of column_2. But how do i add the row number beside, and would I be able to put a WHERE for the row number?
Consider below approach
select distinct column_2
from your_table
qualify 340 = dense_rank() over(order by column_2)
Since BigQuery works parallelized there is no guarantee/need for any sorting of table rows. That also means there are no row numbers.
If you want the nth element of a query result you need to define a sorting logic beforehand. You can use navigational functions for that, or a LIMIT with OFFSET if you need one exact value
with t as (
select 'a' as val
union all select 'a'
union all select 'b'
union all select 'c'
union all select 'c'
union all select 'f'
union all select 'y'
union all select 'z'
union all select 'a'
)
select
distinct val
from t
order by 1
-- 5th element has offset 4
limit 1 offset 4

Db2 get values which are not present in list

I have a hardcoded list of ids ex. 1,2,3. I want to get list of ids that are not present in database. Ex. Database have 1,2 so expected result is 3.
Database is read only so I cannot use values clause.
In DB2 you can create a derived table with values using sysibm.sysdummy1. So one method is:
select id
from (select 1 as id from sysibm.sysdummy1 union all
select 1 from sysibm.sysdummy1 union all
select 1 from sysibm.sysdummy1
) x
except
select id
from t;

SQLite - Return Rows Even If They Are Duplicates

I have a simple SQLite table which has just one ID column.
I have some variable IDs that may be duplicates of each other like: 1,2,3,4,3,1 (These IDs are just examples, there could be hundreds of them).
And I have a simple query as follows:
SELECT ID FROM TABLE WHERE ID in (1,2,3,4,3,1)
In the usual case the answer contains only 4 rows with ids 1,2,3,4. Is there any way to force SQLite to return rows in the order of the request (1,2,3,4,3,1) even if they are duplicates?
I have n IDs in my query and I want n rows in return even if they are duplicates.
Edit: The Table Definition is:
CREATE TABLE TEST(ID TEXT PRIMARY KEY)
You can use left join:
select t.*
from (select 1 as id, 1 as ord union all
select 2 as id, 2 as ord union all
select 3 as id, 3 as ord union all
select 4 as id, 4 as ord union all
select 3 as id, 5 as ord union all
select 1 as id, 6 as ord
) ids left join
t
on t.id = ids.id
order by ids.ord;

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 do I LIMIT the number of rows in a DELETE with DB2?

I want to add a security on a sensitive table when I delete lines with an SQL request on a DB2 table.
I want to mimic the way MySQL allows you to limit the numbers of rows deleted in an SQL request.
Basically I want to do this with DB2 :
DELETE FROM table WHERE info = '1' LIMIT 1
Is there a way to do that with DB2 ?
delete from table where id in (select id from table where info = '1' order by id fetch first 1 rows only)
It really depends on your platform.
If you're using DB2 on Linux/Unix/Windows, you can just create a select that gets the rows you want, and put that as a subquery for your delete, and DB2 will be able to delete the results of your select. Like so:
DELETE FROM (
SELECT 1
FROM table
WHERE info = '1'
ORDER BY your_key_columns
FETCH FIRST ROW ONLY
) AS A
;
If you're on DB2 for z/OS, that syntax doesn't work, unfortunately. But, you can use your primary keys to do basically the same thing (this one also works on LUW):
DELETE FROM table
WHERE (info, key2) IN (
SELECT info, key2
FROM table
WHERE info = 1
ORDER BY key2
FETCH FIRST ROW ONLY
);
Here is an example script that demonstrates how it's used:
DECLARE GLOBAL TEMPORARY TABLE SESSION.TEST(
ID INT
,RN INT
) ON COMMIT PRESERVE ROWS;
INSERT INTO SESSION.TEST
SELECT 1,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 1,2 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 1,3 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 1,4 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 1,5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 2,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 2,2 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 2,3 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 3,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 3,2 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 3,3 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 4,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 4,2 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 5,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 6,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 7,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 8,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 9,1 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 10,1 FROM SYSIBM.SYSDUMMY1
;
SELECT * FROM SESSION.TEST ORDER BY ID, RN;
-- LUW Version
DELETE FROM (
SELECT 1
FROM SESSION.TEST
WHERE ID = 1
ORDER BY RN
FETCH FIRST ROW ONLY
) AS A
;
--Mainframe version
DELETE FROM SESSION.TEST
WHERE (ID, RN) IN (
SELECT ID, RN
FROM SESSION.TEST
WHERE ID = 1
ORDER BY RN
FETCH FIRST ROW ONLY
);
SELECT * FROM SESSION.TEST ORDER BY ID, RN;
DROP TABLE SESSION.TEST;
On IBMi DB2:
DELETE FROM table WHERE RRN(table) in
(SELECT RRN(table) FROM table WHERE col1 = '1' AND col2 = '2' FETCH FIRST 5 ROWS ONLY)
If your primary key has multiple values, or you just need multiple values as the condition, this is the query that works:
DELETE FROM TABLE
WHERE (COLUMN1, COLUMN2) IN (
SELECT COLUMN1, COLUMN2 FROM TABLE
WHERE SOME_COLUMN='THIS'
AND SOME_OTHER_COLUMN LIKE 'THAT%'
FETCH FIRST 10 ROWS ONLY)
How is this query?
delete from table D where exists
( select * from ( select * from table M fetch first 10 rows only ) as M
where M.object_id = D.object_id )
MERGE INTO XYZ A<BR>
USING (<BR>
SELECT RID_BIT(B) CHAVE<BR>
FROM XYZ B<BR>
FETCH FIRST 100000 ROWS ONLY) B<BR>
ON RID_BIT(A) = B.CHAVE<BR>
WHEN MATCHED THEN DELETE;
Just select a statement, and put the statement inside the delete query:
delete from (
select from table WHERE info = '1' order by id fetch first 25000 rows only
)
DELETE
FROM Bibl/File
WHERE RRN(File) = (
SELECT min(RRN(File))
FROM Bibl/File
WHERE Fld1 = 'xx'
)
The RRN function is to AS400/iSeries/PowerSystem alone. In other environments there are other functions for the relative record number.
This makes it possible to erase a record of several identical even without UNIQUE key. It can also be used to update with minor changes.
works like the LIMIT but with DELETE and / or UPDATE.
It only works on SQL DB2 in other settings should be changed by RRN function to return the column number
DELETE FROM table
WHERE info = '1'
FETCH FIRST 1 ROWS ONLY