Monday, 25 September 2017

PSEUDO COLUMNS


PSEUDO COLUMNS

--Its not a column inside the table but it act as a column.

SYSDATE 
SYSTIMESTAMP
USER 
UID
ROWNUM
ROWID
NEXTVAL
CURRVAL

SYSDATE -- Its display the sytem date 

SQL> SELECT sysdate FROM DUAL;

SYSDATE
---------
25-SEP-17

SYSTIMESTAMP -- It display the timestamp date with time minutes seconds meridian.

SQL> SELECT systimestamp FROM DUAL;

SYSTIMESTAMP
------------------------------------------
25-SEP-17 02.34.13.201000 PM +05:30

USER -- It display the current user.

SQL> SELECT user FROM DUAL;

USER
------------------------------
HR

UID -- It display the user id.

SQL> SELECT uid FROM DUAL;

       UID
----------
        43

NEXTVAL & CURRVAL 

These are the sequence attributes 

CREATE SEQUENCE s1
START WITH 1
INCREMENT BY 1
MAXVALUE 10

Sequence Created

SQL> SELECT S2.NEXTVAL FROM DUAL;
   NEXTVAL
----------
         1
SQL> SELECT S2.NEXTVAL FROM DUAL;

   NEXTVAL
----------
         2
SQL> SELECT S2.CURRVAL FROM DUAL;
   CURRVAL
----------
         2
SQL> SELECT S2.NEXTVAL FROM DUAL;
   NEXTVAL
----------
         3

ROWNUM

-Its genertes only at run time and always starts with 1.
-Roll number never be stored in database.
-To give row numbers for the output result.

SQL> SELECT first_name, salary,rownum FROM Employees WHERE Department_id= 30;

FIRST_NAME               SALARY     ROWNUM
-------------------- ---------- ----------
Den                       11000          1
Alexander                  3100          2
Shelli                     2900          3
Sigal                      2800          4
Guy                        2600          5
Karen                      2500          6

ROWID

-It is a unique address generated by oracle when user inserts a new row in a table.
-It is permanently stored in a database. 
-Rowid is unique we can retrieve specific row using their rowid.
-Rowid cannot be modified;
-if you delete the row means the row id also deleted
-if you update the data means the row_id is the same for the row.
-rowid length is 18 charecters.

SQL> SELECT first_name, salary,rowid FROM Employees WHERE Department_id= 30;

FIRST_NAME               SALARY ROWID
-------------------- ---------- ------------------
Den                       11000 AAAEAbAAEAAAADNAAO
Alexander                  3100 AAAEAbAAEAAAADNAAP
Shelli                     2900 AAAEAbAAEAAAADNAAQ
Sigal                      2800 AAAEAbAAEAAAADNAAR
Guy                        2600 AAAEAbAAEAAAADNAAS
Karen                      2500 AAAEAbAAEAAAADNAAT

Sunday, 24 September 2017

SEQUENCE IN ORACLE


SEQUENCE :

-- Sequence automatically generates UNIQUE numbers.
-- It is shema object and sharable object.
-- It is mainly used for generating primary key column values.
-- NEXTVAL, CURRVAL are sequence attributes.

Syntax

CREATE SEQUENCE sequence_name
  MINVALUE value
  MAXVALUE value
  START WITH value
  INCREMENT BY value
  CACHE value;
  
CREATE SEQUENCE supplier_seq
  MINVALUE 1
  MAXVALUE 25
  START WITH 1
  INCREMENT BY 1
  CACHE 20;
  
--Here Minvalue 1 , maxvalue is 25 if you not mentioning the maxvalue its default take upto 999999999999999999999999999, started values as 1 and increment by 1 for every run.

--The first sequence number that it would use is 1 and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cache up to 20 values for performance.
  
CACHE is used to increase the performance of the sequence.
  
SQL> CREATE table customer(supplier_id number, supplier_name varchar2(10));

Table created.

