You are on page 1of 8

Data

Database
RDBMS
SQL

PK, Candidate Key, alternateKey, composite PK, Surrogate Key,


Referential Integrety, Parent-child relation, FK

SQL Detals
DDL, DML, DRL, DCL, TCL

DataTypes
Number(Precision,scale), char, varchar, varchar2, Date.

Select
Select * from TAB
select *
Select columns
Distinct - distinct of columns, distinct of *

Where
ORDER BY
IN
wild char % and _
Like

Create Table

DML - Data Level


Insert, Update, Delete

Insert INTO TableName Values(Value1, Value2, Value3); *********Eg-insert into


batch1
values(001,'Basavaraj','B','Rajajinagar','BE',9123456789,'basavaraj@gmail.com');
Insert INTO TableName (Column, column, cloumn) values('value1', 'value2', 'value3')
*********Eg-insert into batch1 (stuid,firstname,lastname)
values(005,'Advaith','Aniketh');

Update TableName set columnName ='Value'; It will insert value in that colum for
all rows.
Update TableName set columnName ='Value', FirstName='NewName' where StudentID='001'
fo specific row.

Delete from TableName;


Delete from TableName where columnName='Value';
Delete from Tablename where ColumnName IN('V1','V2');

COMMIT
ROLLBACK

alter table tablename add <new_column_name> <datatype> (size);


alter table tablename drop column <column_name> ;
alter table tablename modify name varchar2(50);
alter table tablename rename column <old_column_name> to <new_column_name>

Alter table batch1 ADD (salary number (5,2));

Alter Vs Update?
----------------
Alter is used to modify the table-DDL,
Update is used to update existing data in a record - DML

Drop table tablename;

Truncate Table TableName;

DROP VS TRUNCATE

===============================================================

TCL - Transaction
Commit, Rollback, Savepoint,

Commit will do permanent changes on the DML operations performed on a table(Like


Saving)
Data will be visible in table but it will not be retained if session closes without
commit.

Commit;

Rollback will undo the changes done on the table in a particular session, Rollback
cant be done after commit.

Rollback;

****************

Savepoint

Select * from ETLBATCH2

UPDATE ETLBATCH2 SET cellno =9898989898 WHERE stuid=2;


SAVEPOINT SAVE1;

UPDATE ETLBATCH2 SET cellno =8888899999 WHERE stuid=1;


SAVEPOINT SAVE2;

UPDATE ETLBATCH2 SET cellno ='' WHERE stuid is null


SAVEPOINT SAVE3;

ROLLBACK TO SAVEPOINT SAVE2;


COMMIT;
-----------------

***************

All DDL Commands comes with auto commit. only DML needs to be commited
******************

Delete Truncate
-----------------------------------------------------------------------------------
------------------
DML - Datalevel DDL - Table level
Will delete all data from table Will delete all data from table
can be rolled back cannot be rolled back
condition based deleted can be deletes complete data from date, we cant
delete specific data
performed using where clause
deletes data row by row deletes data at once
low in performance high in performance

================================================================

===============================================================
select * from emp where comm is (not) null

====================================
select empno, ename, sal/12 as Monthly_sal from EMP
select empno, ename, sal*12 from EMP
select empno, ename, sal+comm from EMP - NULL exception

=======================================

Alias
Alternate names used for columns and tables to give a meaningfull name

it is used in a query
to reduce column name or to elobeatare column
wen we combine multiple columns and arrive a column
joiin 2 or more table

column
swlect c1 as alias name from table
select c1 aliasname from table

select * from emp;

select ename, job, hiredate from emp;

select ename as "Employee name", job as work, hiredate as "date of Joining" from
emp;

select ename "Employee name", job work, hiredate "date of Joining" from emp;

select empno, ename, sal, comm, (sal+comm) from emp;


select empno, ename, sal, comm, (sal+comm) Total_sal from emp;
select a.empno, a.ename, a.sal, a.comm, (sal+comm) Total_sal from emp a;
select empno, ename, sal, comm, (sal+comm) as SAL(SAL_1);
select empno, ename, sal, comm, (sal+comm) as "TOTAL SAL" from EMP order by "TOTAL
SAL" desc;
ALIAS cannot be used in WHERE, But can be specified in ORDER BY
=========================================================================

DCL - User Access - Administrator Level Commands


Grant, Revoke

Grant will give give access to user


Grant select on table tablename to user1, user2;

Revoke will take away access from an existing user


Revoke Delete on table tablename to user1, user2;
======================================================================

CONSTRAINTS
Constrains are set of rules that we set on a column or table to restrixt the values
that are being inserted.

Uses - It maintains the data integrity(Type, Format, Values)

NULL, NOTNULL, PK, FK, Check, Default, Unique.

