Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Sunday, 17 November 2024

Oracle SQL + How to split a string in Oracle using substr/instr

1 comments

 Table Name: GLCC

Column Name: criteria

Column Value: ALAM-**-98000-10301990-***-***************-*****-OPR**

SELECT

   criteria,INSTR(criteria,'-',1,1) AS first_comma,

   INSTR(criteria,'-',1,2) AS second_comma,

   INSTR(criteria,'-',1,3) AS third_comma

   ,INSTR(criteria,'-',1,4) AS fourth_comma,

   INSTR(criteria,'-',1,5) AS fifth_comma,

   SUBSTR(criteria,1,INSTR(criteria,'-',1,1)-1) column1

   ,SUBSTR(criteria

             ,INSTR(criteria,'-',1,1) + 1

             ,INSTR(criteria,'-',1,2)

              - INSTR(criteria,'-',1,1)

              - 1)

       AS column2

         ,SUBSTR(criteria

             ,INSTR(criteria,'-',1,2) + 1

             ,INSTR(criteria,'-',1,3)

              - INSTR(criteria,'-',1,2)

              - 1)

       AS column3       

                ,SUBSTR(criteria

             ,INSTR(criteria,'-',1,3) + 1

             ,INSTR(criteria,'-',1,4)

              - INSTR(criteria,'-',1,3)

              - 1)

       AS column4  

                       ,SUBSTR(criteria

             ,INSTR(criteria,'-',1,4) + 1

             ,INSTR(criteria,'-',1,5)

              - INSTR(criteria,'-',1,4)

              - 1)

       AS column5 

                       ,SUBSTR(criteria

             ,INSTR(criteria,'-',1,5) + 1

             ,INSTR(criteria,'-',1,6)

              - INSTR(criteria,'-',1,5)

              - 1)

       AS column6

                       ,SUBSTR(criteria

             ,INSTR(criteria,'-',1,6) + 1

             ,INSTR(criteria,'-',1,7)

              - INSTR(criteria,'-',1,6)

              - 1)

       AS column7

             ,SUBSTR(criteria

             ,INSTR(criteria,'-',1,7) + 1)

       AS column8

              FROM

    glcc;  

Wednesday, 27 April 2022

How to display column values in a row in oracle?

2 comments

 SELECT

   deptno,

   RTRIM(xmlagg (xmlelement (e, ename || ',')).extract ('//text()'), ',') enames

FROM emp

GROUP BY deptno;


Your's

Amar Alam

Monday, 18 April 2022

Oracle + Check Materialized View last refresh date and Time

9 comments

SELECT

owner,

mview_name,

TO_CHAR(last_refresh_date, 'yyyymmddhh24miss') last_refresh_date

FROM all_mviews

WHERE 1=1

AND owner = 'APPS'

AND mview_name = 'XXVFI_SFDC_BOM_HDR_MV'


Regards,

Amar

Friday, 4 December 2020

Oracle SQL + How to concatenate time to a date

0 comments

1). select to_date ('17-Feb-2019' || ' 23:59:00', 'dd-mon-yyyy hh24:mi:ss') from dual;

2). If you're passing a DATE variable and a STRING below query should works

select to_date ( to_char(DATE_VARIABLE, 'dd-mon-yyyy') || ' 23:59:00', 'dd-mon-yyyy hh24:mi:ss') from( select to_date('17-Feb-2019', 'dd-mon-yyyy') as DATE_VARIABLE   from dual);

Thanks

Amar Alam

Thursday, 25 August 2016

Query To Get The Number of Seconds or Minutes or Hours Between Two Given Dates

100 comments
For the Seconds:-
-------------------

SELECT ('Your first Date'-'Your another Date') * DECODE( UPPER('SS')
, 'SS', 24*60*60
, 'MI', 24*60
, 'HH', 24, NULL )
FROM DUAL;

Example:-
SELECT (SYSDATE+1-SYSDATE) * DECODE( UPPER('SS')
, 'SS', 24*60*60
, 'MI', 24*60
, 'HH', 24, NULL )
FROM DUAL;

For Minutes:-
---------------

SELECT ('Your first Date'-'Your another Date') * DECODE( UPPER('MI')
, 'SS', 24*60*60
, 'MI', 24*60
, 'HH', 24, NULL )
FROM DUAL;