SQL> CREATE SEQUENCE customer_1
  2  MINVALUE 1
  3  START WITH 1
  4  INCREMENT BY 1
  5  CACHE 20;

Sequence created.

NEXTVAL

SQL> INSERT into customer values(customer_1.nextval,'parthi');
SQL> INSERT into customer values(customer_1.nextval,'karthi');
SQL> INSERT into customer values(customer_1.nextval,'arthi');

SQL> select * from customer;

SUPPLIER_ID SUPPLIER_N
----------- ----------
          1 parthi
          2 karthi
          3 arthi

SQL> ALTER SEQUENCE customer_1
  2  maxvalue 6;

Sequence altered.

SQL> INSERT into customer values(customer_1.nextval,'vimal');
SQL> INSERT into customer values(customer_1.nextval,'kamal');
SQL> INSERT into customer values(customer_1.nextval,'siva');

SQL> INSERT into customer values(customer_1.nextval,'vicky');
INSERT into customer values(customer_1.nextval,'vicky')
                            *
ERROR at line 1:
ORA-08004: sequence CUSTOMER_1.NEXTVAL exceeds MAXVALUE and cannot be
instantiated

CURRVAL

SQL> SELECT customer_1.CURRVAL FROM customer;

   CURRVAL
----------
         6

SET OPERATORS


SET OPERATORS

UNION
UNION ALL
INTERSECT
MINUS

SQL> SELECT * FROM tab1;

       SNO SNAME
---------- ----------
         5 lathika
         6 karthika
         1 Parthi
         2 karthi
         3 kamal
         4 siva

6 rows selected.

SQL> SELECT * FROM tab2;

       SNO SNAME
---------- ----------
         1 siva
         2 ravi
         3 kavi
         4 santhosh
         5 santhosh
UNION 
-- Conditions 
Colomn and Data Type must same 
combine two tables and remove the duplicates 

SQL> SELECT sno FROM tab1 UNION SELECT sno FROM tab2;

       SNO
----------
         1
         2
         3
         4
         5
         6

6 rows selected.

UNION ALL 
--To include the duplicates 

SQL> SELECT sno FROM tab1 UNION ALL SELECT sno FROM tab2;

       SNO
----------
         5
         6
         1
         2
         3
         4
         1
         2
         3
         4
         5

11 rows selected.

INTERSECT

Its display common data from both table.

SQL> SELECT sno FROM tab1 INTERSECT SELECT sno FROM tab2;

       SNO
----------
         1
         2
         3
         4
         5

MINUS

To display the values in the first table not in second table.

SQL> SELECT sno FROM tab1 MINUS SELECT sno FROM tab2;

       SNO
----------
         6

Note:

-- SET OPERATORS used in more than 2 SELECT statement.
-- Top to bottom will be executed.
-- SET OPERATORS when used common data type will matched otherwise error.
-- Multiple number of columns are used in set operators condition is no of columns is matching otherwise its thrown a error.
-- order by is used in last SELECT statement. (if its used in first SELECT statement its wrong);

Friday, 22 September 2017

ANALYTICAL FUNCTION


ANALYTICAL FUNCTION 

RANK()
DENSE RANK()
ROW_NUMBER()
LEAD()
LAG()
ROLLUP()
CUBE()
FIRST()
LAST()
FIRST_VALUE()

SQL> CREATE Table t1(Id Number, Name Varchar2(10), Salary Number);

Table created.

SQL> INSERT into t1 values(1,'Parthi',24000);
SQL> INSERT into t1 values(2,'Karthi',20000);
SQL> INSERT into t1 values(3,'Arthi',20000);
SQL> INSERT into t1 values(4,'Surya',9000);
SQL> INSERT into t1 values(5,'Taj',8000);
SQL> INSERT into t1 values(6,'Priya',19000);
SQL> SELECT * FROM t1;

        ID NAME           SALARY                                                
---------- ---------- ----------                                                
         1 Parthi          24000                                                
         2 Karthi          20000                                                
         3 Arthi           20000                                                
         4 Surya            9000                                                
         5 Taj              8000                                                
         6 Priya           19000                                                

