DataBase: --To store data -Collection of fields and tables. -A database is collection of interrelated data SQL-Structure Query language. SQL is a standard computer language for accessing and manipulating databases. What is SQL? SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against a database SQL can retrieve data from a database SQL can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc. Sql Server: It’s a client/ server environment which use T-Sql to interact with client and server. Uses T-Sql to interact with client and server. T-Sql -Transact structure query language. --SQL is a non-procedural language.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
DataBase:
-- To store data- Collection of fields and tables.- A database is collection of interrelated data
SQL- Structure Query language.
SQL is a standard computer language for accessing and manipulating databases.
What is SQL?SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against a database SQL can retrieve data from a database SQL can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn
SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc.
Sql Server:
It’s a client/ server environment which use T-Sql to interact with client and server.
Uses T-Sql to interact with client and server.
T-Sql - Transact structure query language.
-- SQL is a non-procedural language.
Versions of SQL Server:
Sql Server 6.5
SQL Server 7.0
Sql Server 2000Sql Server 2005
Features of Sql Server:
Highly ScalableReplicationInternet supportSecurityParallel server-The purpose of parallel query execution is to complete a query involving a large amount of data more quickly than possible with a single thread on computers with more than one processor.
EMP
Server
C1C2 C3
Back up and Recovery programming concepts(Yukon ) .net integration
Supporting for dataware housing |
OLTP- Online transaction processing-Online transaction processing, or OLTP, refers to a class of systems that facilitate and manage transaction-oriented applications, typically for data entry and retrieval transaction processing.OLAP Online analytical processing.--> Online Analytical Processing, or OLAP , is an approach to quickly provide answers to analytical queries that are multidimensional in nature.
Database models:
Flat file model:
Hierarchical model
Network model.
Relational model:
- Data is represented in tables. maintains integrity constraints maintains relations rules between tables
Sql Server is supporting only windows operating system.
Logins:
1) Operating system login—windows users2) Sql server login- Sql server users.
Tools of sql server:
MASTER MODEL MSDB
students employees
Systemdatabase
User database
Enterprise manager –DBA
Query Analyser-Developers
Enterprise Manager:
It is an administrative tool to create and maintain database objects.
Database objects are
1. Tables2. Fields3. Views4. Stored procedures5. Triggers6. Functions etc.
2. Query Analyser:
It is a programming tool to create and maintain database objects.
There are 6 system databases:
1)Master: Default database -All System stored procedures -All user information
procedure set of pre-compiled statements.
2)Model: Gives structure to user databases.3) Msdb: contains sql server agent information.4) Tempdb: it’s a temporary database.5) Northwind:6) pubs: Used only for practice
purpose.
Enterprise Manager:
It is an administrative tool to create and maintain database objects.
STEPS TO OPEN ENTERPRISE MANAGER:
Microsoft Sql servers|---- Sql server group | ---- local |-- Databases |___ Tables | -- Views
Start
programs
Microsoft sql server
Enterprise manager
Creating Database:
Open Enterprise manager: | -- Microsoft SQL Servers |-- Sql Server group |- local |-- Databases | Right click and select | New database | Give database name( sql_class) | click ok
Database contains
1) Data files ( contain data): contains primary files(system files and userdata) , secondary files(user data).
2) Log files( Temporary transactions) .ldf( log data file)
Primary files(.mdf) --- Main data fileSecodary files(.ndf): secondary data file.
Log files: contains temporary transactions performed on the data.When the users are performing any transactions all the transactions will be loaded in log file. After completion of transactions they are removed from the log file.
Note: 1. If a condition is based on multiple columns use logical operator ‘and’.
2.If a condition is based on single column use logical operator ‘or’3. If a condition is based on single column and range values then use logical
operator ‘and’.
Delete:Used to delete records in a table.
Syntax: Delete from <tablename>. Delete all records in a table. Delete from <tablename> where <condition>.Deletes only those records satisfying condition.
(1)Delete the employees who are working in deptno 10Delete from emp where deptno=10.
(2)Delete the employees whose salaries are null and working in deptno 20Delete from emp where salary is null and deptno=20.
(3)Delete the employees whose salaries are >=1500 and <=3000Delete from emp where salary >=1500 and salary<=3000.
(4)Delete all the records in emp tableDelete from emp.
1.Delete is used to delete the records in a table.2.Using delete all records can be deleted or records can be deleted based on condition.3.Any records deleted can be Rollback.
1.Truncate is used to delete the records in a table.2.Conditions are not allowed to delete the records.3.Records are permanently deleted and cannot be roll back.
DRL Commands-(select)
Queryit’s a request for information.For writing Queries use ‘select’Using SELECT data can be retrieved from single table or from multiple tables.Any modifications using ‘select’ will not modify the data in tables.
Syntax: 1.Select * from <tablename>.*All columns in table.
select column1,column2, ........ from <tablename> where <condition>
projection: selecting specific columns from a table is called as projection
selection: selecting specific record from a table is called as selection.
ex:
1) Write a query to display all the employees details
--- select * from emp
2) write a query to display empno,ename and salary of the employees
select empno,ename,salary from empl
3) write a query to display empno, ename, salary(annual salary of the employees)
select empno,ename,sal*12 as annualsalary from emp
empno ename salary deptno
101 Ram 1000 10102 Hari 2000 20103 Kiran 3000 10
selection
projection
4) write a query to display the increase salaries of emp’s by 1000 rupees
------- select salary*1000 from emp
5)write a query to display the employees whose working in deptno 10
---- select * from emp where deptno=10
6)write a query to display the employees whose salaries are >=2000
-- select * from emp where sal>=2000
7)write a query to display empno, ename of employees working as ‘analyst’
---- select empno,ename from emp where job=’analyst’
8)write a query to display employes whose empid is 103 and working in deptno 10
--- select * from emp where empno=103 and deptno=10
9) write a query to display employees whose working in 10,20 departments.
-- select * from emp where deptno=10 or deptno=20
special operators in ‘select’
IN: used for list of values.
q) write a query to display employees whose working in 10,20,30 departments
-- select * from emp where deptno=10 or deptno=20 or deptno=30
--- select * from emp where deptno in (10,20,30)
q) write a query to display the employees who are working as clerks, analysts
--- select * from emp where job in (‘clerks’,’analysts’)
q) not in
1) write a query to display the employees who are not working in 20,30 departments
-- select * from emp where deptno not in (20,30)
2) write a query to display employees who are working as clerks, analyst, manager and not working in deptno 10
-- select * from empwhere job in (‘clerk’,’analyst’,’manager’) and deptno<>10
-------- Between---used for range of values
write a query to display employees where salaries are between 1000 and 2000
--- select * from emp where sal between 1000 and 2000
---NOT BETWEEN:
1) Write a query to display employees who are working as clerks and working in deptno=10 and salary not between 2000 and 3000
--- select * from empwhere job=’clerk’ and sal not between 2000 and 3000 and deptno=10
2) write a query to display the employees who are joined from 18-may-1981 to 15-jun-1995
-- select * from emp where hiredate not between ’18-may-81’ and ’15-Jun-95’.
like: used to find a pattern of values
_ (underscore)--- single character
%-- set of characters
q) write a query to display employees whose name starts with character ‘R’
- select * from emp where ename like ‘R%’
q) write a query to display the employees whose name contains second letter ‘A’
--- select * from emp where ename like ‘_a%’
q) write a query to displaqy the employees whose name contains 5 characters
- select * from emp where ename like ‘____’
q) write a query to display the employees whose name continues ‘ll’
---- select * from emp where ename like ‘%ll%’
q) write a query to display the emp’s whose name contains two ‘AA’
--- select * from emp where ename like ‘%A%A%’
q) write a query to display the emp’s whose name contains character ‘A’
--- select * from emp where ename like ‘%A%’
NOT LIKE:
1. write a query to display employees whose name doesn’t contain third character ‘A’
--- select * from emp where ename not like ‘__a%’
2)write a query to display employees whose name doesnot contain the character ‘m’
---- select * from emp where ename not like ‘%m%’
3) write a query to display emp’s whose name doesnot contain fifth character ‘s’
------ select * from emp where ename not like ‘____s%’
4) write a query to display emp’s whose job starts with ‘A’ and ends with ‘T’ and names contain 4 characters and doesnot contains the character ‘A’
-- select * from emp where job not like ‘A%T’and ename like ‘____’and ename not like ‘%A%’
q) write a query to display emp’s who are working as clerks and working in deptno 10 and name contains to continues ‘ee’
--- select * from emp where deptno=10 and job=’clerk’and ename like ‘%ee’
q) write a query to display employees whose name contain atleast 2 characters and working in deptno 10,20,30 and working as analyst, manager and salary between 3000 and 10000
-- select * from emp where ename like ‘%__’and deptno in (10,20,30) and job in (‘analyst’,’manager’)and salary not between 3000 and 10000
----- IS NULL: used to display null value records.
Write a query to display the employees whose salaries are null
--- select * from emp where salary is null
----- IS NOT NULL:
q) write a query to display emp’s whose salaries are not null
-----select * from emp where salary is not null
q) write a query to display emp’s who was not working in managers and working in 20,30 departments
-- select * from emp where job=’manager’and deptno in (20,30)and salary between 5000 and 10000and ename not like ‘m%’and salary is not null
=----------------
EMP
empno ename deptno job
101 Ram 10 analyst102 Smith 20 clerk103 Allen 10 manager104 Hari 20 clerk
1) write a query to display all the deptno’s in emp table
--- select distinct deptno from emp
2) write a query to display all the jobs in emp table
---- select distinct job from emp
3) write a query to display deptno and jobs from emp table
- select distinct deptno and job from emp
Order by Clause:Used to arrage the records in sorting order.Syntax: Select * from <tablename>
[where condition]
1)Write a query to display emp’s in the order of their salaries.select * from emp order by salary
2)Write a query to display emp’s in the descending order of deptnoselect * from emp order by deptno desc
3)Write a query to display employees working in dept no 10 in the order of their job in descending order.select * from emp where deptno=10 order by desc
4)Write a query to display emp’s in the ascending order of deptno and descending order of jobs.select * from emp order by deptno asc,job desc.
5)Write a query to display emp’s who are working as managers in the descending of their deptno’s and names.select * from emp where job=’manager’ order by deptno desc,ename desc.
Group Functionsfunction: A function is a pre defined prg which is used to perform a specific task.
A function always returns a value .Functions are used for mathematical calculations.Group function: A function which process all values in single column and returns a value.
Sum- to calculate totalAvg- to calculate averageMax- to find maximum valueMin- to find minimum valueCount- counts no. of records in a table.
1)Write a query to display total salaries of employees.select sum(sal) from empselect sum(sal) as total salaries from emp
2)Write a query to display the average salaries of emp’s working in deptno 20select Avg(sal) from emp where deptno=20
Note:Group functions will eliminate null values.
3)Write a query to display the highest and lowest salaries of employees.select Max(sal),Min(sal) from empselect Max(sal) As highest salary select Min(sal) As lowest salary
4) Write a query to display the no. of records in a tableselect count(*) from emp
5) Write a query to display the no. of records under salary column.select count(salary) from salary
6) Write a query to display the no. of jobs in emp table select count(job) from empselect count(distinct job) from emp
7) Write a query to display the no. of departments who are working in clerks eliminating duplicate values.select count(distinct dept no) from emp where job=’clerk’
8) Write a query to display the top 3 records in emp table
select top 3 * from emp
9)write a query to display top 1000 records without specifying column namesselect top 1000 * from emp
10) Write a query to display the 10% of records from emp table select top 10 percent * from emp
11) Write a query to display the 50% of the employ names select top 50 percent ename from emp
Single Row FunctionsA function which process a single at a time is called as single row functions.LEN-It counts the number of characters in a given stringeg:select len(‘SQL SERVER’) op=10
1)Write a query to display the employees whose name contains only 5 characters.select * from emp where ename like ‘_____’
orselect * from emp where len(ename)=5
upper:- converts all lower case chars into uppercase characters.select upper(‘sql server’) [o/p: SQL SERVER]
lower:-converts all upper case characters into lower case charactersselect lower(‘SQL SERVER’)
left:- It displays specified no. of characters from left side.select left(‘SQL SERVER’,3)
Right- displays specified no. of characters from right side select right(‘SQL SERVER’,3)
substring- displays specified no. of characters from the specified start position.select substring(‘SQL SERVER’,4,6)‘4’ is starting position,’6’ is no. of chars from the starting position
LTRIM: Removes extra spaces on the extream left of a string.select LTRIM(‘ visix’)
RTRIM: Removes extra spaces on the right side of a string.select RTRIM(‘visix ’)
Replicate-Repeats a string specified no. of timesselect Replicate(‘SQL’,5)
ASCII: American Standard Code for Information InterchangeAccepts a character and displays ASCII value for that character.
select ASCII(‘A’)
CHAR: Accepts ASCII value and displays the characters for that value.select char(97)
Power: Calculates the power of the expression.select power(2,3)
SQRT: calculates the square root of the numberselect SQRT(625)
Square: Calculates the square of a numberselect Square(10)
Getdate(); displays system date and timeselect Getdate()
Year- displays year from the specified dateselect year(‘5/7/05’)
Month: displays month from a specified dateselect month(Getdate())
Day: displays day in a specified dateselect day(Getdate())Datepart: displays the specified part of the dateselect datepart(year,Getdate())
Weekday: displays the day no. in a weekselect datepart(weekday,Getdate())
Datename: converts the specified format into charactersselect datename(month,Getdate())select datename(month,’2/6/05’)select datename(weekday,Getdate())
(1)Write a query to display the employees who joined on Mondayselect * from emp where datename(weekday,doj) like ‘Monday’
3) write a query to display the employees who joined in the month of august.
-- select * from emp where datename(month,doj) like ‘august’
=-------------
DateAdd----- Adds the specified no. of days, months, years to the given date.
syntax: select * into <newtablename> from <oldtablename>
--------- select * into emp1 from emp
------ select empno,ename into emp2 from emp
----- select * from emp2
create a table with employees working in department no 10
---- select * into emp3 from emp where deptno=10
2) without records:
syntax:
select * into <newtablename> from <oldtablename>where <anyfalsecondition>
---- select * into emp4 from emp where 0=1
--- select * from emp4
3) Inserting values using select statementsyntax: insert into <table name><select statement> insert into emp4 .select * from emp1
GROUP BY CLAUSEThis clause used to group a set of records. syntax: select col1,col2...........group function (aggregate functions) from <table name> [where <condition>] group by column 1,column 2..........
RULES: The no of columns used with group by clause must be used with select statement.select deptno ,max (sal) from empNOTE: Group by clause will consider as a new group.2.write a query to display total salaries of emp’s in each category of job .select job ,sum (sal) from emp group by job. EMP EMP NO ENAME SAL JOB DEPT NO 101 Ram 1000 Clerk 10 102 john 2000 analyst 20 103 sam 3000 Clerk 30 104 anil 4000 manager 10 105 kiran 5000 analyst 20
3. Write a query to display total salaries of employers in each category of job of dept no. select deptno , job sum (sal) from emp group by deptno, job 10 Clerk 7000 20 Analyst 7000 30 clerk 3000 40 manager 4000 4.write a query to display the average salaries of emp’s in each dept. who are working as clerks.select deptno avg(sal) from emp where job = ‘clerk’ group by deptno
HAVING CLAUSE used to check condition on group functions. syntax :select col1,col2........................group function from<table name> where <condition> group by col1,col2.......... having <condition>
1)write a query to display total salaries of emp’s in each dept whose total salaries are >5000select deptno,sum(sal) from emp group by dept no having sum(sal) >5000
Note: Alias names or column names are not allowed with having clause.group functions are not allowed with where clause.
2)write a query to display the average salaries of employes who are working as clerks & managers in each dept. whose average salaries are <4000
select deptno,avg(sal) from emp where job in (‘clerk’,’manager’) group by deptno having avg(sal) <4000
SET OPERATORS: used to comine the result of select statements including duplicates.
1.union all2. union3.intersect4. except
1.union all: Displays all the values in the result of select statements including duplicates.
ex: select deptno from empunion allselect deptno from dept
2. union: Displays all the result of select statements eliminating duplicates.
--- select deptno from empunionselect deptno from dept
3. intersect: displays comman values in the result of select statements.
--- select deptno from empintersect select deptno from dept
4. except:
Displays values that are in result of first select statement, second statement.
-- select deptno from empexcept select deptno from dept
2005 operators
- write a query to display first three records in emp table
select top 3 * from emp
write a query to display last 10 records from a table of 2000 records.
select top 10 * from empexceptselect 1990 * from emp
Inserting values using “Union”Create table T1 (sid int,sname varchar(10))
insert into T1select 1,’Ram’Unionselect 2,’Vamsi’Unionselect 3,’Hari’
select * from T1
Note: The process of inserting multiple records is called bulk insert.
JoinsA join is a condition used to join multiple tables.joins are used to retrieve the information multiple tables.
(1)cross join: It is a Cartesian product of records2) Inner join: equi join, non-equijoin3)outer join- left outer join, right outer join, full outer join.4) self join.
1)cross join:
It is a Cartesian product of records.
Cartesian product-- m*n.emp---4 records, dept -3 records
4*3 =12
syntax:
1) select * from <table 1>,<table 2>......2) select * from <table1> cross join <table2>
emp table
dept
empno ename sal job mgrid deptno
101 hari 1000 clerk 102 10102 kiran 2000 analyst 104 20103 Ram 3000 clerk 102 null104 sam 4000 manager 105 20105 john 5000 president null 10
salgrade:
1. write a query to display the records from salgrade and dept tables.
deptno dname dloc
10 sales hyd20 accounting bng30 research pune
grade losal hisal
1 500 10002 1100 20003 2100 3000
3) write a query to display the salgrade, dept,emp tables.
101 hari 1000 10 sales102 kiran 2000 20 accounting104 sam 4000 20 accounting105 John 5000 10 sales
3) write a query to display empno, ename, salary of the employees who are working in accounting dept.
--- select e.empno, e.ename,e.sal fromemp e, dept dwheree.deptno=d.deptnoand dname=’accounting’
Use Inner join model:select e.empno,e.ename,e.sal from emp e,dept d inner join dept on e.deptno=d.deptno and dname=’Accounting’
(4)write a query to display all the details(All columns in emp table) who are working in Bangalore.select e.empno,e.ename,e.sal,e.job,e.mgrid,e.deptno from emp e inner join dept one.deptno=d.deptno and d.loc=’bng’
(5)write a query to display empno,ename,sal,job,dname whose salaries >3000 and working as ‘Manager’select e.empno,e.ename,e.sal,e.job,d.dname from emp e inner join dept one.deptno=e.deptno and e.sal>3000 and e.job=’Manager’
NON-EQUI JOIN:
It retrieves only matched records from multiple tables. Tables does not contain any common columns other than equal to (=) operator. If any special operator is used it’s called as Non-Equi join.
emp table
empno ename sal mgrid job deptno101102103104105
RamAnilVamsiJohnKiran
10002000300040005000
104101104105null
AnalystClerkAnalystManagerPresident
1020101020
dept table
deptno dname loc102030
SalesAccountingResearch
PuneHydchennai
1) write a query to display empno, ename, sal and grade of the employees.
select e.empno,e.ename,e.sal,e.grade from emp e,salgrade swhere e.sal between s.losal and s.hisal
2) write a query to display ename,job,grade of all the employees.select e.ename,e.job,s.grade from emp e,salgrade swhere e.sal between s.losal and s.hisal
3)write a query to display empno,ename,sal,deptname and grade of all the employees select e.empno,e.ename,e.sal,d.dname,s.grade from emp e,dept d,salgrade s where e.deptno=d.deptno and e.sal between s.losal and s.hisal
Note:
Retrieving data from N no.of tables requires (N-1) join conditionsCombination of equi join and non-equi join is Inner join
(4)write a query to display empno,ename,job,dname,grade of employees who are working as ‘Analyst’select e.empno,e.ename,e.job,d.dname from emp e,dept d,salgrade s where e.job=’Analyst’ and e.deptno=d.deptno and [emp-dept] e.sal between s.losal and s.hisal [emp-salgrade]
(5)write a query to display empno,ename,sal,loc of grade 3 employee.select e.empno,e.ename,e.sal,d.loc from emp e,dept d,salgrade s where s.salgrade=3 and e.deptno=d.deptno e.sal between s.losal and s.hisal
empno ename sal loc103 Vamsi 3000 Hyd
project empno prjid doj101 P1 5/6/06
102103
P2P3
3/4/077/7/06
6)write a query to display ename,salary,mgrid,dname,loc and prjid of the employees.
select e.ename,e.sal, e.mgrid,d.dname,d.loc,p.prjid from emp e,dept d, project pwhere e.deptno=d.deptno and e.empno=p.empno
7 ) write a query to display empno, ename,sal,loc of who are working as ‘Analyst’ and working under grade 1 and 2 ,and salary between 1000 and 5000 and working in project P1 and P2.
Select e.ename,e.sal,e.empno,d.loc from emp e,salgrade s dept d ,project where e.job=’Analyst’ and S.grsde in (1,2) and e .sal between 1000 and 5000 and p.prjid in (‘P1’ , ‘P2’) and e.empno=d.dept no and e.empno= p.empno and e.sal between S.Lasal and S.hisal
Outer join:
It is an extention an inner join. outer join retrieves both matched and unmatched records from multiple table.
(i) left outer join : Retreives Matched records from both table and Unmatched records from left table
syntax: select table1.col1, table1.col2, table2.col1, table2.col2 from table1 left outer join table2 on table1.col=table2.col
table1 is the left table and table2 is the right table.
1) write a query to display empno, ename , deptno ,dname and loc of all the employees with unmatched records from emp table.
---- select e.empno,e.ename,d.deptno,d.dname,d.loc from emp e leftouterjoin dept d on e.deptno=d.deptno
--- matched records from emp table.
--- Unmatched records from emp table.
2) Right outer join:
Displays matched records from both tables and unmatched records from right table.
-- identity is used only for generating numeric values. It is not applicable for characters.
create table t1(sid int identity(1,1),sname varchar(10),course varchar(10))
insert into t1 values (‘Ram’, ‘Sql’)insert into t1 values (‘john’,’sql’)
-- select * from t1
Deleting Duplicate records from table
starting value
method 1:
select distinct student.*into student1 from student (realtime not possible)
select * from student insert into student values(102,’anil’,400)
select distinct student.* into student1 from student
select * from student1
method 2: steps
1) count the number of duplicate records in table.2) copy all the distinct values into a new table3) delete duplicate records from table4) insert unique values into table.
step1: count the no. of duplicate records
--- select sid, sname, c=count(*) into s1from student group by sid, sname having count(*) >1
-- select distinct student.* into s2from student s1 wherestudent.sid =s1.sid and student.sname=s1.sname
Step3:
delete duplicate records from the actual table
--- delete student from student, s1 where student.sid=s1.sid and student.sname=s1.sname
sid sname
RamAnil
s2sid sname course
1 Ram sql2 anil oracle
step4: insert unique values into table.
insert into student select * from s2
Constraints:
Data integrity:
Reliability and accuracy of data is data integrity. To maintain data integrity constraints are used constraints are the rules to be defined on columns.
Types of constraints:
1) unique constraints:
2) Not null constraints
3) default constraints
4) check constraints
5) primary key constraints
6) foreign key constraints.
student
sid sname course
1 Ram sql2 Anil oracle3 Kiran C
1) unique constraints:
-------- Not allows duplicate values--- allows only one null value
create table emp(empno int unique,ename varchar(10),sal int,dept int)
--- insert into emp values( 101,’Ram’,5000,10)-----right-- insert into emp values(101,’hari’,5000,10)-----wrong- insert into emp values(null,’hari’,5000,20)-----right-insert into emp values(null,’john’,5000,10)----wrong
2) not null constraints:
-- allows duplicate values- not allows null values
syntax:
-- create table emp(empno int unique, ename varchar(100) not null,sal int,dept int)
--- insert into emp values(101,’Ram’,6000,20)=-----right-- insert into emp values(null,’null’,7000,10)------right-- insert into emp values(102,null,6000,30)----wrong
3 ) default constraints:
inserts the default values when user is not supplying values to columns.
create table mep(empno int unique,ename varchar(10) not null,sal int check(sal > 5000),deptno int)
--- insert into emp values(102,’kiran’,4000,10) ----------wrong--- insert into emp values(null,’John’,8000,10)---right-- insert into emp values(105,’sam’,null, 20)---right
note:
check constraint will accept null values
unique not null 7500
empno ename sal deptno
emp
--- create table employ(empno int unique, ename varchar(10) not null,sal int check (sal between 15000 and 25000),deptno int,job varchar(10) check (job in (‘clerk’,’salesman’)) not null)
4) primary key constraint****
It’s a combination of unique and not null constraints.
--primary key constraints not allows duplicate values.-- It’s not allows null values.
-- create table emp( empno int primary key,ename varchar(10) not null,sal int check(sal>15000),deptno int)
--- insert into emp values(101,’Ram’,8000,10) ------right
unique notnull 15000&25000
empno ename sal
deptno clerk or salesman not null job
employ
--- insert into emp values(null,’kiran’,6000,20) -----wrong-- insert into emp values(101,’John’,3000,10) ----- wrong
Note:
A table must contain only one primary key.
5) Foreign key constraint ****
-- It creates a relation between multiple tables
- It always depends on primary key- It accepts duplicate values-- It accepts null values-- not accepts the null values which are not in primary key
deptno dname locdept
primary key
empno ename sal deptno
primary key
emp
references
foreign key
child table or detail table
steps to create foreign key constraint
1) create a master table
create table dept( deptno int primary key,dname varchar(10) not null,loc varchar(10) not null)
2) insert values into master table
insert into dept values(10,’sales’,’hyd’)
insert into dept values(20,’accounting’,’bng’)
3) create a child table
create table emp( empno int primary key,ename varchar(10) not null,sal int check( sal> 75000),deptno int references dept(deptno))
or
deptno int foreign key ( deptno ) references dept (deptno)
4) insert into values child table
insert into emp values(101,’ram’,6000,30) -----wronginsert into emp values(102, ‘vamsi’,8000,10) -----right
create table student( sid int primary key,sname varchar(10) not null,course varchar(10) not null)
book id book name sid sname course
sid book id issuedate
child table
foreign key
foreign key
books
child table
master tablep.key
master tablelibrary
p.key
deptno dname loc
10 sales hyd20 accounting bng
dept
insert into student values(1,’Ram’,’sql’)
create table library(bookid int primary key,booknae varchar(10) not null)
create table books( sid int references student(sid),book id int references library (book id),issue date datetime)
Note: while defending foreign key constraint , the datatypes of columns must be same as master and child table. But the column name may differ.
empno ename sal deptno
101 Ram 1000 10102 Anil 2000 10
emp is master and child table.
Note: To delete the records from a master table, first delete the records from a child table and then delete the records from master table.
--- delete from dept where deptno=10 ------ wrong
ON DELETE CASCADE:
This caption is used to delete the records from master and child tables at a time.
Steps:
1) use on delete cascade with foreign key constraint.2) perform delete operation on master table.
create table emp( emp int primary key,ename varchar(10) not null, sal int check( sal>5000),deptno int foreign key (deptno)references dept(deptno) on delete cascade)
--- delete from dept where deptno=10.
prjid prjname
p.keybudget
master table
deptno dname loc
p.key
dept
master table
empno ename sal deptno
empno prjid doj
f.key
project
child table
p.key
foreign key
constraints can be declared in 2 ways:
1 ) column level: constraints defined while declaring the columns.
2)Table level: constraints defined after declaring all the columns.
column level:
create table emp
( empno int primary key,ename varchar(10) not null,sal int check (sal>5000),dept int references dept(deptno))
Table level:
create table emp( empno int primary key,ename varchar(10) not null,sal int, dept int,primary key (empno),check(sal>5000),foreign key (deptno) references dept(deptno) on delete cascade)
note:
not null and default constraints are not allowed in table.
create table emp1(empno int constraint p_key primary key,ename varchar(10) not null,sal int constraint c_cnst check(sal>5000),deptno int constraint f_key foreign key(deptno)references dept(deptno) on delete cascade)
Outer query executes first and gives theresult to inner query.
Based on outer query results, inner query executes and gives the result to outer query.
Based on inner query results outer query executes. Co-related queries are bi-directonal where as subqueries are unidirectional.
Important Queries:
1.write a query to display the first highest salary
--select sal from emp where 0=(select count(*) from emp e where emp.sal <e.sal)
Empsal Countsal count10002000300040005000
10002000300040005000
1000 - 0+1+1+1+1=42000 -33000 -2 4000 -15000 -0
2. write a query to find third highest salary.
select sal from emp where 2=(select count(*) from emp e where emp.sal <e.sal)
3.write a query to display the details of 10th highest paid employee.
select * from emp where 9=(select count(*) from emp e where emp.sal <e.sal)
4.write a query to display the first least salary.
select * from emp where 0=(select count(*) from emp e where emp.sal <e.sal).
NOTE!: To find Nth highest salary give n-1=and use the symbol ‘<’ in condition.
To find Nth lowest salary give n-1=and use the symbol ‘>’ in symbol.
5.write a query to display top 3 highest salaries.
select sal from emp where 3>(select count(*) from emp e where emp.sal <e.sal) order by sal
6.write a query to display first 10 highest salaries.
select * from emp where 10>(select count(*) from emp e where emp.sal <e.sal) order by sal
7.write a query to display top 5 lowest salaries.
select * from emp where 5>(select count(*) from emp e where emp.sal >e.sal) order by sal
NOTE2: To find top Nth highest salaries use N> and use the ‘<’ in condition.
To find top Nth lowest salaries use N> and use the ‘>’ in condition.
Views
A view is a virtual or logical table which always depends on a table.
A view holds the results of select statements.
A view doesnot occupy any space where as table occupies space.
when a table is updated automatically view gets updated.
view contains metadata ie data about data.
Types of views(1)simple views(2)complex views
(1)simple views: A view which is based on a single table is called simple view.
syntax: create view <view name>[with exception]
as<select statement>[with check option]
1.create a view for the employees in emp table.create view emp_view As select * from emp
select * from emp_view
2. create a view for empno,ename
create view v1 As select empno,ename from emp
select * from v1
NOTE:Any DML operations performed on the table (or) view will affect both.
3.create a view for the employees working in deptno 10
create view v2 As select * from emp where dept no=10
select * from v2.
NOTE: while inserting the values into a view.If supplied values are not satisfied by the view that record is not inserted in view,but inserted in table.
With Check optioncheck option doesnot allow any DML operation.
A view is not satisfied condition on both table & view.
Modifying a view
Alter view v2 As select * from emp where deptno with check option
select * from v2
1write a query to display all the details in a database.
select * from sysobjects (system table) where x type=’u’users
=’v’ views xtype----column in a sysobjects table.
2.write a query to display text of a view
sp_helptext <viewname>
sp_helptext emp_view
create view emp_view as select * from emp (will be displayed)
With Encryption of a view
Hides the text of a view
1.create a view for the employees working in deptno =10
create view v1 with encryption As select * from emp where deptno=10 with check option.
NOTE: when a table is deleted from the database on which view is dependent view becomes invalid.
when a table is created again the view becomes valid.
(2) Complex views:
A view which is based on multiple tables is a complex view.
A view which is based on group functions is a complex view.
1.create a view for maximum salaries of employees in each department.
create view v1 as select deptno(max) as maximum sal from emp groupby deptno.
Note: views are mainly used for complex select statements complex views cannot be modified.
2.create a view for total salaries, average salaries, max salaries, minimum salaries of a employees in each dept.
create view cv2 as select dept no, sum(sal) as total salary
avg(sal) as average salarymax(sal) as maximummin(sal) as minimum salaryfrom emp group by deptno
3. create a view for empno, ename, sal, job, dname, loc and grade of the employees.
create view cv3 as select e.empno,e.ename,e.sal,e.job,d.dname,d.loc,s.grade from emp e,dept d,salgrade s where e.deptno=d.deptno and e.sal between s.losal and s.hisal
Deleting views
syntax: drop view <viewname>
--- drop view cv1--- drop view cv2,cv3
Creating a view from view
1) create view v1 as select * from emp where deptno=10
2) create view v2as
select ename from v1 where ename like ‘a%’
Rules:
Rules are the conditions defined to used on multiple tables.
Types of Rules
1) Range rule-- used for range of values.
2) List rule--- used for list of values.
syntax:
create rule <rulename>as@variable <condition>|--- user defined variable.
1) create a rule for the condition that values must be >5000.
--- create rule R1 as @ values >5000
Binding the rules to columns in table.
syntax:
sp_bindrule <rulename>, ‘table.column’
---- sp_bindrule R1, ‘emp.sal’
Note:
Rules will not check the existing data.
--- Rules will check the newly inserted records.
Unbinding the rules:
syntax:
sp_unbindrule ‘table.column’
- sp_unbindrule ‘emp.salary’
1) write a query to display all the rules in a database.
--- select * from sysobject where xtype=’R’
2) write a query to display the text of a rule.
-- sp_helptext <rulename>
sp_helptext R1
3) create a rule for list of values hyd, bng, pune
- create ti;e r1as@ values in (‘hyd’,’bng’,’pune’)
-- sp_bindrule R2,’dept.loc’
Deleting the rule
syntax:
drop rule <rulename>
- drop rule r2
Defaults:
Used to define a default value.
syntax:
create default <default name>as <value>
- create default d1as ‘hyd’
- sp_binddefault df1, ‘dept.loc’
- sp_unbinddefault ‘dept.loc’
--- select * from dept.
Deleting the defaults:
syntax:
drop default <default name>
drop default df1
TCL commands(commit,rollback)
commit--- saves the previous transactionrollback---cancel the previous transaction
sql server by default performs auto commit transactions
2. Explicit transactions: These transactions must start with begin transactions and ends with commit or rollback.
syntax:
begin tran or transaction------------commit /rollback tran
To save the records permanently in a database.
-- begin tran select * from empcommit--------------
-- begin trandelete from empcommit
-----
- begin trandrop from emprollback tran
----
- begin trandrop from emp
rollback tran
----
-- begin traninsert into emp (empno,ename)values (125,’Ram’)
delete from emp where empno=117
update emp set salary =9000 where empno=103
rollback tran.
-------
save Transaction:
It is used to mark the transactions
syntax:
save tran <transaction name>
Begin Tran insert into emp(empno,ename) values(125,’Ram’)
insert
updatedelete
insert
rollback A
rollback B
rollback A
save Tran ADelete from emp where empno=117save Tran Bupdate emp set salary=9000 where emp no=103Rollback B
(3)Implicit transactions: These transactions doesnot require delete transaction by default implicit transactions is off. When a connection is operating in implicit transaction mode, the instance of the SQL Server Database Engine automatically starts a new transaction after the current transaction is committed or rolled back.
To make it on use the command. set implicit- Transactions onset implicit_transactions on
select * from emp commit delete from emp rollback tran.
Go- Used to execute multiple statements.
create Database DB1 Go use DB1 Go create table student(sid int,sname varchar(10)) Go insert into student values(1,’John’) Go insert into student values(2,’Vamsi’)
select * from student.
T-SQL Programming
SQL SERVER PART-II
T-SQL Programming is procedural language.To execute multiple steps at a time T-SQL Programming is required.
Steps(1)variable declaration(2)Initialising values(3)process or calculation(4)print the result
1.Variable Declaration:
syntax: Declare @ variable datatype,@ variable database ex: 1.Declare @ a int 2.Declare @ a int,b int
2.Initialising variables:
syntax: set @ variable =value ex: set @ a=10 set @ a=’visix’ set @ b=204.Print result:
syntax: 1.print @ variable 2.print ‘Message’
commentssingle line --------multiple lines /* === */
(1)write a program to accept a name and print it.
Declare @ A varchar(10)set @ A=’RAM’print @ A
(2)write a program to accept two integer values and print the sum of two numbers
--program for sum of two numbers
Declare @A int ,@B int ,@ c int set @ A=10set @ B=20set @ c=@ A+@ Bprint ‘sum of two numbers:’+convert(varchar,@c)
(3)write a program to print adition,multiplication,subtraction of two numbers.
Declare @A int ,@B int ,@ c int set @ A=10set @ B=5set @ c=@ A+@ Bset @ c=@ A*@ B
set @ c=@ A-@ Bset @ c=0;print ‘The sum of two numbers:’+convert(varchar,@c)print ‘The multiplication of two numbers:’+convert(varchar,@c)print ‘The subtraction of two numbers:’+convert(varchar,@c)
(4)write a program to accept sid,sname,marks of sub1,marks of sub2,calculate total and print all the details of student.
Declare @ A int,@ B varchar(10) @ M1 int,@ M2 int,@ t int set @ A=1 set @ B=’RAM’ set @ M1=10 set @ M2=20 set @ T=@ M1+@M2print ‘Name of the student:’+convert(varchar,@ B)print ‘Studentid:’+convert(varchar,@ A)print ‘The sum of marks:’@ T
(5)write a program to accept ur date of birth and print the day of dob
***************************************YOU WAS BORN ON TUESDAY
Declare @ N Datetimeset @ N=’5/6/92’print ‘********************************’print ‘YOU WAS BORN ON’Datetime(weekday,@ N)print ‘********************************’
(6)write a program for swapping two integer values
Declare @A int ,@B int ,@ Temp int set @ A=10set @ B=20print ‘Before swaping’print convert(varchar,@A)+space(4)+convert(varchar,@B)print ‘After swaping’set @ Temp=@ Aset @ A=@ Bset @ B=@ Tempprint ‘convert(varchar,@ A)+space(4)+convert(varchar,@ B)
Note: ‘+’ is concatenation operator,if ‘+’ is used between two int values it is trated as addition.
For concatenation values always convert integer values to varchar datatypes.
Conditional statements
syntax:if <condition>
{ begin _____ _____ } end else { begin ____ ____ end }(1)write a program to print greatest value among two numbers
Declare @ A int,@ B intset @ A=900set @ B=178if(@ A>@ B)beginprint ‘A is greater’endelsebeginprint ‘B is greater’end
(2)write a program to print the greatest value among three numbers.
Declare @ A int,@ B int,@ C intset @ A=900set @ B=178set @ C=80if @ A>@ B and @ A>@ Cprint ‘A is greater’else if @ B >@ cprint ‘B is greater’else
print ‘C is greater’
(3)write a program to print whether a given number is even number or odd number
Declare @ N int set @ N=80if @ N % 2=0print convert(varchar,@N)+’is Even’elseprint convert(varchar,@ N)+’is odd’
Iterative statement
syntax: while <condition> begin ____ ____ end
(!) write a program to print the numbers 1 to 10
Declare @ i int set @ i=1 while @ i<=10beginprint @ iset @ i=@ i+1 end
(2)write a program to print the sum of 10 numbers
Declare @ i int,@ sum set @ i=1set @ sum=0while @ i=10beginset @ sum=@ sum+@ iset @ i=@ i+1end print @ sum
Assigning column values to variablesSyntax: select var1=col1,var2=col2,- - - - from <tablename> where <condition>
(!)write a program to display empno,ename and salary of the employee for the given empno.
Declare @ A int,@ B varchar(10),@ C int select @ A=empno, @ B=ename, @ C=salary from emp where empno=102 print ‘ ------------------------------‘ print @ A print @ B print @ C print ‘-----------------------------‘
(2)write a program to display the number of records in a table.
Declare @ N int select @ N = count(*) from empif @ N>0print ‘Total records in table: ‘+convert(varchar,@ N)elseprint ‘No records in table’
T-SQL Programs
Unnamed NamedT-SQL Programs T-SQL programs
*Difference between Unnamed and Named T-SQL Programs
UN NAMED T-SQL NAMED T-SQL1.Un named T-SQL programs will temporary executes and display.2.These programs doesnot have any name.3.These programs starts with declare
1.Named T-SQL programs will permanently stored in database and display the results.2.Name is must for this programs.3.These programs starts with create.
DeclareCreate
Named T-SQL Programs(A)PROCEDURES:
A procedure is a set of pre-complied statements.
A procedure compiles only once but executes multiple times to reduce burden on server procedures will create.
client request server
1000 records
(1)Parse(2)Compile Data cache- Data(3)Optimization Procedure cache- Execution plan(4)Execute
Types of Procedures
(1)System stored procedures(2)Extended stored procedures(3)User defined procedures
1.System stored procedures: These procedures will be stored in Master DataBase.
These procedures will have a prefix sp.
ex: sp_help sp_tables sp_rename
select /*/ from emp
2.Extended stored procedures:
These procedures are also stored in Master Database.
These procedures have a prefix.
ex: xp_send mail- To send mails xp_cmd shell- To access Ms-Dos commandsThese extended stored procedures will work only in Master database.
1) clustered index : when clustered indexes created on table the records will be arranged in ascending order and the information is represented in the form of B-Tree structure. The information is obtained at leaf node.
B-Tree Structure
The default index created when a primary key defined on a column is clustered index.
Creating a clustered index
create clustered index index1 on emp(empno).
sp_help index emp.
Note: A table must contain only one clustered index.
(2)Non-clustered index: In non-clustered index the information is not arranged in sorting order.
2 3 2878+98474
4 - A5 - B
6 - C7 - D
A B C D
Intermediate level
leaflevel
Root level
A table may contain more than one non-clustered index.
ex:
create non-clustered index index2 on emp(ename).create nonclustered index index3 on emp(salary).
Note: Creating more number of indexes will degrade the performances of select statements.
1.Display indexes on a table.sp_help index emp.
Dropping indexes on table
Syntax: Drop index tablename.indexname
Drop index emp.index1Drop index emp.index1,emp.index2
(3)Unique index: Unique index works as unique constraint.
A table may contain more than one unique index.create unique index index4 on emp(empno).Unique index is defined on those columns which contains unique values.
Note: Unique index will not allow one null value also.
(4)Composite index: An index defined on multiple columns ia composite index.
create composite index index6 on emp(empno,ename).
Steps for getting execution plan
Types of scan
(1)Table scan
(2)Index scan
Table scan perform <=10000
Index scan perform >10000
Cursors
A cursor is temporary buffer which holds the result of select statement for navigation of records.
Cursors are used to retrieve the records randomly.
Steps for declaring cursor
(1)Cursor declaration(2)open cursor(3)Fetch records from cursor.(4)close cursor(5)Deallocate cursor
1.Go to query menu.
2.Show execution plan.
3.Select statement
4.In result window,click on the execution plan.
(1)Cursor Declaration
syntax: Declare <cursor name> <cursor type> for <select statement>
(2)Open Cursor
syntax: open <cursor name>
(3)Fetch records from cursor
syntax: fetch <keywords> from <cursor name>
(4)Close Cursor
syntax: close <cursor name>
(5)Deallocate Cursor
syntax: Deallocate <cursor name>
Types of cursors
(1)Forward only cursors
(2)Static cursors
(3)Dynamic cursors(update cursors)
(4)Keyset cursors
1. Forword only cursors:
--- Declare a cursor for the records in emp table.
declare emp_cur cursor for select * from emp
open emp_curfetch next from emp_curclose emp_curdeallocate emp_cur
Note: Forward only cursor,support only next keyword.
Relative N Displays Nth record from current position and from top.
Relative -N Displays Nth record from current positon and from buttom.
Declare emp_cur cursor static for select * from emp open emp_cur
Fetch first from emp_cur
Fetch last from emp_cur
Fetch prior from emp_cur
Fetch next from emp_cur
101 RAM 1000
102
103
104
105
106
107
Fetch Absolute 3 from emp_cur
Fetch Absolute -4 from emp_cur
Fetch Relative 2 from emp_cur
Fetch Relative -3 from emp_cur
close emp_cur
Deallocate emp_cur
Note: Any modifications on the table will not affect the static cursor if it is opened.
3.Dynamic cursors: Any modifications perform on a table will affect the dynamic cursor when the cursor is opened.
Dynamic cursors doesn’t supports absolute keyword for
select * from emp
open emp_cur
Fetch first from emp_cur
Fetch last from emp_cur
Fetch prior from emp_cur
Fetch next from emp_cur
Fetch Relative 2 from emp_cur
Fetch Relative -3 from emp_cur
close emp_cur
Deallocate emp_cur
4.Keyset cursors: To create a keyset cursor,the table must contain unique index.
keyset cursors behaves as both static & dynamic cursors.
sp_helpindex emp.
Declare emp_cur cursor keyset.
for select * from emp
open emp_cur
Fetch first from emp_cur
Fetch last from emp_cur
Fetch prior from emp_cur
Fetch next from emp_cur
Fetch Absolute 3 from emp_cur
Fetch Absolute -3 from emp_cur
Fetch Relative 2 from emp_cur
Fetch Relative -3 from emp_cur
close emp_cur
Deallocate emp_cur
update emp set salary=102 where empno=102(dynamic cursors)
Note: when non unique index columns are modified behaves as dynamic cursors.
when unique index columns are modified behaves as static cursors and will not display the values.
Ex: Deallocate emp_cur
update emp set salary=25000 where empno=102
update emp set empno=101 where empno=102
select * from emp
********TRIGGERS********
A trigger is system stored procedure which automatically fires when a DML operation is performed on a table.
Triggers are used to maintain data integrity and provide the security to table.
Types of Triggers
(1)For triggers: Fires after DML operation.
(2)Instead of triggers: Fires before DML operation.
1. For triggers:syntax: create trigger <trigger name> on <tablename>
For [insert/update/delete] as
<T-SQL statements>
(1)create a trigger on emp table for insert
create trigger emp_trig on emp For insert As print ‘Record inserted successfully’
insert into emp (empno,ename) values (115,’RAM’)
when a trigger is created two virtual tables are generated. They are inserted table & deleted table.
Insert – Inserted - newly inserted record
Delete-Deleted-All deleted records
Update --------1.Inserted-Newly modified records
2.Deleted-old records
**write a query to display [find] 3rd highest salary.select sal from emp where 2=(select count(*) from emp e where emp.sal<e.sal)
1.create a trigger for insert om emp table to check the condition salary must not be less than 2000.
create trigger emp_trig1 on emp
for insertas--select * from insertedif(select sal from inserted)<2000Beginprint ‘sal must be >2000’Rollback Tranelseprint ‘Records inserted successfully’
2.create a trigger not to allow the records on Saturday
create trigger emp_trig2 on emp for insert as if(select datename(weekday,Getdate()) Like Saturday Begin print ‘U cannot insert records on Saturday’ Rollback Tran end else print ‘Records inserted’
insert into emp(empno,ename,salary)
3.create a trigger on emp table not to accept the records before 9 and after 5
create trigger emp_trig3 on emp for insert As if(select DateTime(HH,Gettime()) between 9 and 17 Begin print ‘Records inserted’ and else begin print ‘Cannot insert records after office hours’ Rollback Tran end
4.create a trigger for delete on emp table not to allow users to delete morethan two records at a time.
create trigger emp_trig4 on emp for delete as
--select * from deletedif(select count(*) from deleted)>2Beginprint ‘U cannot delete more than two records at a time’Rollback Tranelseprint ‘Records deleted’
***Queries:(1)write a query to display the first highest salary.select max(sal) from emp.
(2)write a query to display the details of second highest salary.
select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))
5.create a trigger for update on emp table
create trigger emp_trig5 on emp for update as /*select * from inserted select * from deleted*/ print ‘Records uipdated’
update emp set salary=32000 where empno=101
Modifying a trigger
Alter trigger emp_trig5 on empfor updateasif update(empno)print ‘empno is updated’if update(ename)print ‘ename is updated’if update(salary)print ‘salary is updated’
2.Instead of triggers:
syntax: create trigger <triggername> on <tablename>/<view name>instead of [insert/update/Delete]
as<T-SQL statements>
To display the trigger on tablesp_helptrigger on table
1.create a trigger on emp table not to modify the table.
create trigger emp_trig on emp instead of insert,update,delete AS print ‘U cannot modify table’ Delete from emp update emp set salary=9000
select * from emp
2.create a view for the employees total salaries in each department.
create view v10 as select deptno,sum(salary) as total salaries from emp Group by deptno create trigger view_trig on v10 instead of insert,update,delete As print ‘U cannot modify view’
Deleting Triggers
Syntax: Drop trigger <trigger name> Drop trigger emp_trig1,emp_trig2
Executing procedure within trigger:
create procedure p10 as print ‘visix’ create trigger emp_trig on emp instead of insert,update,delete asexec p10 print ‘Ameerpet’
Delete from emp
Backup and Recovery
Backup: Storing a copy of the files in another location.
Restore: Getting back or recovering from deleted files.