Example:-
SELECT (SYSDATE+1-SYSDATE) * DECODE( UPPER('MI')
, 'SS', 24*60*60
, 'MI', 24*60
, 'HH', 24, NULL )
FROM DUAL;

For the Hours:-
-----------------

SELECT ('Your first Date'-'Your another Date') * DECODE( UPPER('HH')
, 'SS', 24*60*60
, 'MI', 24*60
, 'HH', 24, NULL )
FROM DUAL;

Example:-
SELECT (SYSDATE+1-SYSDATE) * DECODE( UPPER('HH')
, 'SS', 24*60*60
, 'MI', 24*60
, 'HH', 24, NULL )
FROM DUAL;

Thanks
Amar Alam

Thursday, 14 January 2016

PL/SQL - Date & Time

11 comments

PL/SQL provides two classes of date and time related data types:
  • Datetime data types
  • Interval data types
The Datetime data types are:
  • DATE
  • TIMESTAMP
  • TIMESTAMP WITH TIME ZONE
  • TIMESTAMP WITH LOCAL TIME ZONE
The Interval data types are:
  • INTERVAL YEAR TO MONTH
  • INTERVAL DAY TO SECOND
Field Values for Datetime and Interval Data Types
Both datetime and interval data types consist of fields. The values of these fields determine the value of the datatype. The following table lists the fields and their possible values for datetimes and intervals.
Field Name
Valid Datetime Values
Valid Interval Values
YEAR
-4712 to 9999 (excluding year 0)
Any nonzero integer
MONTH
01 to 12
0 to 11
DAY
01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the calendar for the locale)
Any nonzero integer
HOUR
00 to 23
0 to 23
MINUTE
00 to 59
0 to 59
SECOND
00 to 59.9(n), where 9(n) is the precision of time fractional seconds
The 9(n) portion is not applicable for DATE.
0 to 59.9(n), where 9(n) is the precision of interval fractional seconds
TIMEZONE_HOUR
-12 to 14 (range accommodates daylight savings time changes)
Not applicable for DATE or TIMESTAMP.
Not applicable
TIMEZONE_MINUTE
00 to 59
Not applicable for DATE or TIMESTAMP.
Not applicable
TIMEZONE_REGION
Not applicable for DATE or TIMESTAMP.
Not applicable
TIMEZONE_ABBR
Not applicable for DATE or TIMESTAMP.
Not applicable
The Datetime Data Types and Functions
Following are the Datetime data types:
  • DATE - it stores date and time information in both character and number datatypes. It is made of information on century, year, month, date, hour, minute, and second. It is specified as:
  • TIMESTAMP - it is an extension of the DATE datatype. It stores the year, month, and day of the DATE datatype, along with hour, minute, and second values. It is useful for storing precise time values.
  • TIMESTAMP WITH TIME ZONE - it is a variant of TIMESTAMP that includes a time zone region name or a time zone offset in its value. The time zone offset is the difference (in hours and minutes) between local time and UTC. This datatype is useful for collecting and evaluating date information across geographic regions.
  • TIMESTAMP WITH LOCAL TIME ZONE - it is another variant of TIMESTAMP that includes a time zone offset in its value.
