I have a transactional database with more than 100 columns. Now if I have to select all the rows but only those columns which have changed down the table (more than one distinct value for a particular column). how can I do it in ORACLE?
With my query, I have to manually write 100 lines to check if there is more than 1 distinct count for a particular column. It was tedious. I need some expertise here and if we have any easy method.
SELECT id,
CASE WHEN COUNT(DISTINCT column1) > 1 THEN column1 END AS column1,
CASE WHEN COUNT(DISTINCT column2) > 1 THEN column2 END AS column2,
.
.
.
FROM your_table_name
GROUP BY id
2
Answers
The way I understood it, one option is to create a function which returns refcursor, composed from columns whose values have changed. In order to find them, gather table statistics and check
user_tab_columns
view’snum_distinct
column.Sample data: only
phone
column has changed:Function has to be an autonomous transaction because DDL (gathering table stats) implicitly commits.
Testing:
I think you can take a look into dynamicSQL queries for this – check out Oracle’s DynamicSQL, something along the lines:
Will help your usecase, this generates the dynamic SQL query by querying all tab columns to retrieve the column names for the specified table, it then constructs a query that includes a
CASE
expression for each column, checking if the distinct count is greater than 1. The generated query is stored in thev_query
variable and is executed usingEXECUTE IMMEDIATE
.