You are on page 1of 133

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: Its 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.

Server EMP

C1

C2

C3

Versions of SQL Server: Sql Server 6.5 SQL Server 7.0

Sql Server 2000 Sql Server 2005

Back up and Recovery programming concepts(Yukon ) .net integration

Features of Sql Server: Highly Scalable Replication Internet support Security Parallel 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.

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 101 102

Ename John Sam

deptno 10 20

Dept

Deptno 10 20

Dname Sales Accounting

Loc Hyd pune

RDBMS: Relational database management system. RDBMS=DBMS+RELATIONAL MODEL. ORDBMS: Object relational database management system ORDBMS=RDBMS+OOPS ARCHITECTRE OF SQL SERVER:

System database

MASTER

MODEL

MSDB User database

students

employees

Sql Server is supporting only windows operating system. Logins: 1) Operating system loginwindows users 2) Sql server login- Sql server users. Tools of sql server:

Enterprise manager DBA Query Analyser-Developers Enterprise Manager: It is an administrative tool to create and maintain database objects.

Database objects are 1. 2. 3. 4. 5. 6. Tables Fields Views Stored procedures Triggers 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: its a temporary database. 5) Northwind: Used only for practice 6) pubs: purpose.

Enterprise Manager: It is an administrative tool to create and maintain database objects. STEPS TO OPEN ENTERPRISE MANAGER:

programs

Start Microsoft sql server

Enterprise manager

Microsoft Sql servers | ---- Sql server group | ---- local |-- Databases |___ Tables | -- Views

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 file Secodary 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

. This setting is for local system

...

Window authentication

ok

server

host

Sql server authentication

login password ok

sa

System

Query Analyser Object Browser Query window

Result window

T-SQL commands programming

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.

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 SERVER

Sql commands

Software commands---

Only for sql server environment

- 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.

Creating a table:: Syntax: create table <tablename>(col1 datatype, col2 datatype,........,coln datatype) Sql server----1024 columns allowed for table.

Oracle1000 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 software 2) 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

Char 1. Fixed length datatype 2. a char(10)

varchar 1. variable length datatype 2. a varchar(10)

In case of char:

Wastage of memory

In case of varchar: V I S I X

Release the unused bytes

nchar: used to store characters minsize is 2 bytes maxsize is 4000 bytes. nvarchar: used to store alphanumeric values minsize is 2 bytes maxsize 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 bytes Real -----4 bytes Decimal values Integer values .

3) Datetime datatypes: Small datetime (or) date time --- 4 bytes. Big datetime ---- 8 bytes

Sql Server date format: -- mm/dd/yy 05/31/07 2007.5.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. Moneydatatype 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 create table student ( sid int, dname varchar(10), dob datetime, coursejoined varchar(10), doj datetime) alter--- used to modify the structure of database objects. coursejoined doj

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 columns b) 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 emp Alter column salary float

Increase the size of ename to 30 characters: - alter table emp alter column ename varchar(30) - decrease the size of ename to 5 characters alter table emp alter column ename varchar(5) Note: To decrease the size of column the existing data must satisfy the size or data doesnt 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 2nd 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:

empno 101 102

ename Ram null

salary null null

deptno null null

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.

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 T T F F

exp2 T F T F

and T F F F

or T T T F

EMP:

empno 101 102 null 104

ename hari kiran ram null

salary 1000 null 3000 4000

deptno 10 20 10 20

job clerk manager analyst clerk

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

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 10 Delete from emp where deptno=10. (2)Delete the employees whose salaries are null and working in deptno 20 Delete from emp where salary is null and deptno=20. (3)Delete the employees whose salaries are >=1500 and <=3000 Delete from emp where salary >=1500 and salary<=3000. (4)Delete all the records in emp table Delete 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. DRL Commands-(select) Queryits 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. 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.

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:

selection empno 101 102 103 ename Ram Hari Kiran projection salary 1000 2000 3000 deptno 10 20 10

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