Following table provides the Datetime functions (where, x has datetime value):
S.N
Function Name & Description
1
ADD_MONTHS(x, y);
Adds y months to x.
2
LAST_DAY(x);
Returns the last day of the month.
3
MONTHS_BETWEEN(x, y);
Returns the number of months between x and y.
4
NEXT_DAY(x, day);
Returns the datetime of the next day after x.
5
NEW_TIME;
Returns the time/day value from a time zone specified by the user.
6
ROUND(x [, unit]);
Rounds x;
7
SYSDATE();
Returns the current datetime.
8
TRUNC(x [, unit]);
Truncates x.
Timestamp functions (where, x has a timestamp value):
S.N
Function Name & Description
1
CURRENT_TIMESTAMP();
Returns a TIMESTAMP WITH TIME ZONE containing the current session time along with the session time zone.
2
EXTRACT({ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND } | { TIMEZONE_HOUR | TIMEZONE_MINUTE } | { TIMEZONE_REGION | } TIMEZONE_ABBR ) FROM x)
Extracts and returns a year, month, day, hour, minute, second, or time zone from x;
3
FROM_TZ(x, time_zone);
Converts the TIMESTAMP x and time zone specified by time_zone to a TIMESTAMP WITH TIMEZONE.
4
LOCALTIMESTAMP();
Returns a TIMESTAMP containing the local time in the session time zone.
5
SYSTIMESTAMP();
Returns a TIMESTAMP WITH TIME ZONE containing the current database time along with the database time zone.
6
SYS_EXTRACT_UTC(x);
Converts the TIMESTAMP WITH TIMEZONE x to a TIMESTAMP containing the date and time in UTC.
7
TO_TIMESTAMP(x, [format]);
Converts the string x to a TIMESTAMP.
8
TO_TIMESTAMP_TZ(x, [format]);
Converts the string x to a TIMESTAMP WITH TIMEZONE.
Examples:
The following code snippets illustrate the use of the above functions:
SELECT SYSDATE FROM DUAL;
Output:
08/31/2012 5:25:34 PM
SELECT TO_CHAR(CURRENT_DATE, 'DD-MM-YYYY HH:MI:SS') FROM DUAL;
Output:
31-08-2012 05:26:14
SELECT ADD_MONTHS(SYSDATE, 5) FROM DUAL;
Output:
01/31/2013 5:26:31 PM
SELECT LOCALTIMESTAMP FROM DUAL;
Output:
8/31/2012 5:26:55.347000 PM

The Interval Data Types and Functions
Following are the Interval data types:
  • INTERVAL YEAR TO MONTH - it stores a period of time using the YEAR and MONTH datetime fields.
  • INTERVAL DAY TO SECOND - it stores a period of time in terms of days, hours, minutes, and seconds.
Interval functions:
S.N
Function Name & Description
1
NUMTODSINTERVAL(x, interval_unit);
Converts the number x to an INTERVAL DAY TO SECOND.
2
NUMTOYMINTERVAL(x, interval_unit);
Converts the number x to an INTERVAL YEAR TO MONTH.
3
TO_DSINTERVAL(x);
Converts the string x to an INTERVAL DAY TO SECOND.
4
TO_YMINTERVAL(x);
Converts the string x to an INTERVAL YEAR TO MONTH.




Ur's
Amar Alam

Thursday, 28 August 2014

Few Examples on Dynamic SQL

50 comments
------------------------------------------------------------------
DECLARE
v_table_name varchar2(100) := 'test_dept';
v_stmt varchar2(1000);
BEGIN
v_stmt := 'insert into '||v_table_name||' values(50,''HR'')';
execute immediate v_stmt;
dbms_output.put_line(v_stmt);
END;

-------------------------------------------------------------------
DECLARE
type sob_record is record
(
name gl_sets_of_books.NAME%type,
currency_code gl_sets_of_books.CURRENCY_CODE%type,
set_of_books gl_sets_of_books.SET_OF_BOOKS_ID%type
);
v_stmt varchar2(1000);
curr sys_refcursor;
row_rec sob_record;
BEGIN
v_stmt := 'select name,currency_code,set_of_books_id from gl_sets_of_books where set_of_books_id=:input';
open curr for v_stmt using 2023;
loop
fetch curr into row_rec;
exit when curr%notfound;
dbms_output.put_line(row_rec.currency_code || '    '||row_rec.name);
end loop;
END;


-------------------------------------------------------------------------------

DECLARE
type status_record is record
(
cid xx_account_status_swap.customer_number%type,
acc_status xx_account_status_swap.new_account_status%type
);
type status_table is table of status_record;

v_stmt varchar2(1000);
curr sys_refcursor;
status_coll status_table;
BEGIN
v_stmt := 'select customer_number,new_account_status from xx_account_status_swap where success_status=:input';

open curr for v_stmt using 'P';
fetch curr bulk collect into status_coll;

for i in 1..status_coll.count loop
dbms_output.put_line(status_coll(i).cid||'   '||status_coll(i).acc_status);
end loop;

dbms_output.put_line('----------------------------------------------');
dbms_output.put_line(status_coll.count);
dbms_output.put_line('----------------------------------------------');
END;

--------------------------------------------------------------------------------


Ur's
AmarAlam

