Professional Documents
Culture Documents
SQL Lecture 1
What is Database?
Database: This is the data structure used to store organized information. A database is
Topically mad up of many liked tables of rows and columns.
Database: organize form of data in specific order is called database
Database: database is a shared collection of logically related data that is stored to meet
the requirements of different users of an organization.
Database is a shared collection of logically related data designed to meet the information
needs of an organization
What is DBMS?
STANDS FOR Database Management SystemA DBMS is a database program.
Or its a software system that user a standard method of cataloging, retrieving, running
queries on data
The DBMS manages incoming data organizes it and provides ways for the data to be
modified or extracted by users or other programs.
Some examples include MYSQL, postures, Microsoft Access, SQL Server,
File Maker, Oracle, DBASE, Clipper and FoxPro since there are so many database
management systems available, it is important for there to be a way for them to
communicate with each other
What is RDBMS?
Short for relational database management system and pronounced as separate letters,
A type of database management system (DBMS) that stores data in the form of related
tables. Relational Databases are powerful because they require few assumptions about
how data is related or how it will be extracted from the database as result, the same
database can be viewed in many different ways.
Finally
Introduction to
SQL Lecture 1
table of salaries and another of telephone number , the two tables could be related
to each other by sharing an ID field that contained a ID number for each
employee of the company .
A relational database management system (RDBMS) is a database management
system (DBMS) that is based on the relational model as introduced by Edgar F.
Codd.
What is SQL?
SQL (pronounced ess-que-el) stands for structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards
Institute), it is the standard language for relational database management systems.
SQL Statements are used to perform tasks such as update data on a database, or
retrieve data from a database. Some common relational database management
systems that use SQL are: Oracle, Sybase, Microsoft Access, SQL server, ingress, etc.
Al though most database systems use SQL, most of them also has their own
additional proprietary extensions that are usually only used on their system. However,
that standard SQL commands such as Select, Update, delete, Create and
Drop can be used to accomplish almost everything that one needs to do with a
database.
Introduction to
SQL Lecture 1
Introduction to
SQL Lecture 2
Introduction to
SQL Lecture 2
Introduction to
SQL Lecture 2
Some extra metrials which are used in sql and pl/sql language
Operaters
Relational Operator
<,>,<=,>=,<>,=
Logical operators
AND, OR AND NOT
Arithmetic operator
+ ,-,*,/
SQL operators;
Is, is not, like, not like, between , not between , in , not in , etc from oracle 10g
Clause
Class assignemtns:
Continue during lecture---------------------
Introduction to
SQL Lecture 3
FUNCTIONS
Functions are small programs that are used to perform specific task when called
by it name . there are two types of functions
Built-In Functions.
Built in functions are red made functions which are already stored in the
database and can be called when required. Built in functions are further divide
into two categories.
Single Row functions are those functions that apply to an individual row, i.e.
its is effective on a row basis and apply to each row one by one. Single row
functions return a single result row for every row of required table or view.
These functions can appear in select list, WHERE CLAUSES, START WITH AND
CONNECT BY CLAUSES, and AND HAVING CLAUSES.
While the aggregate functions need a group of rows to be apply. The group of
rows means one ore more than one rows.
It means group functions are effective on a group.
Introduction to
SQL Lecture 3
4- Conversion Single Row Functions ( Convert From one type to other Type)
5- Misc Functions
Character
Functions
Upper
Lower
Initcap
Soundex
Substr
Instr
Replace
Translate
Concate
Rtrim
Ltrim
Trim
Length
Numeric
Functions
Round
Trunc
Ceil
Floor
Sign
Abs
Exp
Ln
Log
Mod
Remainder
Power
Sqrt
Date
Functions
Next_Day
Last_Day
Months_Between
Add_months
Conversion
Functions
Chr
To_number
To_char
To_Date
Ascii
Misc
Functions
Nvl
Nanvl
Nvl2
Decode
Length
Lpad
Rpad
Sysdate
User
Uid
Introduction to
SQL Lecture 3
Substr
Use to pick portion of string from specific string.
Syntax: substr(strin,start value, end value);
Note:= last one parameter is optional
Replace
Use to find a portion of string in the string and replace with
other string replace occur as a whole string not character by
Character
Syntax: replace (string, characters to replace, characters to replace with);
Selet ename, replace(ename,AD,AP) as ename from emp;
Select ename, replace(ename,AD, ) as ename from emp;
Translate
Use to find a portion of string in the string and replace with
Other string, replace occurs character by character
Syntax: translate(string,characters to replace,characters to replace with);
Select ename,translate(ename.AD,AP) as ename from emp;
Select ename,translate(ename,AD, ) as ename from emp;
Introduction to
SQL Lecture 3
Concat
Use to Concatenate more that two strings
Sysntax: concat(string1,string2);
Select ename,job,concat(ename,job) ename from emp;
Select ename,job,concat(concat(ename,-)-job)) as ename from emp;
Round
Use to round the fraction portion of numeric value.
Sysntax: round(numberic value, round value);
Note:= last one parameter is optional
Select round (10.456,1) from dual;
Select round (10.456,2) from dual;
Select round (10.456,0) from dual;
Select round (10.456) from dual;
Select round (10.456,-1) from dual;
Select round (10.456,-2) from dual;
Select round(15,594,-1) from dual;
Select round(12.594,-1) from dual;
Select empno,sal,sal*10.8967/100+sal as net from emp;
Some of the one type of point and some of the difrent point
So
Select empno,sal,round(sal*10.8967/100+sal,2) as net from emp;
Select empno,sal,round(sal*10.8796/100+sal,0) as net from emp;
Select round (sysdate,Month) from dual;
Select round (sysdate,year) from dual;
Trunc
Use to truncate the fraction portion of numeric value.
Syntax: trunc(numeric value, trunc value)
Note: = last one parameter is optional
Select trunc(10.456,1) from dual;
Select trunc(10.456,2) from dual;
Select trunc(10.456,0) from dual;
Select trunc(10.456) from dual;
Select trunc(10.456,-1) from dual;
Select trunc(10.456,-2) from dual;
Introduction to
SQL Lecture 3
LTrim, Rtrim,Trim
Trim the spaces characters, or remove the spaces
Syntax: Ltrim(string), Rtrim(string),Trim(string);
Select ename,ltrim(ename) from emp;
Select * from emp where ename=KING ;
Select * from emp where rtrim(ename)=KING;
Select * from emp where rtrim(ltrim(ename))=KING;
Select * from emp where trim(ename)=KING;
Length
Find the length of the string specified.
Syntax: length(string)
Select ename,length(ename) from emp;
Select ename,length(oracle) from dual;
Introduction to
SQL Lecture 3
Mod
Find the reminder
Syntax: mod(dividend,devisor);
Select mod(10,2) mod(11,2),mod(2,5) from dual;
Select * from emp where mod(sal,2)=0;
Select empno,sal,decode(mod(sal,2),0,sal+1,sal)
From emp;
Select empno,sal,decode(mod(sal,2),1,sal+1,sal) from emp;
Remainder
Find the remainder
Syntax: remainder (Dividend, devisor);
Select remainder (10, 2), remainder (11, 2), remainder (2, 5) from dual;
Abs
Convert negative value to positive.
Syntax: abs (expression);
Select 4-5, ABs (1300-1400) from dual;
Select sysdate,sysdate+60,round((sysdat+60)-sysdate) days1,
Abs(round((sysdate+60))-sysdate)) absdays from dual;
Exp
Find the power equivalent value
Syntax: exp (expression);
Select exp (100) from dual;
Ln and log
Ln find the natural logarithm and log find the logarithm
Syntax: ln(expression),log(expression,expression);
Select ln(100),log(100,2) from dual;
Power
Find the power equivalent value
Syntax: power (expression,expression);
Select power (10, 2) from dual;
Sqrt
Find the square root value
Syntax: sqrt(expression)
Select sqrt(100) from dual;
Introduction to
SQL Lecture 3
Date Function
Next_day
Find the next day fro the date specified.
Syntax: next_day(date,day);
Select next_Day(sysdate,Monday) from dual;
Last_Day
Find the last day of the month the date sepicifed.
Syntax : last_day(date);
Select last_day (sysdate) from dual;
Months_Between
Find the difference in months between to date.
Syntax : months_between(date-date);
Select months_between(sysdate,hiredate) from emp;
select months_between(sysdate,to_date(10-mar-1983)) from dual;
select months_between(sysdate,'01-jan-1982')/12 as age from dua;
select * from emp
where round(months_between(sysdate,hiredate)/12)>25;
select empno,ename,hir as montly,
round(months_between(sysdate,hiredate))*sal as grand_total from emp ;
add_months
add no of months in a date
syntax: add_months(date,no.of months);
select add_months(sysdate,2) from dual;
select add_months(hiredate,2) from dual;
select sysdate as today, last_day(add_months(sysdate,6)) as lastday from dual;
select round(months_between(sysdate,to_date(10-jul-1983))/12) yrs from dual;
Introduction to
SQL Lecture 3
select
round(months_between(sysdate,to_date('10-jul-1983'))/12) yrs,
round(round(months_between(sysdate,to_date('10-jul-1983'))/12)/12)
as months
round(round(round(months_between(sysdate,to_date('10-jul1983'))/12)/12)/12) as day
from dual;
To_number
Chracters that represent number can be converted to
number value
Syntax: to_number(character value that representing number)
Select to_number(123),2+456,2+to_number(456) from dual;
To_date
Characters the represent date can be converted to date
value
Syntax: to_date(character value that representing date);
select ('02/22/2003','MM/DD/YY') from dual;
problem it menas oracle not stesfiy about the above formts
select to_date('02/22/2003','MM/DD/YY') from dual;
select to_char(10-jan-1983,day) from dual;
it have problem
select to_char(to_date('10-jul-1983'),'day') from dual;
To_Char
Convert date or numbers to characters
Syntax: to_char(number)
Syntax : to_char(date,format)
Select 123, to_char (123) from dual;
Select sal,to_char(sal) as salary from emp;
Select ename,to_char(hiredate,dd/mm/yy) from emp;
Select to_char(hiredate,month,ddth,yy) from emp;
Select to_char(to_Date(22-feb-2005),day) from dual;
Select empno,ename,hiredate,to_char(hiredate,DDth Month, YYYY) from emp;
Select sysdate,to_char(sysdate,dd/mm/yyyy), to_char(sysdate,hh:mi:ss pm)
from dual;
Select empno,ename,hiredate, to_char(hiredate,HH:mi:ss) from emp;
Introduction to
SQL Lecture 3
Date formats
Day
Dd
Ddth
Dy
Day
D
Ddd
Month
mm
mon
Month
Rm
Year
Y
YY
YYY
YYYY
Year
Time Formats
Ss (seconds)
HH, hh12, am, pm
Select
sysdate,to_char(sysdate,ddth,month,yyyy),to_char(sysdate,hh:mi:ss,am) from
dual;
Select sysdate,sysdate+2,sysdate+2/24 from dual;
Select sysdate,to_Char(sysdate,d),to_char(sysdate,ddd),to_char(to_date(31dec-2007),ddd) from dual;
Select sysdate,to_char(sysdate,YYYY B.C) from dual;
Nvl
Substitute a value for null value.
Syntax: nvl(nul_value,alternate_value)
Select empno,sal,sal+comm. As net from emp;
Select empno,sal,sal+nvl(comm,0) as net from emp;
Select empno,sal,comm.,nvl(comm,0) as comm from emp;
Select empno,sal,comm.,nvl(to_char(comm.),-) as omm from emp;
Nvl2
Allow different action based on where value is null.
Syntax: to_date(character value that representind date)
Select empno,eame,hiredate,nvl2(hiredate,Hired,Not Yet Hired) from emp;
select ename,job,hiredate,comm,nvl2(comm,'yes','no') from emp;
Introduction to
SQL Lecture 3
10
Decode
Determine action based upon value in a list
Syntax: decode (condition, action, condition, action, else action)
Syntax: decode (value, if1, then1, if2, then2, if3 else)
Select empno,ename,sal,deptno,decode(deptno,10,sal*10/100,20,sal*20/100) as
increment_employee from emp;
Select
empno,ename,sal,job,decode(upper(job),MANAGER,sal*12/100,ANALYST,
sal*10/100,sal*5/100) as increment_emp from emp;
Lpad and Rpad
Used to pad or file a character string to a fixed width
Syntax: Lpad(string, length ,padding value)
Rpad(string ,elength, padding value)
Select empno,ename,lpad(ename,30,*),rpad(ename,30,*),Lpdad(ename,30 )
from emp;
select rpad(ename,25,'-'),job from emp;
Sysdate,user and uid
Function that return signle value and need no pramentr ot
pass in
Syntax: sysdate,user,uid
Select sysdate,user,uid from dual;
Introduction to
SQL Lecture 4
Joining Tables
In relational database management system the relation are normalized and we
need to display data from multiple table. To display data from multiple tables you
need to mention the names of the entire table with column name in select
statement. E.g.
Select emp. empno, enmp. Ename, emp.deptno, dept.deptno, dept.dname
From EMP, dept;
Select empno,ename,emp.deptno,deptn.deptno,dname
From EMP, dept;
The above queries will generate a Cartesian product, because it simply joning
every row of one table with every row from another table.
We need to mentioned the proper join condition to avoid Cartesian product.
Introduction to
SQL Lecture 4
Introduction to
SQL Lecture 6
Group Functions
Functions need a group of rows to be applied. The group of rows means one ore
more than one rows.
It means group functions are effective on a group.
Following are the different group functions
Max, min, median, sum, avg, count, stddev
Select sum(sla) from emp;
Selectsum(sal),avg(sal),min(sal),max(sal),median(sal),
count(sal),count(*),count(comm)
From emp;
Select sum(sal), avg(sal) from emp
Group by deptno;
Select deptno,sum(sal),avg(sal) from emp;
Group by deptno;
Select * from emp
Having avg(sal)>2000;
Select deptno, avg(sal) from emp
Where avg(sal)>2000
Grop by deptno;
Select deptno,avg(sal) from emp
Having avg(sal)>2000
Group by deptno;
SUBQUERIES
Query with in query is called sub query. It is used to search for unknown
condition.
Select * from emp
Where deptno=(select deptno from emp where ename=BLAKE);
Select * from emp
Where deptno=(select deptno from emp);
Select * from emp
Where sal=(select max(sal) from emp);
Introduction to
SQL Lecture 6
Introduction to
SQL Lecture 7
INSERT statement
The INSERT Statemtn adds one ore more rows to a table.. it has two formats
INSERT INTO table-1[(columns list)] values (value- list);
And ,
INSERT INTO table-1[(columns list)] (query-specification)
INSERT INTO table-1 values[(values);
The first from insert a single row into table-1 and explicitly specifies the columns
values for the row. The second forms uses the result of query-specification insert
one or more rows into table-1. the result rows from the query are the rows added
to the insert table.
NOTE: the query connotes reference table-1.
Both forms have and o optional column list specification. Only the columns listed
will be assigned values. Unlisted columns are set to null, so unlisted columns
must allow nulls.
Specification rows (second forms) are assigned to the corresponding column in
column list in order. If the optional column list is missing, the default column list is
substituted. The default column list contains all columns in table-1 in the order
they were declared in
CREATE TABLE, OR CREATE VIEW.
Examples
Insert into EMP values (234,jamal,Analyst, 7782,12-jan-2007, 1200, 0, 10);
Insert into EMP values (234,jamal,Analyst, null, sysdate, 1200, null, 10);
Insert into EMP values (234,jamal,Analyst, null,sysdate, default, null, 10);
Insert into EMP values (234,jamal,Analyst, 7782,12-jan-2007, 1200, 0, 10)
Insert into EMP (empno, ename, job) values (234,ali,manager);
Insert into EMP (empno, ename, job) values (null,ali,manager);
Insert into emp select * from employee;
Insert into abc select * from abc;
Insert into emp select * from dept;
Introduction to
SQL Lecture 7
DELETE Statement
THE DELETE statement rovmes selected rows from a table. It has the follwing
general format:
DELETE from table-1[where predicate]
Introduction to
SQL Lecture 7
The optional WHERE clause has the same format as in the SELECT Statement.
See WHERE Clause. The WHERE clause chooses which table rows to delete. If
it is missing, all rows are in table-1 are removed.
The WHERE Clause predicate can contain sub queries, but each sub queries
cannot reference table-1. this prevents situations where result are dependent on
the order of processing.
Delete from emp;
Delete from emp where deptno=10;
Delete from emp where job=CLERK;
Delete from emp
Where sal= (select hisal from salgrade where grad=4);
Delete FROM EMP
WHERE SAL IN (SELECT SAL FROM EMP WHERE JOB='ANALYST');
Delete from emp where sal>(select max(sal)
From emp where sal<(select max(sal) from emp
where sal<(select max(sal) from emp)));
Introduction to
SQL Lecture 9
Create Table
CREATE TABLE will create a new, initially empty table in the current database.
The table will be owned by the user issuing the command.
If as scheam name is given( for example, CREATE TABLE myschema.mytable
)
Then the table is crate in the specified schema. Otherwise it is created in the
current schema.
Temporary tables exist in a special schema, so a schema name may not be
given when creating a temporary table. The name of the table must be distinct
from the name of any other table, sequence, index, or view in the same schema.
CREATE TABLE also automatically creates a data type that represents the
composite type corresponding to one row of the table. Therefore, tables cannot
have the same name as nay existing data type in the same schema.
The optional constraint clauses specify constraints (texts) that new of updated
rows must satisfy fro an insert or update operation to succeed. A constraint is an
SQL object that helps define the set of valid values in the table in various ways.
Examples
Create table department
(
Deptno number (2),
Introduction to
SQL Lecture 9
Introduction to
SQL Lecture 9
Add
varchar2 (10),
Constraint abc_uq unique (city, date1)
);
The key of this table is the combination of city and date1.
The primary key
The primary key is a key which uniquely identity the single row of a table
The primary key is a kay which has the following characteristic
Foreign key
Unique
Not null
Index
Relation ship facilities
Introduction to
SQL Lecture 9
);
Create table employee
(
Empno number(4) constraint empno_pk primary key,
Ename varchar2(10) constraint nn_name not null,
Job varchar2(10).
Mgr number(4) constraint mgr_sk references employee(empno),
Hiredate date,
Salary number(7,2) constraint salary_chk check(salary between 0 and 15000),
Comm Number(4),
Deptno number(5) constraint deptno_fk references department(deptno)
);
Table Level constraints
Defining constraints at table level in the following examples
Create table deparemnt
(
Deptno number(4),
Dname varchar2(10) constraint nn_dname not null,
Location varchar2(10),
Constraint deptno_pk primary key(deptno)
);
Introduction to
SQL Lecture 9
Add(
Addresss varchar2(20)
);
Alter table employee
Add(
Address varchar2(20),
Phone varchar2(0)
);
alter table employee
add(
address varchar2(20) constraint add_nn not null
);
Alter table employee
Add constraint job_nn not null (job);
Alter table employee
Add constraint empno_pk primary key (deptno)
alter table student_information add
CONSTRAINT fk_province_id FOREIGN KEY(province_id) REFERENCES
province(province_id)
/
/
Renaming Column
Introduction to
SQL Lecture 9
Introduction to
SQL Lecture 9
Views
View is a logical table based on one or more tables or views.
A view contains no data itself. The tables upon which a view is based are called
base tables.
Purpose of view
1- For security purpose
2- To ease the complex queries.
Types of View
1- Simple View (From single Table DML allowed)
2- Complex View (having group function or joins, DML not allowed)
Altering View
No alter command for view, but drop and recreate the view or use create or
replace command.
Examples
Create or replace view view1 as select * from emp;
Create or replace view view1 as select empno,ename,job from emp;
Create or replace view view1 (empno, name, Category) as select empno, ename,
job from EMP;
Create or replace view view1 as select * from emp where deptno=10;
Create or replace view view3 as select * from emp where deptno=10 with check
option;
Create or replace view view4 as select * from emp where deptno=10 with read
only;
Create or replace view view1 as select deptno,sum(sal) total from emp group by
deptno;
Create or replace view view1 as select emp.* dname,loc,grade from emp, dept,
salgrade
Where emp.deptno=dept.deptno
And sale between losal and hisal;
Introduction to
SQL Lecture 9
Indexes
Indexes help us retrieve data from tables quicker. And index is a schema object that
contains any entry fro each value that appears in the indexed columns(s) of the table or
cluster and provides direct, fast access to rows.
Oracle database support several type of index.
Replding an index
It means to assign the another tablepsace and also specifiy the size for using .
alter index abc_index
rebuild
storage (initial 8m next 4m pctincrease 0)
tablespace users
/
Introduction to
SQL Lecture 9
Partitioned a table
You can divide the rows of a single table into multiple parts. Dividing a tales data
in the manner is called partitioning the table, the table that is partitioned is called
partitioned table, and the parts are called partitioned