1. Notnull - NULL and NOTNULL -


A NOT NULL constraint prohibits a database value from being null.

Create table tablename(column1 datatypa NOTNULL, column2 datatype NOTNULL);

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
In a existing table

ALTER TABLE CUSTOMERS


MODIFY SALARY DECIMAL (18, 2) NOT NULL;

2. Unique
A unique constraint prohibits multiple rows from having the same value in the
same column or combination of columns but allows some values to be null.

Create table tablename(column1 datatypa UNIQUE, column2 datatype UNIQUE);


Alter Table tablename modify columnname datatype Unique;

NOTNULL and UNIQUE together can be applied on one column

3. PK
A primary key constraint combines a NOT NULL constraint and a unique constraint in
a single declaration.
That is, it prohibits multiple rows from having the same value in the same column
or
combination of columns and prohibits values from being null.

Create table tablename(column1 datatypa Primary Key)


Composite primary key

Create table tablename(column1 datatype, column2 datatype, column3 datatype,


Primary Key(column1, column2)

now maximum of 32 keys can be defined in a table, previouly it was 16.

4. FK
A foreign key constraint (also called a referential integrity constraint)
designates a column as the foreign key
and establishes a relationship between that foreign key and a specified primary or
unique key, called the referenced key.
Create table tablename(column1 datatypa Primary Key, Column2 dataype foreignkey
references tablex(columnx))

5. check
A check constraint requires a value in the database to comply with a specified
condition.

Create table tablename(column1 datatype, column2 datatype, column3 datatype


check(value BETWEEN a and b));

Create table ccsample(sid number(5) CHECK(sid>35), bid number(5) CHECK(bid between


0 and 100), cid number(5) check(cid<35))

ALTER TABLE etlbatch2 ADD CONSTRAINT cellcheck CHECK (length(CELLNO)=10); - To


limit length in cell
SQL QUERY to validate: Select cellno from etlbatch2 where LENGTH(CELLNO) <>10
ALTER TABLE etlbatch2 ADD CONSTRAINT positchk CHECK (CELLNO>=0);

6. ALTER TABLE TABLENAME ADD <COLUMNNAME> <DATATYPE (LENGTH)> DEFAULT 'VALUE'


ALTER TABLE TEKEMP ADD COMM NUMBER(5,3) DEFAULT '00'

select constraint_name, constraint_type


from user_constraints
where table_name IN ('TABLE1', 'TABLE2');

ON DELETE CASCADE
CREATE TABLE dept_20
(employee_id NUMBER(4) PRIMARY KEY,
last_name VARCHAR2(10),
job_id VARCHAR2(9),
manager_id NUMBER(4) CONSTRAINT fk_mgr
REFERENCES emp(empno) ON DELETE SET NULL,
hire_date DATE,
salary NUMBER(7,2),
commission_pct NUMBER(7,2),
department_id NUMBER(2) CONSTRAINT fk_deptno
REFERENCES dept(deptno)
ON DELETE CASCADE );

In the first ON DELETE clause,


if manager number 2332 is deleted from the employees table, then Oracle sets to
null the value of manager_id for all employees
in the dept_20 table who previously had manager 2332.

In the second ON DELETE clause,


Oracle cascades any deletion of a department_id value in the departments table to
the department_id values of its dependent rows of the dept_20 table.
For example, if Department 20 is deleted from the departments table, then Oracle
deletes all of the employees in Department 20 from the dept_20 table.

Droping
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;
ALTER TABLE EMPLOYEES DROP PRIMARY KEY;
=======================================

CREATE TABLE PAT


(PID NUMBER(5),
FNAME varchar2(25),
LNAME varchar2(25),
DOB DATE,
LOC varchar(30),
PHONE NUMBER(10),
EMAIL varchar(25))

CREATE TABLE DOC


(DID NUMBER(5),
FNAME varchar2(25),
LNAME varchar2(25),
SPECIALITY varchar(25),
LOC varchar(30),
PHONE NUMBER(10),
EMAIL varchar(25))

CREATE TABLE CONSULT


(CID NUMBER(5),
PID number(5),
DID number(5),
Complain varchar(30),
Proc varchar(30),
Charge number(10,3))

select constraint_name, constraint_type, search_condition


from user_constraints
where table_name IN ('PAT', 'DOC', 'CONSULT');

select constraint_name, constraint_type, search_condition


from user_constraints
where table_name IN ('CON1');
ALTER TABLE CON1 DROP PRIMARY KEY;
=========================

AGREGATE FUNCTIONS

count
select count(*) from tekemp;

select min(ename) from emp;

select count(distinct ename) from tekemp;

MIN
select min(sal) from emp;
select min(ename) from emp;
select min(sal+comm) from emp;
select min(sal+comm) as Least_salary from emp;

MAX
select max(sal) from emp;
select max(ename) from emp;
select max(sal+comm) from emp;
select max(sal+comm) Least_salary from emp;

SUM
select sum(sal) from emp;
select sum(ename) from emp;
select sum(sal+comm) from emp;
select sum(sal+comm) totalpaid from emp;

AVG
select AVG(sal) from emp;
select AVG(ename) from emp;
select AVG(sal+comm) from emp;
select AVG(sal+comm) totalpaid from emp;

==================================================

Group by, Having are the extensions of aggregate functions

A GROUP BY clause, part of a SelectExpression, groups a result into subsets that


have matching values for one or more columns.
In each group, no two rows have the same value for the grouping column or columns.
NULLs are considered equivalent for grouping purposes.
GROUP BY returns a single row for each unique combination of the GROUP BY fields.

Group By is used to aggregate or group results for one or more columns


It is always used with aggregate functons

Select ColumnName1, AggFun(ColumnName) as AliasName from Tablename (Where ) group


By ColumnsName1 (Order By)

HAVING - Filters records for aggregated date, its like where but applies only on
aggregate data, where doesnot work on aggregated data
Columns in havinng clause must apper in group By or must have an aggregate
function.
Having works with aggregate function, Having must appear in group by or must have
an aggregate function.

Where is applied first then data is grouped and having is applied.

Where --> Group By --> Having

SYNTAX
Select Column1, AggFun(Column2) from Table where Column1=Value
Group By Column1
Havig AggFun(Column2) Value
Order By

======================================================================JOINS

Retriving data from multipple tables or combining data from multiple data

INNER JOIN - Matching data between tables based on condition (Equi Join [=is used],
nonequijoin[other than = is used like <,>,>=,etc)

equi join -
ansi sqL 1999
SELECT
TABLE1.COLUMN1, TABLE1.COLUMN2, TABLE2.COLUMN2, TABLE2.COLUMN3
FROM TABLE1 INNER JOIN TABLE2 ON TABLE1.COMMONCOLUMN=TABLE2.COMMOMCOLUMN

SELECT A.COLUMN1, A.COLUMN2, B.COLUMN2, B.COLUMN3


FROM TABLE1 A {INNER} JOIN TABLE2 B ON A.COMMONCOLUMN=B.COMMOMCOLUMN
NONEQUI JOIN
A.COLUMN1, A.COLUMN2, B.COLUMN2, B.COLUMN3
FROM TABLE1 A INNER JOIN TABLE2 B ON A.COMMONCOLUMN<>B.COMMOMCOLUMN

OUTER JOIN - RETRIVES BOTH ATCHING AND UNMATCHING DATA BASED ON CONDITION.

LEFT OUTER JOIN - MATCHING DATA FROM BOTH TABLES AND UNMATCHED DATA FROM LEFT TABLE
SELECT A.COLUMN1, A.COLUMN2, B.COLUMN2, B.COLUMN3
FROM TABLE1 A LEFT {OUTER} JOIN TABLE2 B ON A.COMMONCOLUMN=B.COMMOMCOLUMN

RIGHT OUTER JOIN - MATCHING DATA FROM BOTH TABLES AND UNMATCHED DATA FROM RIGHT
TABLE
SELECT A.COLUMN1, A.COLUMN2, B.COLUMN2, B.COLUMN3
FROM TABLE1 A RIGHT {OUTER} JOIN TABLE2 B ON A.COMMONCOLUMN=B.COMMOMCOLUMN

FULL OUTER JOIN - MATCHING AND UNMATCHING FROM BOTH TABLES


SELECT A.COLUMN1, A.COLUMN2, B.COLUMN2, B.COLUMN3
FROM TABLE1 A FULL {OUTER} JOIN TABLE2 B ON A.COMMONCOLUMN=B.COMMOMCOLUMN

******************
JOINING MORE THAN 2 TABLES
IF JOINING N TANBLES THEN (N-1) JOINS REQUIRED

SELECT
A.COLUMN1, A.COLUMN2, B.COLUMN1, C.COLUMN1
FROM TABLE1 A JOIN TABLE2 B ON A.COMMONCOLUMN=B.COMMONCOLUMN
JOIN TABLE3 C ON A.COMMONCOLUMN=C.COMMONCOLUMN
*************************

SELFJOIN

SELECT a.column_name, b.column_name...


FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;

SELECT e1.empno, e1.ename, e1.job, e2.ename as Manager


FROM emp e1, emp e2
WHERE e1.mgr = e2.empno;

**********************************

CARTESIAN JOIN

SELECT e.empno, e.ename, e.deptno, d.dname


FROM emp e, dept d

SELECT *
FROM emp e, dept d

****************************

You might also like