In the ANALYTICAL Function there are two keywords used.

OVER (ORDER BY COLUMN)
OVER (PARTITION BY COLUMN ORDER BY COLUMN)  

RANK() :  Equal rows are ranked the same rank.Next rank will be empty.    
 
SQL> SELECT Id, Name, Salary, RANK() over (order by salary desc) "RANK" from t1;

        ID NAME           SALARY RANK               
---------- ---------- ---------- ------------                  
         1 Parthi          24000        1                  
         2 Karthi          20000        2                  
         3 Arthi           20000        2                  
         6 Priya           19000        4                  
         4 Surya            9000        5                  
         5 Taj              8000        6                  

6 rows selected.

N th MAXIMUM Salary using RANK()

SELECT First_Name,Salary FROM 
( SELECT First_Name,Salary, RANK() OVER (ORDER BY Salary DESC) "RANK" from Employees ) where RANK = 5;

N th MAXIMUM Salary department wise by using RANK() 

SELECT First_Name,department_id,Salary FROM 
( SELECT First_Name,Salary,department_id, RANK() OVER (partition by department_id ORDER BY Salary DESC) "RANK" from Employees ) where RANK = 2;

DENSE_RANK() : Equal rows are ranked the same rank.Next rank will be named as the next position

SQL> SELECT Id, Name, Salary,DENSE_RANK() over (order by salary desc) from t1;

        ID NAME           SALARY DENSE_RANK()OVER(ORDERBYSALARYDESC)            
---------- ---------- ---------- -----------------------------------            
         1 Parthi          24000                                   1            
         2 Karthi          20000                                   2            
         3 Arthi           20000                                   2            
         6 Priya           19000                                   3            
         4 Surya            9000                                   4            
         5 Taj              8000                                   5            

6 rows selected.

Nth MAXIMUM Salary by Using DENSE_RANK 

SELECT First_Name,Salary FROM 
( SELECT First_Name,Salary,DENSE_RANK() OVER (ORDER BY Salary DESC) "RANK" from Employees ) where RANK = 5;

N th MAXIMUM Salary department wise by using RANK() 

SELECT First_Name,department_id,Salary FROM 
( SELECT First_Name,Salary,department_id, DENSE_RANK() OVER (partition by department_id ORDER BY Salary DESC) "RANK" from Employees ) where RANK = 2;


ROWNUM 

SQL> SELECT Id, Name, Salary,ROW_NUMBER() over (order by salary desc) from t1;

        ID NAME           SALARY ROW_NUMBER()OVER(ORDERBYSALARYDESC)            
---------- ---------- ---------- -----------------------------------            
         1 Parthi          24000                                   1            
         2 Karthi          20000                                   2            
         3 Arthi           20000                                   3            
         6 Priya           19000                                   4            
         4 Surya            9000                                   5            
         5 Taj              8000                                   6            

6 rows selected.

N th MAXIMUM Salary By Using ROWNUM

SELECT * FROM
(
SELECT Rownum rn, Salary FROM
(
SELECT DISTINCT Salary FROM Employees Order By Salary DESC)
)
WHERE rn=&n;

SELECT MIN(Salary) FROM 
(SELECT ROWNUM Rn, Salary FROM
(
SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC)
)
WHERE ROWNUM<=5; 

SELECT First_name, department_id, salary from 
(
 SELECT First_name, department_id, salary, row_number() OVER (ORDER BY salary DESC) as row_num from Employees e 
 )
 where row_num = 2;


N th MAXIMUM Salary of department wise By Using ROWNUM 

SELECT First_name, department_id, salary from 
(
 SELECT First_name, department_id, salary, row_number() OVER (PARTITION BY department_id ORDER BY salary DESC) as row_num from Employees e 
 )
 where row_num = 2;


LEAD 

SQL> SELECT Id, Name, Salary,LEAD(Salary,1,0) over (order by salary desc) from t1;

