Posts

Showing posts from September, 2020

Fill null values with last non-null amount - Oracle SQL

  I have a table that has 4 columns: Item, Year, Month, Amount. Some of the values for Amount are null and when that happens I want to fill those values in with the previous Amount value that is not null. I can easily do this with the LAG function when there is only one null value but when there are multiple in a row I am not sure how to approach it. Below is an example of what the table might look like with an added column for what I want to add in my query: Item | Year | Month | Amount | New_Amount AAA | 2013 | 01 | 100 | 100 AAA | 2013 | 02 | | 100 AAA | 2013 | 03 | 150 | 150 AAA | 2013 | 04 | 125 | 125 AAA | 2013 | 05 | | 125 AAA | 2013 | 06 | | 125 AAA | 2013 | 07 | | 125 AAA | 2013 | 08 | 175 | 175 I had two ideas which I can't seem to get to work to produce what I want. First I was going to use LAG but then I noticed when there are multiple null values in a row it won't satisfy that. Next I was going...

Oracle Interview Question and Answer

Image
  Why does the same query takes different amount of time to run?    There are three broad reasons that queries take longer at different times. Either you are getting different performance because the system is under a different sort of load, you are getting different performance because of data volume changes, or you are getting different performance because you are getting different query plans. Different Data Volume When you generate your initial timings, are you using data volumes that are similar to the volumes that your query will encounter when it is actually run? If you test a query on the first of the month and that query is getting all the data for the current month and performing a bunch of aggregations, you would expect that the query would get slower and slower over the course of the month because it had to process more and more data. Or you may have a query that runs quickly outside of month-end processing because various staging tables that it depends on o...

Cursor Query

 --set SERVEROUTPUT ON -------------------------------FETCHING RECORDS IN SCALAR VARIABLE------------------------------------ DECLARE     v_name VARCHAR2(100); BEGIN     SELECT first_name        INTO v_name     FROM employees     WHERE employee_id=100;          dbms_output.put_line('v_name '||v_name); END; / --------------------------FETCHING RECORDS INTO COLLECTION OBJECT---------------------------------- DECLARE     TYPE lv_name_list_type IS TABLE OF VARCHAR2(100);     lv_name_list lv_name_list_type := lv_name_list_type(); BEGIN     SELECT first_name     BULK COLLECT INTO lv_name_list      FROM EMPLOYEES;          FOR I IN lv_name_list.first..lv_name_list.last     LOOP         dbms_output.put_line(lv_name_list(I));     END LOOP; END; / --------------------EXPLICT CURSOR WITH LOO...