4) write a query to display the increase salaries of emps 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 emp where 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 emp where 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 15jun-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 emps whose name contains two AA --- select * from emp where ename like %A%A% q) write a query to display the emps whose name contains character A --- select * from emp where ename like %A% NOT LIKE: 1. write a query to display employees whose name doesnt 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 emps whose name doesnot contain fifth character s ------ select * from emp where ename not like ____s% 4) write a query to display emps 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 emps 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 emps whose salaries are not null -----select * from emp where salary is not null q) write a query to display emps 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 10000 and ename not like m% and salary is not null =---------------EMP

empno 101 102 103 104

ename Ram Smith Allen Hari

deptno 10 20 10 20

job analyst clerk manager clerk

Distinct Clause: Used to eliminate duplicate values. syntax: select distinct col1,col2........from <tablename>

1) write a query to display all the deptnos 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 emps in the order of their salaries. select * from emp order by salary 2)Write a query to display emps in the descending order of deptno select * 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 emps 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 emps who are working as managers in the descending of their deptnos and names. select * from emp where job=manager order by deptno desc,ename desc.

Group Functions
function: 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 total Avg- to calculate average Max- to find maximum value Min- to find minimum value Countcounts no. of records in a table. 1)Write a query to display total salaries of employees. select sum(sal) from emp select sum(sal) as total salaries from emp 2)Write a query to display the average salaries of emps working in deptno 20 select 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 emp select Max(sal) As highest salary select Min(sal) As lowest salary 4) Write a query to display the no. of records in a table select 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 emp select 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 names select 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 Functions


A function which process a single at a time is called as single row functions. LEN-It counts the number of characters in a given string eg: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 _____ or select * 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 characters select 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 times

select Replicate(SQL,5) ASCII: American Standard Code for Information Interchange Accepts 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 number select SQRT(625) Square: Calculates the square of a number select Square(10) Getdate(); displays system date and time select Getdate() Year- displays year from the specified date select year(5/7/05) Month: displays month from a specified date select month(Getdate()) Day: displays day in a specified date select day(Getdate()) Datepart: displays the specified part of the date select datepart(year,Getdate()) Weekday: displays the day no. in a week select 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 characters

select datename(month,Getdate()) select datename(month,2/6/05) select datename(weekday,Getdate()) (1)Write a query to display the employees who joined on Monday select * 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())---hour select 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 statement syntax: insert into <table name><select statement> insert into emp4 .select * from emp1 GROUP BY CLAUSE This 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 emp NOTE: Group by clause will consider as a new group. 2.write a query to display total salaries of emps in each category of job . select job ,sum (sal) from emp group by job. EMP EMP NO ENAME 101 Ram 102 john 103 sam 104 anil 105 kiran SAL 1000 2000 3000 4000 5000 JOB DEPT NO Clerk 10 analyst 20 Clerk 30 manager 10 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 emps 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 emps in each dept whose total salaries are >5000 select 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 all 2. union 3.intersect 4. except

2005 operators

1.union all: Displays all the values in the result of select statements including duplicates. ex: select deptno from emp union all select deptno from dept 2. union: Displays all the result of select statements eliminating duplicates. --- select deptno from emp union select deptno from dept 3. intersect: displays comman values in the result of select statements. --- select deptno from emp intersect select deptno from dept 4. except: Displays values that are in result of first select statement, second statement. -- select deptno from emp except select deptno from dept

- 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 emp except select 1990 * from emp

Inserting values using Union


Create table T1 (sid int,sname varchar(10)) insert into T1 select 1,Ram Union select 2,Vamsi Union select 3,Hari select * from T1 Note: The process of inserting multiple records is called bulk insert.

Joins
A 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 records 2) Inner join: equi join, non-equijoin 3)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

empno 101 102 103 104 105

ename hari kiran Ram sam john

sal 1000 2000 3000 4000 5000

job clerk analyst clerk manager president

mgrid 102 104 102 105 null

deptno 10 20 null 20 10

dept

deptno 10 20 30

dname sales accounting research

dloc hyd bng pune

salgrade:

grade 1 2 3

losal 500 1100 2100

