Upload
meetrocky
View
41
Download
0
Tags:
Embed Size (px)
Citation preview
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
Ex:
EMP
Empno Ename deptno101 John 10102 Sam 20
Dept
Deptno Dname Loc10 Sales Hyd20 Accounting pune
RDBMS: Relational database management system.RDBMS=DBMS+RELATIONAL MODEL.
ORDBMS: Object relational database management systemORDBMS=RDBMS+OOPS
ARCHITECTRE OF SQL SERVER:
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.
C:\program files\microsoft sql server\ms sql\Data.
Sql Server 2005:
In sql server 2005 query analyzer and enterprise manager are in a single window.
How to open sql menu:
Start-programs- Microsoft Sql server 2005- sql server management studio
Note: In sql server 2005 the default memory allocated for data file is 2 mb and for logfile is 1 mb.
Query Analyser:
It is a programming tool to create and maintain database objects.
Steps to open Query analyzer
Start- programs - Microsoft sql server Query analyzer
Server
... Window authentication
.
ok
This setting is for local system
hostserver
Sql server authentication
salogin
password
ok
System
T-Sql commands:
1) Information rule: To store the information into database that information must be in the form of tables.
T-SQL –Non – procedural language.
- Accepts only one statement.
Query Analyser
Object Query windowBrowser
Result window
T-SQL
commands programming
2) Integration of sublanguages:
--- DDL-- DML-- DQL ( or) DRL- DCL- TCL.
1) DDL(Data definition language): used to define database objects.
Commands create, alter, drop
2) DML(Data manipulation language)
Commands- insert, update, delete.
3) DQL(data query language) or DRL (Data retrieval language)
Commands-- select.
4) DCL(Data control language)
Commands Grant, Revoke, Deny.
5) TCL(Transaction control language)
Commands-- Commit, Rollback.
1. DDL Commands:
Create - used to create database objects.
Creating database:
Syntax: create database <databasename>
-- create database SQL CLASS.
Steps for executing the command
Select the statement
|press F5.
Using a database:
use <database name>
- use sql class.
- To display all the tables in a database command is sp_tables.
- Sql commands are used for creating modifying and for other manipulation on database objects.
-- Software commands are use for environment settings and to get the details database objects.
SQL SERVER
Sql commands Software commands---
Only for sql server environment
Creating a table::
Syntax: create table <tablename>(col1 datatype, col2 datatype,........,coln datatype)
Sql server----1024 columns allowed for table.
Oracle—1000 columns allowed for table.
Rules for creating a table
-- Table names must be unique in a database. Space characters are not allowing table names.
- special characters are not allowed in columns.- datatypes are must for each column.
Datatypes:
- Type of data to be stored in columns
1) Built in datatype- provided by software2) User defined datatypes- defined by user from built-in datatypes.
1. Character datatypes:2. Numeric datatypes.3. Datetime datatypes.
1) Character datatypes:
A) Char---used to store characters
minimum size is 1 byte, maximum size is 8000 bytes.
B) varchar---used to store alphanumeric values|--- ANSI characters.
-- minsize is 1 byte, maxsize is 8000 bytes.
Difference between char and varchar
In case of char:
In case of varchar:
Char varchar
1. Fixed length datatype 1. variable length datatype2. a char(10) 2. a varchar(10)
V I s I x
Wastage of memory
V I S I X
Release the unused bytes
nchar: used to store characters
minsize is 2 bytesmaxsize is 4000 bytes.
nvarchar: used to store alphanumeric values .
minsize is 2 bytesmaxsize is 4000 bytes.
Unicode characters:--- universal codes.
Note: nchar and nvarchar can understand any universal code characters where as char and varchar can understand only ANSI characters.
2) Numeric datatypes:
Integer values:
Tiny int ------1 byte
Small int--- 2 byte
Int-----4 bytes
Big int--- 8 bytes
Float-----8 bytesReal -----4 bytes
3) Datetime datatypes:
Small datetime (or) date time --- 4 bytes.
Big datetime ---- 8 bytes
Integer values
Decimal values
Sql Server date format:
-- mm/dd/yy
05/31/07
2007-05-31 00:00:00
7777-mm-dd hh:mi:ss
Image: used to store pictures
Text---datatype is used to store large amount of data.
Money—datatype is used to store money values.
EMP:
empno ename salary deptno doj
create table emp(empno int, ename varchar(10), salary money, deptno int, doj datetime)
To display description of a table:
Ex: sp_help <tablename>
-- sp_help emp
(or)
- emp alt+f1
student
sid sname dob coursejoined doj
create table student( sid int, dname varchar(10),
dob datetime,coursejoined varchar(10),doj datetime)
alter--- used to modify the structure of database objects.
Deleting columns
delete empname, salary and deptname columns
-- Alter table emp drop columns ename,salary and deptname
Note:
A table must contains atleast one column.Adding columns to the table.
1. write a query to add managerid and commission to emp table.
Alter table emp add managerid int, commission int
Modifying columns
a) changing the datatye of columnsb) Increasing or decreasing the size of columns
Syntax: alter table <tablename> alter column <column name> datatype
Change the datatype of salary column to float.
Alter table empAlter column salary float
Increase the size of ename to 30 characters:
- alter table empalter column ename varchar(30)
- decrease the size of ename to 5 characters
alter table empalter column ename varchar(5)
Note: To decrease the size of column the existing data must satisfy the size or data doesn’t exist.
Renaming columns in table
Syntax:
sp_rename ‘tablename.oldcolumnname’, new colname
- sp_rename ‘emp.empno’,employnumber
change the ename column to employ name
-- sp_rename ‘emp.ename’,employname
Renaming a table
Syntax:
sp_rename oldtablename,newtablename
- sp_rename emp,employ
- sp_help employ
Renaming a database
Syntax:
sp_renamedb olddatabasename,new databasename
- sp_renamedb sqlclass,sql server class
Note: Renaming a database is not possible in enterprise manager in sql server 2000, possible in sql server 2005.
Navigation:
select the database -- Right click--- rename
Drop--- used to delete database objects.
Dropping a table
syntax: drop table <tablename>
- drop table emp
Dropping a multi tables
syntax: drop table <table1> <table2> ....
--- drop table emp, student
Deleting a database:
syntax: drop database <database name>
-- drop database sqlclass- drop database emp
Note: databases cannot be deleted when they are currently in use.
Deleting a multidabases:
syntax:
drop database <database1> <database2> ......
--- drop database sqlclass,emp
note: multiple databases can be deleted when they are not currently use.
2. dml commands:
insert: used to insert the data into tables.
syntax:
1) insert into <tablename> values (value1,value2 , ........)
2) insert into <tablename> select value1,value2,......
3) insert into <tablename> (col1,col2) values (value1,value2....)
create table emp1(empno int, ename varchar(10), salary int, job varchar(10), deptno int)
insert into emp1 values(101,'Ram',5000,'clerk',10)
insert into emp1 values(102,'vamsi') --Error
2 nd method:
insert into emp1 select 103,'John',8000,'Analyst',10
select * from emp
note:
single quotation(‘ ‘) is must for varchar datatype
NULL VALUE
A null value is an undefined value.
A null value indicates that the column is empty.
A null value is not equal 0
A null value is not equal to another null value.
Null value are independent of the datatype.
Emp:
ex:
Implicit method:Explicit method:
1) implicit method:
-- sql server inserts null values when user is not supplying the values to column.
ex: insert into emp(empno, ename) values(101,’Ram’)insert into emp(empno) values (102)
2) explicit method:
-- In explicit method user has to supply null values
-- insert into emp values(103,’John’,null,null)
- insert into emp values(104,null, 5000,10)
Note: To insert the null values into the columns of varchar and datetime datatypes remove single quotations.
update:
used to modify records in a table.
empno ename salary deptno
101 Ram null null102 null null null
syntax:
1) update <tablename> set <column1> =value, <column 2>=value ........||--- modifies all records in table.
2) update <tablename> set <col1>=value, <col2>=value where <condition>
| ----- modifies only those records satisfying condition.
Operators:
1) Arithmetic operators: +,-,*,/
2) Relational operators: >,<,>=,<=,<>(not equal to)
3) Assignment operators-- =(equalt to)
4) Logical operators: and,or,not
5) special operators:in,not in, between, not between, like, not like,is null, is not null
exp1 exp2 and or
T T T TT F F TF T F TF F F F
EMP:
1) Increase the salaries of all the employees by 1000 rupees
- update emp set salary=salary+1000
Note: Any arithmetic operation performed on null value will not affect them.
2) Increase the salaries of employees by 500 who are working in deptno10.
-- update emp set salary=salary+500 where deptno=10
3) modify the salaries of employees 20000 where salaries are null.
- update emp set salary =isnull(salary,0)+20000 where salary is null
4) modify empno as 103,salary 15000 who are working in deptno10 and working as ‘analyst’
-- update emp set empno=103, salary=salary+15000 where deptno=10 or job=’analyst’
5) modify the salaries of employees to 10000 working in 10,20 departments
--- update emp set salary=salary +10000 where deptno=10 or deptno=20
empno ename salary deptno job
101 hari 1000 10 clerk102 kiran null 20 managernull ram 3000 10 analyst104 null 4000 20 clerk
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.
Truncate: Used to delete records in table.
Syntax: Truncate table <tablename> Truncate table emp.
Differences between Delete---Truncate
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>
select * from <tablename> where <condition>
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
Distinct Clause:
Used to eliminate duplicate values.
syntax: select distinct col1,col2........from <tablename>
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())
Week: no. of weeks in a year
select datepart(week,Getpart())select datepart(yyyy,Getdate())select datepart(yy,Getdate())select datepart(y,Getdate())select datepart(mm,Getdate())select datepart(m,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.
-- select dateadd(day,3,’5/15/07’)- select dateadd(month,4,’5/15/07’)-- select dateadd(year,5,’5/15/07’)
Datediff--- finds the number of days, months, years difference between two dates
select datediff(day,’6/7/06’,’5/3/07’)
select datediff(month,’6/7/06’,’5/3/07’)
select datediff(year,’6/7/06’,’5/3/07’)
convert--- used to convert numeric values into varchar data type.
convert(varchar(15), datepart(year,doj))
select datepart(hh,getdate())---hourselect datepart(mi,getdate())------month
select datepart(ss,getdate())
select datepart(n,getdate())
creating a table from existing table:
1) with records:
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.
Types of Joins(1)cross join(2)inner joinEqui Join, Non-Equi Join(3)Outer joinleft outer Join,right outer join,full outer join(4)self join
(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.
--- select * from salgrade, dept, emp
-- select * from salgrade cross join dept cross join emp
***Inner join:
- It retrieves only matched records from tables.
1. Equi join2. non-equi join
equi join:
To use equi join ‘=’ operator is must. Their must be a common column to write equi join condition.
grade
losal
deptno
loc
500
1100
2100
500
1100
2100
500
1100
2100
1000
2000
3000
1000
2000
3000
1000
2000
3000
10
10
10
20
20
20
30
30
30
sales
sales
sales
accounting
accounting
accounting
research
research
research
hyd
hyd
hyd
bng
bng
bng
pune
pune
pune
hisal dname
1
2
3
1
2
3
1
2
3
syntax:
1) select table1.col1, table1.col2, ........, table2.col1,table2.col2
where table1.col=table2.col
2) select table1.col1, table1.col2,.....,table2.col1, table2.col2,...... fromtable1 inner join table2 on table1.col =table2.col.
1) write a query to display empno, ename, salary, deptno, dname of the employees.
--- select e.empno,e.ename,e.sal d.deptno,d.dname from emp e, dept d where e.deptno=d.deptno
ex:
2) write a query to display emp name, salary, job and loc of the employees
---- select e.ename , e.sal, e.job, d.loc fromemp e, dept dwhere e.deptno=d.deptno
empno ename sal deptno dname
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.
syntax:
select table1.col1,table1.col2,table2.col1,table2.col2 fromtable1 rightouterjoin table2on table1.col=table2.col
1) write a query to display empno,ename,deptno, dname,loc from emp and dept tables, and unmatched records from dept tables.
---- select e.empno,e.ename,d.deptno,d.dname,d.locfrom emp e rightouterjoin dept don e.deptno=d.deptno
empno ename deptno dname loc
101 Ram 10 sales hyd102 anil 20 accounts bng103 vamsi 10 sales hyd104 kiran 10 sales hyd105 John null null null
1) Full outer join :
Displays matched and unmatched records from both tables.
--- select e.empno,e.ename ,d.deptno,d.dname,d.locfrom emp e fullouterjoin dept don e.deptno=d.deptno
empno ename deptno dname loc
101 Ram 10 sales hyd102 Anil 20 Accounts bng103 vamsi 10 sales hyd104 kiran 10 sales hydnull null 30 Research pune
empno ename deptno dname loc
101 Ram 10 sales hyd102 Anil 20 Accounts bng103104105 John 10null null 30 Research pune
SELF JOIN:
A table which joins to itself is called self join.
---- It creates 2 virtual tables c1,c2.
--- It creates two duplicate tables not visible c1,c2 like emp table.
write a query to display the manager of all the employees
--- select c1.empno,c1.ename, c2.empno as mgrid, c2.ename as manager name from emp c1, emp c2 where c1.mgrid=c2.empno
empno ename mgrid job
101 Ram 104 Analyst102 Anil 101 clerk103 vamsi 104 analyst104 John null president105 kiran 104 manager
Creating the Database:
Primary files: It contains both system information and user information.
Secondary files: These files contains only user information.
Log files: These files contains temporary transaction performed on the data.
empno ename mgrid manager name
101 Ram 104 John102 Anil 101 Ram103 vamsi 104 John105 Kiran 104 John
Data files
Log file(.ldf)
primary files(.mdf)
secondary files(.ndf)
How to create Database:
Create database visix on primary(name=’visix_data.mdf’,filename=’c:\test\visix_data.mdf’,size=5mb,maxsize=10mb,filegrowth=1mb)
log on
(name=’visix_log.ldf’, filename=’c:\test\visix_log.ldf’,
size=2mb,max size=5mb,file growth=1mb)
Adding secondary files(modifying database):
alter database visixadd file( name=’visix_data1.ndf’,filename=’c:\test\visix_data1.ndf’,size=3mb,max size=5 mb,file growth= 1mb)
Identity:
Used for autogeneration of numbers
syntax:
location of the file
physical name
identity (seed, incrementing value)
ex: identity(1,1) output-- 1,2,3,4 identity(10,5) output- 10,15,20
-- 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
sid sname course
1 Ram sql2 Anil oracle1 Ram sql3 Vamsi C2 Anil Oracle
output:
step2:
copy the distinct values into new table.
-- 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
syntax:
create table <tablename>(col1 datatype unique, col2 datatype ..........)
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.
syntax:
create table <tablename>(col1 datatype default <value>,.....)
create table deptdeptno int unique,dname varchar(10) not null,loc varchar(10) default ‘hyd’)
-- insert into dept values(10,’sales’,’bng’)-- insert into dept values(20,’accounting’,null)
- insert into dept(deptno,dname) values(30,’research’)
here default loc is hyd, user not supplied value.
note:
default constraint will accept null values if user is supplying.
unique notnull hyd
deptno dname loc
3) check constraint:
used to while conditions on columns.
syntax:
create table <tablename>(col1 datatype check (<condition>) ......)
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.
syntax:
create table <tablename>(col1 datatype primary key, col2 datatype.....)
-- 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.
ex:
syntax:
empno ename dob doj
p.key nn nn nn
sp_helpconstraint <tablename>
- sp_helpconstraint emp
giving user defined names to constraints.
Column level
syntax: create table <tablename> (column1 datatype constraint <constraint name> <constraint name>,column2 ........)
Table level
syntax:
create table <tablename>(column1 datatype, column2...........,constraint <constraint name> <constraint type>(column) .........)
Column level how to create 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)
Table level
syntax:
create table emp( empno int,ename varchar(10) not null,sal int, dept int,constraint p_key primary key (empno),constraint c_cnst check (sal>5000),constraint f_key foreign key(deptno)references dept(deptno))
create table emp( empno int,ename varchar(10) not null,dob datetime not null,doj datetime not null,primary key(empno),check(doj>dob))
note:
To define a constraint on multiple columns use table level constraints.
composite primary key
A primary key defined on multiple columns is called composite primary key.
create table trains
p.key nn nn nn
empno ename dob doj
condition: doj>dob
( trainno int,compno varchar(10),seatno int,doj datetime,primary key(trainno,compno, seatno,doj),check=(doj>getdate())
Deleting constraints on table:
syntax:
alter table <tablename>drop constraint <constraint)
1) drop check constraint on emp table
-- sp_help constraint emp1
alter table emp1 drop constraint c_cnst
2) drop primary constraint on emp table
-- sp_help constraint emp1
alter table emp1 drop constraint p_key.
3) drop not null constraint on emp table.
--- sp_help constraint emp1alter table emp1 drop constraint p_keyalter table emp alter column ename varchar(10) null
Note:
To drop a primary key constraint on master table,first drop foreign key constraint on child table and then drop the constrainst on the master table.
--- sp_help constraint dept.
alter table emp1 drop constraint f_key
alter table dept drop constraint pk_dept_76cba758
-- sp_help constraint emp
alter table emp drop constraint fk_emp_deptno_7A9C383C
Adding constraints on table
syntax:
alter table <tablename>add constraint <constraint name> <constraint types> (column)
Add a primary key constraint on empno column
-- alter table emp add constraint p_key primary key(empno)
note:
The existing data must satisfy the constraint properties to add a constraint on table.
1) add a check constraint on job column for list of values clerk, manager, analyst
syntax: alter table empadd constraint check_cnstclerk(og in (‘clerk’,’analyst’,’manager’)
2) add a not null constraint on emp name column
-- alter table emp alter columnename varchar(10) not null
Note:
To add a primary key constraint first make the column as not null and then add a primary key constraint.
1) alter table emp alter columnempno int not null
Normalization
The process of dividing a table into multiple tables without loss of information is normalization
ex:
Normal forms:
1 NF
2 NF
3NF4 NF
BCNF(Boyce code NF)
5 NF
empno ename sal deptno dname loc leaves fromdate todate
101 Ram 1000 10 sales hyd 3 5/15/07 6/16/07
102 anil 2000 20 accounts bng 2 6/3/07 6/4/07
---- ---- ----- 30 research pune -- ---- -----
---- Ram 1000 10 sales hyd 2 6/5/07 6//07
1 st normal form:
The table should maintain atomic values or the intersection of rows and columsn must be atomic
1 NF:
2 NF:
The table should be in 1 NF and all non-key columns must be fully dependent on key columns.
empno prjid prjname doj
101 p1,p2 sales 5/7/07 ,accounts 6/3/07
102 p2,p3 accounts, 6/3/07 research 5/12/07
103 p3,p1 research 5/12/07 sales 5/7/07
empno prj id prjname doj
101 p1 sales 5/7/07101 p2 accounts 6/3/07102 p2 accounts 6/3/07102 p3 accounts 5/12/07103 p3 research 5/12/07103 p1 sales 5/7/07
student:
1 st table:
2 nd table:
project id prjname
p1 sales
p2 accounts
p3 research
p.key
empno prjid doj
101 p1 5/7/07101 p2 6/3/07102 p2 6/3/07102 p3 5/12/07103 p3 5/12/07103 p1 5/7/07
sid sname coursejoined doj actualfee feepaid
1 A sql 6/1/07 1000 5002 x oracle 6/10/07 2000 1500
p.key
course actual fee
1 st table:
3 rd table:
1 st table:
p.key
sid sname doj
f.key
sid feepaid due
empno ename sal deptno dname loc
1 a 1000 10 sales hyd2 b 5000 20 accounts bng
prjid prjname budget leaves fromdate todatep1 sales 1000000 2 5/7/07 5/9/07p2 accounting 2000000 3 6/6/07 6/9/07
2nd table:
3rd table:
4th table:
5th table:
deptno dname loc
p.key
empno prjid
f.key f.key
empno ename sal deptno
f.key
empno leaves fromdate todate
3 nf:
The table should be 1 NF and 2 NF and should eliminate transitive dependency.
Sub queries:
A query within a query
In subqueris inner query executes first and gives the result to outer query.
Based on the query results outerquery.
prjid prjname budget
p.key
ex: select ( select
outer query
inner query
result
based on the result of inner query outer query executes.
Types of subqueries:
1) single row subqueries2) multi row subqueries
1. single row subqueries:
An inner query which returns a single row to the outer query is called as single row subqueries.
1) write a query to display the employees who are working in sales department.
--- select * from emp where ( select deptno from dept where dname=’sales’)
2) write a query to display the employees who are working in Bangalore.
-- select * from deptwhere loc=’bng’
3) write a query to display employees who are doing the same job as ‘john’
-- select * from emp where( select job from emp where ename=’john’)
4) write a query to display the employees who are working in the dept of ‘anil’
-- select * from emp wheredept=(select deptno from emp where ename=’anil’)
5) write a query to display the name of john’s manager
select ename from emp where empno=( select mgrid from emp where ename=’john’)
dept dname loc
10 sales hyd20 accounting bng30 research pune
dept
6) write a query to display anil’s managers, manager name
-- select ename from where empno=( select ename from emp where empno=( select mgrid from emp where ename=’anil’))
7) write a query to display the first highest salary
-- select max(sal) from emp
8) write a query to display the details of first highest paid employee.
-- select * from emp where sal=( select max(sal) from emp)
9) write a query to display the second highest salary
-- select max(sal) from emp wheresal<(select max(sal) from emp)
10. write a query to display the details of second highest salary employees
select * from emp wheresal=(select max(sal) from emp where sal<(select max(sal) from emp))
empno ename sal job mgrid deptno
101 Ram 1000 clerk 102 10102 Anil 2000 analyst 104 20103 John 3000 clerk 102 10104 Vamsi 4000 mgr 105 20105 Sam 5000 president null 10
11)write a query to display the details of 3rd highest salary of employees.
- select * from emp where sal=(select max(sal) from emp wheresal<(select max(sal) from emp wheresal<(select max(sal) from emp)))
12) write a query to display the employees whose salaries are more than the average salaries of employees in deptno 20
- select * from emp where sal>(select avg(sal) from emp where deptno=20)
NOTE: A condition in inner query is not applied for outer query.
2. multi row subqueries:
An inner query which returns multiple values to the outer query is called as multirow subqueries.
ex: IN-- list of values
any --- more than minimum< any-- less than maximum
all- more than maximum
< all- less than minimum
IN:
write a query to display employees working in sales and accounting dept’s
select * from emp where deptno indeptname in(‘sales’,’accounting’)
3. write a query to display the employees whose salaries are more than the minimum salaries in deptno 10
-- select * from emp where sal> ( select min(sal) from emp where deptno=10
Multi query method:
-- select * from emp where sal> any ( select sal from emp where deptno=10)
NOTE: > any operator first finds minimum value from a list of values and then retrieves the records more than that minimum values.
<Any:
write a query to display the employees whose salaries are less than the maximum salaries in deptno 20
-- select * from emp where sal<any(select sal from emp where deptno=20)
NOTE: < any operator first finds maximum value from a list of values and then retrieves the records less than that maximum value.
>All:
write a query to display the employees whose salaries are more than the max salaries in deptno 20.
--select * from emp where sal >all (select sal from emp where deptno=20)
NOTE: >All operator first finds maximum value from a list of values and then retrieves the records more than that maximum value.
<All:
write a query to display the employees whose salaries are less than the minimum salaries in deptno 20.
--select * from emp where sal <all (select sal from emp where deptno=20)
NOTE: <All operator first finds minimum value from a list of values and then retrieves the records more than that minimum value.
________________________________________________________________________
Co-Related SubQueries
select(select)
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
Transaction stands for it’s unit of work.
Types of transaction:
1) autocommit transactions:2) explicit transactions3) implicit transactions
1. autocommit transactions:
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.
xp_cmd shell ‘Dir’xp_cmd shell ‘copy c:\AP.TXT D:\AP.TXT’
3.User Defined Procedures:
These procedures are defined by users.syntax: create procedure <procedure name> as <T-SQL Statements>
1.create a procedure to find the sum of two numbers
create procedure p1AsDeclare @ A int,@ B int,@ c intset @ A=10set @ B=20set @ C=@ A+@ Bprint @ C
exec p1
procedures with parameters:
syntax:
create procedure <procedurename>(para m1, para m2 ..........)as< T-sql statements>
--- alter procefure p1(@a int, @b int)asdeclare @c intset @c=@a+@bprint @c
-- exec p1 10,20exec p1 34,56
1. create a procedure to get the details of a student for the given empno
1.create procedure to get the details of a student for the given empno
-create procedure p2(@n int)asselect * from emp where empno=@n
2.create a procedure to displaying the records in emp table.
-- create procedure sp_empasselect * from emp
-- exec sp_emp(or)- sp_emp
2. create a procedure to insert the values into a table.
- create a procedure sp_insert (@empno int, @ename varchar(10), @sal int)asinsert into emp values(@empno,@ename, @sal)
-- exec sp_insert 101,’Ram’,1000
Global variables:
--- Global variables contain system information useful to user.
- These global variables starts with @@symbols
a) @@version: Displays the current version of sql server
b) select @@language: result USEnglish
c)select @@connections:
Displays the number of connection establish to the sql server.
c) select @@error:
contains previously generated error number.
- alter procedure sp_insert(@empno int, @ename varchar(10),@sal int)
as
declare @n intinsert into emp values(@empno, @ename, @sal)set @n=@@errorif @n>0
print ‘record not inserted’else
print ‘record inserted successfully’
1) create a procedure for deleting the records in emp table for the given empno.
2) create a procedure to accept studentid, student name, marks of sub1, sub2 . calculate total and average and print all the details of student.
3) write a query to display all the procedure in a database.
-- select * from sysobjects where xtype=’p’
4) write a query to display the text of a procedure.
-- sp_helptext <procedurename>
sp_helptext sp_insert.
Procedures with parameters:
syntax:
create procedure <procedurename>( para m1, para m2 .......)as
<t-sql statements>
-- alter procedure p1(@ a int, @b in)as declare @c intset @c=@a +@bprint @c
--- exec p1 10,20exec p1 34,56
1.create a procedure to get the details of a student for the given empno
--- create procedure p2(@n int) Asselect * from emp where empno=@n
exec p2 102
2.create a procedure to display the records in emp table.
create procedure sp_emp As select * from empexec sp_emp (or)sp_emp
3.create a procedure to insert the values into a table.
create procedure sp_insert (@ empno int,@ ename varchar(10),@ sal int)Asinsert into emp values(@ empno,@ ename,@ sal)Exec sp_insert 101,’Ram’,1000
Global Variables
Global variable contain system information useful to user.
These global variable starts with @@ symbols.
(A)@@version: Displays the current version of SQL server.
(B)select @@ language: Result US English.
(C)select @@ combinations: Displays the number of connection established to the SQL Server.
(D)select @@ error: contains previously generated error number.Alter procedure sp_insert(@ empno int,@ ename varchar(10),@ sal int)asdeclare @ n intinsert into emp values(@ empno,@ename,@ sal)set @ n=@@ errorif @ n>0print ‘Record not inserted’elseprint ‘Record inserted successfully’
(1) create a procedure for deleting the records in emp table for the given empno.
(2) create a procedure to accept student ID,student name,marks of sub1,sub2 calculate total and average and print all the details of student.
(3)write a query to display all the procedures in a database.
select * from sysobjects where xtype=’P’
(4)write a query to display the text of a procedure.
sp_helptext <procedure name> sp_helptext sp_insert
Procedures without parameters
(1)create a procedure to find the sum of 2 numbers.
create procedure sp_add (@ A int,@ B int,@ C int out) as set @ C=@ A + @ B print @ C
Execution
declare @ sum intexec sp_add 10,20,@ sum out
Deleting procedures
syntax: Drop procedure <procedure name> Drop procedure p1
Drop procedure sp_insert ,sp_add
Executing procedure with in a procedure:
craete procedure p1 As print ‘SQL server class’
create procedure p2 As exec p1 print ‘At 7:30 pm’
Exec p2
(B)FUNCTIONS:
A function is a pre-defined program used to perform a specific task.
A function always returns a value.
Types of functions
(1)Built functions
(2)User defined functions: (a)Scalar valued functions
(b)Table valued functions
(a)Scalar valued functions:A function which returns a scalar value is called scalr valued functions.
These functions used for Mathematical calculations.
syntax: create function <function name> (para m1,para m2----------) returns <datatype> as begin return <statement> end
(1)create a function to find the sum of two numbers
create function Fun_add (@ A int,@ B int) Returns int As begin Return @ A +@ B end
select DBO,fun_Add(10,20)
Calling a function in program
Declare @ M int,@ N int,@ K int set @ M=19 set @ N=100 set @ K=DBO,fun_Add(@ M,@ N) print @ K
Calling a function while creating a table:
create table student (sid int, sname varchar(10),sub1 int, sub2 int, Total as DBO,fun_Add(sub1,sub2))
insert into student values(1,’Ram’,90,80)
insert into student values(1,’Ram’,40,80)
(B) Table valued functions: A function which returns a table is table valued functions.
syntax:
create function <function name > ()returns table asreturn <select statement>
1) create a function for the records in emp table.
---- create function f1()returns tableas return select * from emp
execution of a function
select * from dbo.f1()
2) create a function for empno, ename of the employees working in deptno=10
create function f2()returns tableasreturn select empno,ename for emp where deptno=10.
--- select * from dbo.f2()
Deleting a function:
drop function <function name>
drop function f1,f2
Indexes:
-- An index is a performance object
-- Indexes are used to retrieve the data fastly and efficiently.
NOTE: An index page requires 25 % extra to the actual memory of records.
extent: collection of 8 pages in extention
sytax: create <index type> index <index name>on <tablename> (column)
101 RAM 1000102 KIRAN 2000
103 KRISHNA 7000104 _ _105 _ _
106 _ _107 _ _
page1 -101,102page2-103,104,105page 3-106,107
8 kbpage 1
8 kb
page 2
page 3
index page
Types of indexes:
1) clustered index2) non-clustered index3) unique index4) composite index.
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.
Keywords: first,last,next,prior,obsolute,relative.
2.Static cursors: Supports all the keywords.
first Displays first record in cursor.
next Displays next record in cursor.
last Displays last record in cursor.
prior Displays previous record in cursor.
Absolute N Displays Nth record from top.
Absolute –N Displays Nth record from buttom.
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.
creating Backup:
open enterprise manager
Microsoft SQL Servers
SQL Server
Local
Databases
select a database(visix)
Right click & select all tasks
Backup database
General
NameBackup
Database-completeDesignation
Filename
Select location filename
Visix back bak
Addok
ok
ok
Steps for Restoring:
Restore a database:
open enterprise manager
Microsoft SQL Servers
SQL Servers group
Local
DataBases
Right click & select all tasks
Restore database
General/options
Restore as database
Restore from device
select filename & click ok
visix
select Device
Restore from disk
ADD
Filename
Types of Backup
(1)Complete backup(2)Differential backup(3)Transaction log backup(4)Files & Filegroups backup
1.Complete backup:- Takes a backup of entire database including primary,secondary,log files.
2.Differential backup:- Takes a backup of newly added files after complete backup.
3.Transaction log backup:- Takes a backup of only log files.
4.Files & file groups backup:- Takes a backup of only selected files.
JOBS
A job is a unit of works done by the system at schedule date of time.
Steps for jobs:
Open enterprise manager
Microsoft SQL Servers
SQL Server group
Local
SQL Server Agent Must be in green colour
Jobs Right click & select new job
If the job is not scheduled to execute the job select the job right click on select job. Again right click and click on refresh job.
If job is scheduled automatically job executes.
General steps schedules
Job
select output files & give filename(jobsoutput.txt) select date & time
click apply & ok click apply and ok
DTS
schedules
steps
General Advanced
Step name
Database
CommandSelect * from emp
Job nameJob1
new
new schedule
Name
Recurring
s1
change
change
step1
visix
DTS –Data Transformation services
DTS is used for importing & exporting the files from one software to another software.
(1)Copying tables from one database to another database.(2)Import/export files(3)Creating packages
Copying Tables from one database to another databaseImport/Export files
Steps:Open enterprise manager
Microsoft SQL Servers
SQL Server group Local
Databases
Select a databases(Northwind)
Right click & select all tasks
export data
next
select filename
nextselect required sheets
next
Choose a Destination
Destination
Server
Windows Authentication Windows Authentication
Database
Choose a DatasourceDatasource
Filename
Student
Local
M/S OLE DB provider for SQL Server
M/S Excel 97-2000
finish
Providers
Notepad - SQL Server(text file)Oracle - SQL Server
Choose a DatabaseData source
next
select reqired sheets next
finish
succeeded
PACKAGES
Creating Packages
A package is a group of multiple connections.
The extension name is for packages .DTS
Packages can provide a security.
Packages can be stored in cd’s and floppy’s.
M/S OLE provider for Oracle
properties
Choose a Destination
Destination
Server
Windows authentication
Database
M/S OLE DB provider for SQL Server
local
student
server name
Username
Test connection
DTS PACKAGE .DTS
Excel (source) server(destination)
Access(destination)
Open enterprise manager
Microsoft SQL Servers
SQL Server group
Local
Data transaction sevices
Local packages Right click & select new packageDTS PackageICONS
select filenameselect filename
4. Go to task menu & select Transform data task(select source & destination icons)
X(Excel)
Access
SQL Server
Destination 2
Server
Windows Authentication
Database
Datasource
FilenameDatasource 1Filename
Student
Local
M/S OLE DB provider for SQL Server
M/S Excel 97-2000M/S Excel 97-2000
click on create
click on create Right click on TDT & Properties
10. To execute the package click on execute icon. To execute a single step right click on transform data task.
11. To save the package go to package menu & click on save.
To save the package in cd’s/floppy’s go to package menu & click on save as & select the location as structured storage file.
Access SQL Server
Oracle
excel
SQL SERVER 2005(Yukon) start
TDT
O
X
source Destination Transform
Selecttable/view
programs
Microsoft SQL Server 2005
SQL Server Management studio
select * from sys.sysobjects where xtype=’U’
SQL Server 2000 packages are called as DTS packages.
DTS packages are replaced with SSIS in SQL server 2005.SSIS-SQL Server Integration services(.dtsx)
In SQL Server 2000 .dts.
In SQL Server 2005 .DTS x
notepad(source) - SQL Server(destination)
Creating packages in SQL Server 2005(SSIS)
start
programs Microsoft SQL Server 2005 SQL Server Business Development Studio Filename new project select integration services project
click on
Right click on SSIS Package in solution explorer
select new package click on data flow
click on hyperlink
select tool box & select source and destination icons drop & drop it on the form
1
Flat file source
SQL server destination
connection manager
mappings
new
conection manager
Name
filename
Delemeled
server
SQL serverauthentication
login name
database
1
2
3
a
b
click on mappings
host
sa
visix sql
ok
To execute the package right click on the package name and click on execute package.
Generating sql script:
A script file is required to avoid inconsistency in the tables when they are recreated.
......
..
.
.
.
.
......
....
..
.
..........
........
......
developers Testers client
.exe
Open Enterprise mangaer
Microsoft sql server
sql server group
local
databases
select a databases (visix)
tables
select a table(emp.dept)
right click and select generate sql script
click on show all
select required database objects
click ok
save the (script.sql) file
save
Executing the script:
open query analyzer|___> open ur database |--- copy the script file into query analyzer and execute it.
Security:
Creating Windows users
select my computer
Right click & selectmanager
Local users & groups
Users
Right click & select new user
Give username & password
Click on create & close
Granting permissions to windows user:
open Query analyzer and use the commandsp_grantlogin ‘Linux7\w user’
system name username
Revoke- It’s a permanently removed command.Deny- It’s a temporarily removed command.
sp_revoke login ‘Linux 7\wuser’sp_deny login ‘Linux 7\wuser’
SQL Server Authentication
Creating SQL Server Users:
sp_Addlogin ‘Suser’,’Visix’
username password
Open Query Analyser with SQL Server Authentication
Granting permissions for user database:
when SQL Server user is created he has permissions only to access system databases.
To grant permissions to user databases.
SQL Server
SQL Server Authentication
Login name
Password Visix
Suser
ok
Follow the navigation:
Open enterprise manager
Microsoft SQL Servers
SQL Server group
Local
Security
Select username(S user)
Right click & select programs
click on database access tab
select databases
click ok
Deleting SQL Server:
sp_droplogin ‘Suser’
Note: The user cannot be deleted when it is currently logged (or) he has got permissions to access user databases.
Locks
It is the mechanism used by sql server to maintain multiple users at a time.
Types of Locks:
(1)Shared locks(2)Exclucive locks(3)Update locks
1.Shared locks: Shared locks allows only retrieval of no modifications are possible.
2.Exclusive locks: This is only for updations (or) modifications.
3.Update locks: It is combination of shared locks and exclusive locks.
Interview Questions(SQL Server) website:
www.geekinterview.com
Questions doubt clarification website:
www.sqlteam.com
SQL Commands website:
www.msdn.microsoft.com