SQL> SELECT Id, Name, Salary,LEAD(Salary,2,100) over (order by salary desc) from t1;

LAG 

SQL> SELECT Id, Name, Salary,LAG(Salary,2,100) over (order by salary desc) from t1;

6 rows selected.

SQL> SELECT Id, Name, Salary,LAG(Salary,1,0) over (order by salary desc) from t1;
6 rows selected.

FIRST_VALUE

SELECT employee_id, department_id, hire_date , FIRST_VALUE(hire_date)
OVER (PARTITION BY department_id ORDER BY hire_date) DAY_GAP, hire_date- (FIRST_VALUE(hire_date)
OVER ( partition by department_id ORDER BY hire_date)"Day Count"
FROM employees
WHERE department_id IN (20, 30)
ORDER BY department_id, DAY_GAP;


EMPLOYEE_ID DEPARTMENT_ID HIRE_DATE DAY_GAP    Day Count
----------- ------------- --------- --------- ----------
        201            20 17-FEB-04 17-FEB-04          0
        202            20 17-AUG-05 17-FEB-04        547
        117            30 24-JUL-05 07-DEC-02        960
        116            30 24-DEC-05 07-DEC-02       1113
        118            30 15-NOV-06 07-DEC-02       1439
        119            30 10-AUG-07 07-DEC-02       1707
        114            30 07-DEC-02 07-DEC-02          0
        115            30 18-MAY-03 07-DEC-02        162

FIRST AND LAST

SELECT department_id,
       MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) "Worst",
       MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) "Best"
  FROM employees
  GROUP BY department_id
  ORDER BY department_id;
  
DEPARTMENT_ID      Worst       Best
------------- ---------- ----------
           10       4400       4400
           20       6000      13000
           30       2500      11000
           40       6500       6500
           50       2100       8200
           60       4200       9000
           70      10000      10000
           80       6100      14000
           90      17000      24000
          100       6900      12008
          110       8300      12008
                    7000       7000
  
LISTAGG() 

    DEPT_ID DNAME
---------- ----------
        10 cse
        10 ece
        20 eee
        30 mech
        10 mech
        20 it
        30 it 

SELECT Dept_Id, LISTAGG(DName,',')within group (order by dname)"List" FROM Listagg1 group by dept_id;

   DEPT_ID DNAME
---------- ----------
        10 cse,ece,mech
        20 eee,it
        30 mech,it 

ROLLUP

SQL> SELECT * FROM t3;

    DEP_ID        SID     SALARY
---------- ---------- ----------
         1          1       4000
         1          2       6000
         1          3       6000
         1          4       6500
         1          5       7500
         2          1       7500
         2          2       6500
         2          3       8500
         2          4       9500
         2          5       9000

10 rows selected.

SELECT dep_id,sid,SUM(salary) 
FROM t3 GROUP BY ROLLUP(dep_id,sid) ORDER BY dep_id,sid;

    DEP_ID        SID SUM(SALARY)
---------- ---------- -----------
         1          1        4000
         1          2        6000
         1          3        6000
         1          4        6500
         1          5        7500
         1                  30000
         2          1        7500
         2          2        6500
         2          3        8500
         2          4        9500
         2          5        9000
         2                  41000
                            71000

CUBE

SQL> Select dep_id,sid,sum(salary) from t3 group by CUBE(dep_id,sid) order by dep_id,sid;

    DEP_ID        SID SUM(SALARY)
---------- ---------- -----------
         1          1        4000
         1          2        6000
         1          3        6000
         1          4        6500
         1          5        7500
         1                  30000
         2          1        7500
         2          2        6500
         2          3        8500
         2          4        9500
         2          5        9000
         2                  41000
                    1       11500
                    2       12500
                    3       14500
                    4       16000
                    5       16500

    DEP_ID        SID SUM(SALARY)
---------- ---------- -----------
                            71000

SQL LOADER


SQL Loader :