hisal 1000 2000 3000

1. write a query to display the records from salgrade and dept tables.

grade 1 2 3 1 2 3 1 2 3

losal 500 1100 2100 500 1100 2100 500 1100 2100

hisal 1000 2000 3000 1000 2000 3000 1000 2000 3000

deptno 10 10 10 20 20 20 30 30 30

dname sales sales sales accounting accounting accounting research research research

loc hyd hyd hyd bng bng bng pune pune pune

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 join 2. non-equi join equi join: To use equi join = operator is must. Their must be a common column to write equi join condition.

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,...... from table1 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:

empno ename 101 102 104 105 hari kiran sam John

sal 1000 2000 4000 5000

deptno 10 20 20 10

dname sales accounting accounting sales

2) write a query to display emp name, salary, job and loc of the employees ---- select e.ename , e.sal, e.job, d.loc from emp e, dept d where e.deptno=d.deptno

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 from emp e, dept d where e.deptno=d.deptno and 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 on e.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 on e.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 its called as Non-Equi join. emp table empno 101 102 103 104 105 ename Ram Anil Vamsi John Kiran sal 1000 2000 3000 4000 5000 mgrid 104 101 104 105 null job Analyst Clerk Analyst Manager President deptno 10 20 10 10 20

dept table deptno 10 20 30 dname Sales Accounting Research loc Pune Hyd chennai

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 s where 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 s where 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 conditions Combination 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 103 ename Vamsi project empno 101 prjid P1 doj 5/6/06 sal 3000 loc Hyd

102 103

P2 P3

3/4/07 7/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 p where 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.

empno 101 102 103 104 105

ename Ram anil vamsi kiran John

deptno 10 20 10 10 null

dname sales accounts sales sales null

loc hyd bng hyd hyd null

--- 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 from table1 rightouterjoin table2 on 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.loc from emp e rightouterjoin dept d on e.deptno=d.deptno

empno 101 102 103 104 null

ename Ram Anil vamsi kiran null

deptno 10 20 10 10 30

dname sales Accounts sales sales Research

loc hyd bng hyd hyd pune

1) Full outer join : Displays matched and unmatched records from both tables. --- select e.empno,e.ename ,d.deptno,d.dname,d.loc from emp e fullouterjoin dept d on e.deptno=d.deptno

empno 101 102 103 104 105 null

ename Ram Anil John null

deptno 10 20 10 30

dname sales Accounts

loc hyd bng

Research

pune

SELF JOIN: A table which joins to itself is called self join.

empno 101 102 103 104 105

ename Ram Anil vamsi John kiran

mgrid 104 101 104 null 104

job Analyst clerk analyst president manager

---- 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 101 102 103 105

ename Ram Anil vamsi Kiran

mgrid 104 101 104 104

manager name John Ram John John

Creating the Database:

primary files(.mdf) Data files secondary files(.ndf)

Log file(.ldf)

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.

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 physical name

(name=visix_log.ldf, filename=c:\test\visix_log.ldf, location of the file size=2mb, max size=5mb, file growth=1mb)

Adding secondary files(modifying database): alter database visix add 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:

identity (seed, incrementing value)

starting 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

sid 1 2 1 3 2

sname Ram Anil Ram Vamsi Anil

course sql oracle sql C Oracle

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) 2) 3) 4) step1: count the number of duplicate records in table. copy all the distinct values into a new table delete duplicate records from table insert unique values into table. count the no. of duplicate records

--- select sid, sname, c=count(*) into s1 from student group by sid, sname having count(*) >1

output:

sid Ram Anil

sname

step2: copy the distinct values into new table. -- select distinct student.* into s2 from student s1 where student.sid =s1.sid and student.sname=s1.sname

sid 1 2

s2 sname Ram anil

course sql oracle

Step3: delete duplicate records from the actual table --- delete student from student, s1 where student.sid=s1.sid and student.sname=s1.sname

step4: insert unique values into table. insert into student select * from s2

student sid 1 2 3 sname Ram Anil Kiran course sql oracle C

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.

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>,.....)

