SQL
SQL
SQL Statements
Types of Constraints:
1. Primary Key Constraints - Unique and Not Null – column and table level declaration
acc_no Number(5) CONSTRAINT acc_no_pk PRIMARY KEY
2. Foreign Key Constraints – referential integrity constraint, it allows NULL values in child table
We cannot delete parent table column data which is referenced as foreign key in child table
Primary key and foreign key can exist in same table also
project_id NUMBER(5) CONSTRAINT emp_projid_fk REFERENCES PROJECT(project_id)
3. Unique Constraints – makes column data unique but NULL can be inserted - column level
declaration
acc_no Number(5) CONSTRAINT acc_no_unique UNIQUE
4. Check Constraints – gives restriction to what value can go into particular column – column level
declaration
EmpSalary Number(10,2) CONSTRAINT emp_sal_chk CHECK (EmpSalary > 0 AND EmpSalary <
10000)
5. Not Null Constraints – doesn’t allow NULL values - column level declaration and cannot be done
at table level
acc_no Number(5) CONSTRAINT acc_no_notnull NOT NULL
6. Composite Primary Key – two or more columns are considered as Primary Key – table level
declaration
CONSTRAINT cust_idacc_no_pk PRIMARY KEY (CUST_ID, ACC_NO)
ALTER TABLE tablename MODIFY (colum1 NUMBER(5) NOT NULL, acc_no NUMBER(10) PRIMARY KEY);
ALTER TABLE tablename ADD CONSTRAINT pk1 PRIMARY KEY (cust_id, acc_no);
ALTER TABLE tablename ADD CONSTRAINT ck1 CHECK (Acc_type IN (‘Savings’, ‘Current’, ‘pf’));
DataTypes:
1. NUMBER
NUMBER(p,s)
p – precision - total number of digits before and after decimal point
s – scale - total number of digits after decimal point
to store 12345.67 – NUMBER(7, 2)
2. INTEGER
To store whole numbers positive or negative
3. CHAR - Character
stores fixed-length character strings
CHAR(x) can hold characters up to x bytes
Even when less than x bytes is used, declaration would still occupy a fixed size of x bytes
Can be used when size of column is fixed, like Gender (M or F) – CHAR(1)
4. VARCHAR2
No difference between VARCHAR and VARCHAR2. VARCHAR is older version. If we
declare something in VARCHAR it will be automatically taken as VARCHAR2
Varrying character or VARCHAR is a variable length character datatype
VARCHAR2(x) can accommodate maximum of x characters or x bytes of data
However, for character data less than x bytes, only that much space will be used
5. DATE
For input and output of dates, standard oracle date format is ‘DD-MON-YY’
It won’t take any size with its declaration
It occupies a fixed length, 7 bytes of memory and stores information about century,
year, month, day, hour, minute and second
Aggregate Functions:
Date Functions:
CASE Statements:
Compares the expression in CASE statement against values given in WHEN to determine the result
CASE expression
WHEN value1 THEN Result1
WHEN value2 THEN Result2
ELSE Result3
END
Scenario 1: Senior management of a company want to give salary increase to its employees depending
on their designation
CASE designation
CASE designation
END;
Scenario 2: Need to create a report showing salary band of employees. The salary band depends on the
current salary level of the employee
Different conditions in WHEN expression is checked in a sequential manner till one is met. If non of them
meet, it will give the result in “ELSE” expression
CASE
WHEN Boolean Expression THEN Result1
WHEN Boolean Expression THEN Result2
ELSE Result3
END
CASE
1. NVL function – evaluates the first argument and return the same if it is NOT NULL else it returns
second argument
NVL(expr1, expr2)
Select nvl(comm,0) from emp;
Select NVL(To_CHAR(comm), ‘Commission not available’) from emp;
2. NVL2 function - evaluates the first argument and return the second argument if it is NOT NULL
else it returns third argument
NVL2(expr1, expr2, expr3)
Joins:
1. Left Outer Join – includes all records from the left table and matching records from right table
SELECT ……. FROM table1 LEFT OUTER JOIN table2 ON condition
2. Right Outer Join – includes all records from the right table and matching records from left table
SELECT ……. FROM table1 RIGHT OUTER JOIN table2 ON condition
3. Full Outer Join – includes all matching records from the left and right tables and then extra
records from both left and right tables
E.g. Match all customers and suppliers by country
This returns suppliers that have no customers in their country,
and customers that have no suppliers in their country,
and customers and suppliers that are from the same country.
SELECT ……. FROM table1 FULL OUTER JOIN table2 ON condition
4. Inner Join – includes only matching records from left and right tables
SELECT ……. FROM table1 INNER JOIN table2 ON condition
Independent SubQueries:
Select col1 from table1 where col2 in (select col2 from table2 where col2 = ‘ABC’)
Scenario: To list the cust_id and loan_no for all customers who have taken a loan of amount greater
than loan amount of customer id = 111
Correlated Subqueries:
Scenario: To list all customers who have a fixed deposit amount less than the sum of all their loans
select custid, sum(fd_amount) from fd_account group by custid having sum(fd_amount) <
Is used in combination with sub query and is considered to be met, if subquery returns at least
one row
Can be used in DML statements – SELECT, INSERT, UPDATE, DELETE
Is not very efficient, since sub-query is rerun for every row in the outer query’s table
Where EXISTS (subquery);
Where NOT EXISTS (subquery);
Scenario: The inventory manager wants to analyze which item have been sold (EXISTS) and not sold
(NOT EXISTS) for some time. Then wants to check if those items can be removed from ITEMS table. The
details about the Items are in ITEMS table and the sales records are stored in LINEITEMS table
Merge Statements:
Using emp
ON (emp_testing.empno = emp.empno)
Note: cannot update the same row of the target table multiple times in same MERGE statement
…….
Scenario:Company ABC has many departments and employees are allocated to one of them. We need
to create separate table for each of the department and insert emp record for the respective
departments into them.
INSERT ALL
INSERT ALL
INSERT FIRST
Minus Query:
RANK Functions:
RANK()OVER(
PARTITION BY <expr1>[{,<expr2>...}]
ORDER BY <expr1>[ASC|DESC],[{,<expr2>...}]
)
First, the PARTITION BY clause distributes the rows in the result set into partitions by one or more
criteria.
Second, the ORDER BY clause sorts the rows in each a partition.
The RANK() function is operated on the rows of each partition and re-initialized when crossing
each partition boundary.
SELECT
first_name,
last_name,
salary,
RANK()OVER(ORDER BY salary)salary_rank
FROM
employees;
In this example, we omitted the PARTITION BY clause so the whole result set was treated as a single
partition.
The ORDER BY clause sorted the rows in the result by salary. The RANK() function then is applied to each
row in the result considering the order of employees by salary in descending order.
SELECT
first_name,
lname,
deptno,
sal,
RANK()OVER(
PARTITION BY deptno
ORDER BY sal)salary_rank
FROM
emp;
SELECT
first_name,
lname,
deptno,
sal,
DENSE_RANK()OVER(
PARTITION BY deptno
ORDER BY sal)salary_rank
FROM
emp;
ROWID & ROWNUM are pseudocolumns which are not actual columns in the table but behave like
actual columns.You can select the values from pseudocolumns like ROWID & ROWNUM.ROWID &
ROWNUM are very important pseudocolumns in oracle which is used in data retrieval.
1. ROWID is nothing but the physical memory location on which that data/row is stored.ROWID
basically returns address of row.
2. ROWID uniquely identifies row in database.
3. ROWID is combination of data object number,data block in datafile,position of row and datafile in
which row resides.
4. ROWID is 16digits hexadecimal number whose datatype is also ROWID Or UROWID
5. The fastest way to access a single row is ROWID
6. ROWID is unique identifier of the ROW.
1. ROWNUM is magical column in Oracle which assigns the sequence number to the rows retrieves in
the table.
2. To limit the values in the table you can use rownum pseudocolumn
3. ROWNUM is nothing but logical sequence number given to the rows fetched from the table.
4. ROWNUM is logical number assigned temporarily to the physical location of the row.
5. You can limit the values in the table using rownum
6. ROWNUM is also unique temporary sequence number assigned to that row.
ROWID ROWNUM
select ename, empno from emp where rownum =1 and rowid not in
In order to reach for nth record of emp table, the query first discards the top n-1 records and then
selects the top record from the remaining list.
SELECT COUNT(empno)
Select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp);
Select min(sal) from (select * from emp order by sal desc) where rownum <=5);