--Its a bulk loader utility
--SQL Loader is used to loads data from flat file into a oracle table.
--High Performance Data Loads

Step 1: Input is CSV,DAT,FLAT File 
Step 2: Creation of CTL File [CTL : Control File]
Step 3: Open in a Command Prompt.
Step 4: SQLLDR username/Password
Step 5: Pathname of the CTL File.

Step 1: Report1.CSV

Step 2: load data 
        infile " FILE PATH OF THE CSV FILE "
        into table table name 
fields terminated by ',' optionally enclosed by ' " '
(Column 1, column 2...Column n) 
-- Save the file name as FILENAME.CTL extension

Step 3: Open in Command Prompt
Step 4: SQLLDR Username/Password 
Step 5: CONTROL = Path Name Of the CTL File .

Finally 

Commit point reached - logical record count Total number of record .

CREATE table load (first_name varchar2(20),Salary Number);

Table Created.

SELECT * FROM Newload;

No Rows Selected

SELECT * FROM load;

FIRST_NAME               SALARY
-------------------- ----------
Den                       11000
Alexander                  3100
Shelli                     2900
Sigal                      2800
Guy                        2600
Karen                      2500
Susan                      6500
parthi                     2000
parthi                     2000

The above file is converted into the CSV File format Named as newreport.csv

CTL File Creation Syntax

load data
infile 'C:\sql notes\Class\newreport.csv'  
into table newload
fields terminated by ',' optionally enclosed by '"'
(First_name, Salary )

The File is saved as newload.CTL extention.

Open Command Prompt

SQLLDR HR/ADMIN

CONTROL = "CONTROL FILE PATH NAME"

Select * from Newload;

10 rows selected

Bad File -- its contain information about the missing datas.
log File -- Information about the records to be inserted log on time execution time.
CSV File -- Common Separated Value file.
CTL File -- Control File.

Inserting new data into the old table via SQL LOADER makes an error.

Two Types

Conventional Path LOAD -- used in table partition
Direct Path LOAD--  Directly load the data in table

Its not a oracle utility
Performance wise SQLLOADER is more faster than external table 
External table is oracle utility.

TCL - TRANSACTION CONTROL LANGUAGE


TRANSACTION CONTROL LANGUAGE

COMMIT -- once commit means to save all pending changes permanent storage.
ROLLBACK -- To discard all pending clauses
SAVEPOINT -- It is marker 
DDL operation is auto commit.

SQL> CREATE TABLE TCL(Cid Number);

Table created.
SQL> INSERT into TCL values(1);
SQL> INSERT into TCL values(2);
SQL> INSERT into TCL values(3);
SQL> commit;

Commit complete.

SQL> INSERT into TCL values(4);
SQL> INSERT into TCL values(5);
SQL> SAVEPOINT S5;

Savepoint created.

SQL> SELECT * FROM TCL;

       CID                                                                      
----------                                                                      
         1                                                                      
         2                                                                      
         3                                                                      
         4                                                                     
         5                                                                      

SQL> ROLLBACK TO S5;

Rollback complete.

SQL> SELECT * FROM TCL;

       CID                                                                      
----------                                                                      
         1                                                                      
         2                                                                      
         3                                                                      
         4                                                                      
         5                                                                      
SQL> INSERT into TCL values(6);
SQL> INSERT into TCL values(7);
SQL> SELECT * FROM TCL;

       CID                                                                      
----------                                                                      
         1                                                                      
         2                                                                      
         3                                                                      
         4                                                                      
         5                                                                                                                                            
5 rows selected.

SQL> CREATE TABLE A1(ID Number);
Table created.

SQL> INSERT into A1 values(1);
SQL> commit;

Commit complete.

SQL> INSERT into A1 values(2);
SQL> INSERT into A1 values(3);
SQL> CREATE TABLE A2(ID Number);

Table created.

SQL> INSERT into A2 values(4);
SQL> INSERT into A2 values(5);
SQL> INSERT into A2 values(1);
SQL> INSERT into A2 values(2);