Tuesday, 3 June 2014

Query to find the first word from a string

1 comments
 WITH qry
AS
(
   SELECT NULL field_name FROM dual
      UNION ALL
   SELECT 'AMAR' FROM dual
      UNION ALL
   SELECT 'AMAR ALAM' FROM dual
      UNION ALL
   SELECT 'Abdul M Faheem' FROM dual
      UNION ALL
   SELECT 'Sravan P. Kumar' FROM dual
      UNION ALL
   SELECT 'IBM India Pvt, Ltd' FROM dual
      UNION ALL
   SELECT 'IBM India Pvt, Ltd.' FROM dual
      UNION ALL
   SELECT 'IBM India Pvt Ltd' FROM dual
)
SELECT field_name,
       REGEXP_REPLACE(field_name, '^(\w+)(.*?)(\w*$)', '\1')  exp1,
       REGEXP_REPLACE(field_name, '^(\w+)(.*?)(\w*$)', '\2')  exp2,
       REGEXP_REPLACE(field_name, '^(\w+)(.*?)(\w*$)', '\3')  exp3
  FROM qry;




Ur's
AmarAlam

Monday, 3 March 2014

Splitting String Using Oracle SQL 9i

0 comments
 SELECT TRIM( SUBSTR ( txt
                     , INSTR (txt, ',', 1, level ) + 1
                     , INSTR (txt, ',', 1, level+1) - INSTR (txt, ',', 1, level) -1
                     )
            )
         AS token
   FROM ( SELECT ','||:in_string||',' AS txt  FROM dual )
 CONNECT BY level <= LENGTH(txt)-LENGTH(REPLACE(txt,',',''))-1

Example
-------
If value of in_string is entered as
7890,345,567,123,408

Output Is

TOKEN
======
7890
345
567
123
408


Thanks
Amar Alam

Wednesday, 12 February 2014

Multicolumn Subqueries

1 comments
We can compare elements having multiple values with the set of elements. This is called a multicolumn subquery.

CREATE TABLE EMPDEP(EMPNO NUMBER, DEPTNO NUMBER,SALARY NUMBER);

CREATE TABLE EMPCITY(EMPNO NUMBER, DEPTNO NUMBER,CITY VARCHAR2(30));

INSERT INTO EMPDEP VALUES (1,10,1000);

INSERT INTO EMPDEP VALUES (2,20,2000);

INSERT INTO EMPDEP VALUES (3,30,3000);

INSERT INTO EMPCITY VALUES (1,10,'NAGPUR');

INSERT INTO EMPCITY VALUES (2,20,'DELHI');

INSERT INTO EMPCITY VALUES (3,30,'NAGPUR');

SELECT * FROM EMPDEP

EMPNO DEPTNO SALARY
1 10 1000
2 20 2000
3 30 3000

SELECT * FROM EMPCITY

EMPNO DEPTNO CITY
1 10 NAGPUR
2 20 DELHI
3 30 NAGPUR

SELECT E1.EMPNO, E1.DEPTNO,E1.SALARY
FROM EMPDEP E1 WHERE (E1.EMPNO,E1.DEPTNO)
IN (SELECT E2.EMPNO,E2.DEPTNO FROM EMPCITY E2 WHERE CITY = 'NAGPUR')

EMPNO DEPTNO SALARY
1 10 1000
3 30 3000



Thanks
AmarAlam

Wednesday, 14 August 2013

Some Interesting SQL Queries

0 comments
Query to retrieve 1,4,7,10.....rows from a table

SELECT a.* FROM emp a WHERE (ROWID, 1) IN (SELECT ROWID, MOD (ROWNUM, 3) FROM emp);

--------------------------------------------------------------------

Query to print Rupees in words :

SELECT sal "Salary ", (' Rs. ' (TO_CHAR (TO_DATE (sal, 'j'), 'Jsp')) ' only.' ) "Sal in Words" FROM emp

--------------------------------------------------------------------

Query to print the calender for the year