unique deptno

notnull dname

hyd loc

create table dept deptno 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.

3) check constraint: used to while conditions on columns. syntax: create table <tablename> (col1 datatype check (<condition>) ......)

emp

unique empno

not null ename

7500 sal deptno

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

employ unique empno deptno notnull ename clerk or salesman job 15000&25000 sal not null

--- 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**** Its a combination of unique and not null constraints. --primary key constraints not allows duplicate values. -- Its 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

--- 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

dept

deptno

dname primary key

loc

references emp empno ename sal deptno

child table or detail table

foreign key primary key

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) -----wrong insert into emp values(102, vamsi,8000,10) -----right

library

master table

p.key

master table

book id

book name

sid

sname

course

p.key sid books foreign key child table foreign key book id issuedate

child table

create table student ( sid int primary key, sname varchar(10) not null, course varchar(10) not null) dept

deptno 10 20

dname sales accounting

loc hyd bng

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 101 102 Ram Anil

sal 1000 2000

deptno 10 10

p.key prjid

budget prjname master table p.key

master table dept deptno dname loc

p.key empno ename sal deptno foreign key project child table empno f.key prjid doj

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.

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:

empno p.key

ename nn

dob nn

doj nn

syntax:

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))

p.key empno

nn ename

nn dob

nn doj

condition: doj>dob

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

( 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 emp1 alter table emp1 drop constraint p_key alter 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 emp add constraint check_cnst clerk(og in (clerk,analyst,manager) 2) add a not null constraint on emp name column -- alter table emp alter column ename 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 column empno int not null

Normalization The process of dividing a table into multiple tables without loss of information is normalization ex:

empno 101 102 -------

ename Ram anil ---Ram

sal 1000 2000 ----1000

deptno dname 10 20 30 10

loc leaves fromdate todate 5/15/07 6/3/07 ---6/5/07 6/16/07 6/4/07 ----6//07

sales hyd 3 accounts bng research pune sales hyd 2 -2

Normal forms: 1 NF 2 NF 3NF 4 NF BCNF(Boyce code NF) 5 NF

1 st normal form: The table should maintain atomic values or the intersection of rows and columsn must be atomic

empno 101

prjid p1,p2

prjname sales ,accounts

doj 5/7/07 6/3/07 6/3/07 5/12/07 5/12/07 5/7/07

102 103

p2,p3 p3,p1

accounts, research research sales

1 NF: empno 101 101 102 102 103 103 prj id p1 p2 p2 p3 p3 p1 prjname sales accounts accounts accounts research sales doj 5/7/07 6/3/07 6/3/07 5/12/07 5/12/07 5/7/07

2 NF: The table should be in 1 NF and all non-key columns must be fully dependent on key columns.

p.key

project id p1 p2 p3

prjname sales accounts research

empno 101 101 102 102 103 103

prjid p1 p2 p2 p3 p3 p1

doj 5/7/07 6/3/07 6/3/07 5/12/07 5/12/07 5/7/07

student:

sid 1 2

sname A x

coursejoined doj sql oracle 6/1/07 6/10/07

actualfee 1000 2000

feepaid 500 1500

1 st table:

1 st table: p.key course actual fee

2nd table:

p.key sid 3 rd table: sname doj

f.key sid feepaid due

empno ename 1 2 a b

sal 1000 5000

deptno 10 20

dname sales accounts

loc hyd bng

prjid p1 p2

prjname budget leaves sales 1000000 2 accounting 2000000 3

fromdate 5/7/07 6/6/07

todate 5/9/07 6/9/07

1 st table:

p.key deptno dname loc

2nd table:

f.key

f.key

empno

prjid

3rd table: f.key

empno

ename

sal

deptno

4th table:

empno

leaves

fromdate todate

5th table:

p.key

prjid

prjname

budget

3 nf: The table should be 1 NF and 2 NF and should eliminate transitive dependency.

Sub queries: A query within a query

outer ex: select ( select query

inner query

result

based on the result of inner query outer query executes.

In subqueris inner query executes first and gives the result to outer query. Based on the query results outerquery.

Types of subqueries: 1) single row subqueries 2) 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. dept dept 10 20 30 dname sales accounting research loc hyd bng pune

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 dept where 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 where dept=(select deptno from emp where ename=anil) 5) write a query to display the name of johns manager select ename from emp where empno=( select mgrid from emp where ename=john)