SQL> rollback;

Rollback complete.

SQL> SELECT * FROM A1;

        ID                                                                      
----------                                                                      
         1                                                                      
         2                                                                      
         3                                                                      
SQL> SELECT * FROM A2;
no rows selected

DML : DATA MANIPULATION LANGUAGE


DML : DATA MANIPULATION LANGUAGE ( DATA LEVEL OPERATIONS PERFORMED)

INSERT 
UPDATE 
DELETE 
MERGE

INSERT 

Its used to insert the values in the tables.

Syntax

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)  
VALUES (value1, value2, value3,...valueN);

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

INSERT ALL
  INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
  INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
  INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
SELECT * FROM dual;

-- if using INSERT ALL statement means its ends with DUAL; 

UPDATE 

--old records is replced by new records 

UPDATE TABLE_NAME SET COLUMN_NAME = 'NEW DATA' WHERE COLUMN_NAME = 'OLD DATA'; syntax

UPDATE course SET Cname= 'Parthi' WHERE Cname = 'Karthi'; -- 'karthi' is replaced  with 'parthi'

UPDATE course SET Cid=100,Cname='Arthi' WHERE Cname= 'karthi'; - karthi cname is replaced with arthi and cid is also change into 100

UPDATE course SET Cid=10; if without mentioning WHERE Clause it will update all the column.

DELETE

DELETE FROM table_name; -- Syntax Its DELETE all records in the table. 

-- if mentioning without where condition in DELETE statement all records will be deleted.

DELETE FROM course WHERE Cname='parthi' -- the cname contains parthi column is deleted from the table .


Sunday, 17 September 2017

DDL: DATA DEFINITION LANGUAGE

DDL Data Definition Language

CREATE 
ALTER 
   ADD
   MODIFY
   RENAME
   DROP
RENAME 
DROP
TRUNCATE 


TABLE

Database Design Document
Combination of rows and column with data or structure.

CREATE

Syntax : CREATE TABLE Table_Name( Column 1 Datatypes,Column 2 Datatypes); 

CREATE TABLE Student113
(
Sid Number,
Sname varchar(10),
SLocation varchar(10)
);

Table created

ALTER - ADD, MODIFY, RENAME, DROP

ADD

ALTER TABLE Student113 ADD Sdept_id Number(3);
ALTER TABLE Student113 ADD Dob Date;
ALTER TABLE Student113 ADD resume long;

MODIFY

ALTER TABLE STUDENT113 MODIFY Sdept_id char(2);

RENAME 

ALTER TABLE Student113 RENAME COLUMN RESUME TO FEEDBACK;

desc student111;

ALTER TABLE STUDENT113 Drop Column FEEDBACK;

TABLE ALTERED

RENAME : RENAME the table name into an another name here the name is student113 now rename student113 nme into student234

RENAME STUDENT113 TO STUDENT234;

Statement processed

DESC student234;

Drop : Drop command is used to delete the structure and data.

Drop table Student111;

Table Dropped 

Desc Student111;

Object to be described could not be found.-- because the structure and table is dropped.

TRUNCATE: Its used to delete the data only 

TRUNCATE table student234;

Table Truncated

The data only truncated table structure is same.

To View the dropped table:

Select * from recyclebin; -- this query is used to view the dropped table list.

To Retrieve the dropped table

FLASHBACK -- Its used to retrieve the dropped table

FLASHBACK TABLE student111 TO BEFORE DROP RENAME TO student222;
    
FLASHBACK TABLE students TO BEFORE DROP; -- this is the syntax for the flashback here students is table name 

PURGE -- Its used to delete permanently in the database

Syntax : purge table t1;

The table t1 is already dropped but it stores in the recyclebin if the above syntax is used to delete the table inthe reycle bin also.


FLASHBACK TABLE t1 TO BEFORE DROP;

ORA-38305: object not in RECYCLE BIN -- now t1 objects not in the recycle bin.