SELECT LPAD (MONTH, 20 - (20 - LENGTH (MONTH)) / 2) MONTH, "Sun", "Mon",
"Tue", "Wed", "Thu", "Fri", "Sat"
FROM (SELECT TO_CHAR (dt, 'fmMonthfm YYYY') MONTH,
TO_CHAR (dt + 1, 'iw') week,
MAX (DECODE (TO_CHAR (dt, 'd'),
'1', LPAD (TO_CHAR (dt, 'fmdd'), 2)
)
) "Sun",
MAX (DECODE (TO_CHAR (dt, 'd'),
'2', LPAD (TO_CHAR (dt, 'fmdd'), 2)
)
) "Mon",
MAX (DECODE (TO_CHAR (dt, 'd'),
'3', LPAD (TO_CHAR (dt, 'fmdd'), 2)
)
) "Tue",
MAX (DECODE (TO_CHAR (dt, 'd'),
'4', LPAD (TO_CHAR (dt, 'fmdd'), 2)
)
) "Wed",
MAX (DECODE (TO_CHAR (dt, 'd'),
'5', LPAD (TO_CHAR (dt, 'fmdd'), 2)
)
) "Thu",
MAX (DECODE (TO_CHAR (dt, 'd'),
'6', LPAD (TO_CHAR (dt, 'fmdd'), 2)
)
) "Fri",
MAX (DECODE (TO_CHAR (dt, 'd'),
'7', LPAD (TO_CHAR (dt, 'fmdd'), 2)
)
) "Sat"
FROM (SELECT TRUNC (SYSDATE, 'y') - 1 + ROWNUM dt
FROM all_objects
WHERE ROWNUM <= ADD_MONTHS (TRUNC (SYSDATE, 'y'), 12) - TRUNC (SYSDATE, 'y')) GROUP BY TO_CHAR (dt, 'fmMonthfm YYYY'), TO_CHAR (dt + 1, 'iw'))
ORDER BY TO_DATE (MONTH, 'Month YYYY'), TO_NUMBER (week)

--------------------------------------------------------------------

Use of Order by clause for records with datatype as character

We generally cannot order the records for a column with character data type. Please use the following trick to use the order clause:

select employee_number from employees
order by lpad(employee_number,100);

Using the lpad the zeros would be appended and then sql will treat them as numbers and the employee number would be sorted.

--------------------------------------------------------------------

Printing Fibonacci series in PL/SQL


DECLARE
RESULT NUMBER := 1;
previous NUMBER := -1;
l_sum NUMBER;
n NUMBER;
l_in NUMBER := 10;
BEGIN
FOR n IN 1 .. l_in
LOOP
l_sum := RESULT + previous;
previous := RESULT;
RESULT := l_sum;
DBMS_OUTPUT.put_line (l_sum);
END LOOP;
END;

Other ways to print the Fib series is as follows:

CREATE OR REPLACE FUNCTION fib (n POSITIVE) RETURN INTEGER IS
BEGIN
IF (n = 1) OR (n = 2) THEN -- terminating condition
RETURN 1;
ELSE
RETURN fib(n - 1) + fib(n - 2); -- recursive call
END IF;
END fib;

/

-- Test Fibonacci Series:

SELECT fib(1), fib(2), fib(3), fib(4), fib(5) FROM dual;


--------------------------------------------------------------------

Demonstrate simple encoding and decoding of secret messages 

SELECT TRANSLATE(
'HELLO WORLD', -- Message to encode
'ABCDEFGHIJKLMNOPQRSTUVWXYZ ',
'1234567890!@#$%^&*()-=_+;,.') ENCODED_MESSAGE
FROM DUAL
/