6) write a query to display anils 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 where sal<(select max(sal) from emp)

empno 101 102 103 104 105

ename Ram Anil John Vamsi Sam

sal 1000 2000 3000 4000 5000

job clerk analyst clerk mgr president

mgrid 102 104 102 105 null

deptno 10 20 10 20 10

10. write a query to display the details of second highest salary employees select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))

11)write a query to display the details of 3rd highest salary of employees. - select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp where sal<(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 depts select * from emp where deptno in deptname 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 bidirectonal 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 1000 2000 3000 4000 5000 Countsal 1000 2000 3000 4000 5000 count 1000 - 0+1+1+1+1=4 2000 -3 3000 -2 4000 -1 5000 -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 option check 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=uusers =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 salary max(sal) as maximum min(sal) as minimum salary from 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 v2 as 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 r1 as @ 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 d1 as 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 transaction rollback---cancel the previous transaction Transaction stands for its unit of work.

Types of transaction: 1) autocommit transactions: 2) explicit transactions 3) 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 emp commit --------------- begin tran delete from emp commit ----- begin tran drop from emp rollback tran ---- begin tran

drop from emp rollback tran ----- begin tran insert 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>

insert update delete insert rollback A rollback B rollback A Begin Tran insert into emp(empno,ename)

values(125,Ram) save Tran A Delete from emp where empno=117 save Tran B update emp set salary=9000 where emp no=103 Rollback 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 on set 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=20 4.Print result: syntax: 1.print @ variable 2.print Message comments single 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=10 set @ B=20 set @ c=@ A+@ B print 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=10 set @ B=5

set @ c=@ A+@ B set @ c=@ A*@ B set @ c=@ A-@ B set @ 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+@M2 print 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 Datetime set @ 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=10 set @ B=20 print Before swaping print convert(varchar,@A)+space(4)+convert(varchar,@B) print After swaping set @ Temp=@ A set @ A=@ B set @ B=@ Temp

print 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 int set @ A=900 set @ B=178 if(@ A>@ B) begin print A is greater end else begin print B is greater end (2)write a program to print the greatest value among three numbers. Declare @ A int,@ B int,@ C int set @ A=900 set @ B=178 set @ C=80 if @ A>@ B and @ A>@ C print A is greater else if @ B >@ c

print 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=80 if @ N % 2=0 print convert(varchar,@N)+is Even else print 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<=10 begin print @ i set @ i=@ i+1 end (2)write a program to print the sum of 10 numbers Declare @ i int,@ sum set @ i=1 set @ sum=0 while @ i=10 begin set @ sum=@ sum+@ i set @ i=@ i+1 end print @ sum Assigning column values to variables Syntax: 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 emp if @ N>0 print Total records in table: +convert(varchar,@ N) else print No records in table T-SQL Programs

Unnamed T-SQL Programs Declare

Named T-SQL programs Create

*Difference between Unnamed and Named T-SQL Programs UN NAMED T-SQL 1.Un named T-SQL programs will temporary executes and display. 2.These programs doesnot have any name. 3.These programs starts with declare NAMED T-SQL 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.

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 select /*/ from emp

(1)Parse (2)Compile (3)Optimization (4)Execute Types of Procedures (1)System stored procedures (2)Extended stored procedures (3)User defined procedures

Data cache- Data Procedure cacheExecution plan

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 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 commands These 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 p1 As Declare @ A int,@ B int,@ c int set @ A=10 set @ B=20 set @ C=@ A+@ B print @ 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) as declare @c int set @c=@a+@b print @c -- exec p1 10,20 exec 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) as select * from emp where empno=@n 2.create a procedure to displaying the records in emp table. -- create procedure sp_emp as select * 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) as insert 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 int insert into emp values(@empno, @ename, @sal) set @n=@@error if @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 int set @c=@a +@b print @c --- exec p1 10,20 exec p1 34,56 1.create a procedure to get the details of a student for the given empno --- create procedure p2(@n int) As

select * 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 emp exec 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) As insert 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) as declare @ n int insert into emp values(@ empno,@ename,@ sal) set @ n=@@ error if @ 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 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 int exec 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 as return <select statement> 1) create a function for the records in emp table. ---- create function f1() returns table as 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 table as return 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.

101 102 103 104 105 106 107

RAM KIRAN KRISHNA _ _ _ _

1000 2000 7000 _ _ _ _

8 kb page 1

8 kb page 2

page 3

page1 -101,102 page2-103,104,105 page 3-106,107

index page

extent: collection of 8 pages in extention sytax: create <index type> index <index name> on <tablename> (column)

Types of indexes: 1) 2) 3) 4) clustered index non-clustered index unique index 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 BTree structure. The information is obtained at leaf node. B-Tree Structure 2 3 2878+9 8474 Intermediate level 4 - A 5 - B 6 - C 7 - D

Root level

leaf level

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.

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.index1 Drop 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

1.Go to query menu.

2.Show execution plan.

3.Select statement

4.In result window,click on the 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)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_cur fetch next from emp_cur close emp_cur deallocate emp_cur

101 102 103 104 105 106 107

RAM

1000

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 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 doesnt 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 insert as --select * from inserted if(select sal from inserted)<2000 Begin print sal must be >2000 Rollback Tran else print 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 deleted if(select count(*) from deleted)>2 Begin print U cannot delete more than two records at a time Rollback Tran else print 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 emp for update as if 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 table sp_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 as exec 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 Name Backup Database-complete Designation

Add Filename ok

ok Select location filename Visix back bak 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 visix Restore from device Restore from disk select Device ADD

Filename

select filename & click ok

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 Jobs Right click & select new job Must be in green colour

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.

change

General

steps

schedules schedules steps Job1 new schedule

Job name

General

Advanced

Job

Step name Database Command Select * from emp

step1 visix

new

Name Recurring

s1

change

select output files & give filename(jobsoutput.txt) click apply & ok

select date & time click apply and ok

DTS 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 database Import/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

Choose a Datasource Datasource Filename select filename M/S Excel 97-2000

Choose a Destination Destination M/S OLE DB provider for SQL Server Server Local Windows Authentication Database Student

next select required sheets next finish Providers Notepad Oracle SQL Server(text file) SQL Server

Choose a Database Data source M/S OLE provider for Oracle properties Choose a Destination Destination M/S OLE DB provider for SQL Server Server Windows authentication local Database student server name Username Test connection 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 cds and floppys. DTS PACKAGE Excel (source) Access(destination) Open enterprise manager Microsoft SQL Servers SQL Server group Local Data transaction sevices Local packages Right click & select new package DTS Package I C X(Excel) O N S Access SQL Server server(destination) .DTS

Destination 2 Server

M/S OLE DB provider for SQL Server Local

Windows Authentication Database Datasource Filename select filename select filename M/S Excel 97-2000 Student

Datasource 1 Filename

M/S Excel 97-2000

4. Go to task menu & select Transform data task (select source & destination icons)

TDT source X Destination Transform

Select table/view 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 cds/floppys go to package menu & click on save as & select the location as structured storage file. Access Oracle excel SQL SERVER 2005(Yukon) start 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) SQL Server

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 1 select tool box & select source and destination icons drop & drop it on the form

1 Flat file source 2 SQL server destination 3 connection a manager b mappings conection manager Name filename Delemeled server new host SQL server authentication login name database click on mappings ok visix sql sa

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 & select manager 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 command sp_grantlogin Linux7\w user system name username

Revoke- Its a permanently removed command. Deny- Its 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

SQL Server Suser SQL Server Authentication Login name Password ok Visix

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.

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