SELECT TRANSLATE(
'85@@%._%*@4', -- Message to decode
'1234567890!@#$%^&*()-=_+;,.',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ ') DECODED_MESSAGE
FROM DUAL
/

Computing the Factorial of a number (n!)

CREATE OR REPLACE FUNCTION fac (n POSITIVE) RETURN INTEGER IS
BEGIN
IF n = 1 THEN -- terminating condition
RETURN 1;
ELSE
RETURN n * fac(n - 1); -- recursive call
END IF;
END fac;
/

-- Test n!

SELECT fac(1), fac(2), fac(3), fac(4), fac(5) FROM dual;

sql to print string vertically

SELECT SUBSTR ('&&String', ROWNUM, 1)
FROM all_tables
WHERE ROWNUM <= LENGTH (TRIM ('&STRING'));

Procedure to reverse a string

SQL> create or replace procedure rev(x in varchar2) as
2 c char(1);
3 i number;
4 begin
5 for i in 1..length(x) loop
6 select substr(x,length(x)-i+1,1) into c from dual;
7 dbms_output.put(c);
8 end loop;
9 dbms_output.put_line(' ');
10 end;
11 /

SQL> set serverout on
SQL> exec rev('Amar Alam')
           malA ramA

Display the PL/SQL Dependency Tree

SELECT lvl, u.object_id, u.object_type, LPAD (' ', lvl) || object_name obj
FROM (SELECT LEVEL lvl, object_id
FROM SYS.public_dependency s
START WITH s.object_id =
(SELECT object_id
FROM user_objects
WHERE object_name = UPPER ('&OBJECT_NAME')
AND object_type = UPPER ('&OBJECT_TYPE'))
CONNECT BY s.object_id = PRIOR referenced_object_id
GROUP BY LEVEL, object_id) tree,
user_objects u
WHERE tree.object_id = u.object_id
ORDER BY lvl

When prompted, enter the OBJECT_NAME of the object whose dependencies you want to identify.

The OBJECT_NAME can be a PACKAGE, PACKAGE BODY, or PROCEDURE. The OBJECT_NAME is the name of the object at the root of the tree.

SQL script to lists all the profile settings (all levels)
SELECT pot.user_profile_option_name "Profile"
, DECODE( a.profile_option_value
, '1', '1 (may be "Yes")'
, '2', '2 (may be "No")'
, a.profile_option_value) "Value"
, DECODE( a.level_id
, 10001, 'Site'
, 10002, 'Appl'
, 10003, 'Resp'
, 10004, 'User'
, '????') "Levl"
, DECODE( a.level_id
, 10002, e.application_name
, 10003, c.responsibility_name
, 10004, d.user_name
, '-') "Location"
FROM applsys.fnd_application_tl e
, applsys.fnd_user d , applsys.fnd_responsibility_tl c
, applsys.fnd_profile_option_values a , applsys.fnd_profile_options b
, applsys.fnd_profile_options_tl pot
WHERE UPPER( pot.user_profile_option_name) LIKE UPPER( '%&&v_profile%')
AND pot.profile_option_name = b.profile_option_name
AND b.application_id = a.application_id (+)
AND b.profile_option_id = a.profile_option_id (+)
AND a.level_value = c.responsibility_id (+)
AND a.level_value = d.user_id (+) AND a.level_value = e.application_id
(+)
AND( UPPER( e.application_name) LIKE UPPER( '%&&v_username%')
OR UPPER( c.responsibility_name) LIKE UPPER( '%&&v_username%')
OR UPPER( d.user_name) LIKE UPPER( '%&&v_username%'))
ORDER BY "Profile", "Levl", "Location", "Value"



Ur's
Amar Alam

Monday, 5 August 2013

FriendShip

0 comments
sql>> SELECT UPPER( 'happy friendship day to all') friends FROM DUAL;

FRIENDS
--------------------------------------
HAPPY FRIENDSHIP DAY TO ALL

THANKS
AMAR ALAM

Wednesday, 24 July 2013

Logical SQL Query

1 comments
SQL> SELECT SYS_CONNECT_BY_PATH(LEVEL,' ') "TRIANGLE SHAPE"
  2  FROM DUAL
  3  CONNECT BY LEVEL<=10
  4  ;

TRIANGLE SHAPE
------------------------------------------------------------
 1
 1 2
 1 2 3
 1 2 3 4
 1 2 3 4 5
 1 2 3 4 5 6
 1 2 3 4 5 6 7
 1 2 3 4 5 6 7 8
 1 2 3 4 5 6 7 8 9
 1 2 3 4 5 6 7 8 9 10

10 rows selected.

SQL>


Ur's
AmarAlam

Monday, 15 July 2013

Diff b/w on delete cascade and on delete set null..

0 comments
We use the ON DELETE CASCADE clause with a FOREIGN KEY constraint to specify that 
when a row in the parent table is deleted, any matching rows in the child table are also deleted.

You use the ON DELETE SET NULL clause with a FOREIGN KEY constraint to specify that
when a row in the parent table is deleted, the foreign key column for the row (or rows) in the
child table is set to null.



Ur's
AmarAlam