Your SlideShare is downloading. ×
Sql material
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Sql material

3,148
views

Published on

Published in: Technology

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,148
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
459
Comments
0
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Suresh 1 Data: Data is the most important component in any work that we do; Data means collection ofinformation or collection of raw facts.Ex: 1. Text files 2. Facts 3. Figures (photos) 4. Audios 5. Videos etc...Database: collection of related data.DBMS :( Database Management System) Data Base Management System is the management system or maintenance system on databases. (Or) It is a suit of software program for creating, maintaining & manipulating the data in database. (Or) It allows the users to insert the data, to retrieve the data, to modify the data and to delete the data.Properties:1. Create2. Insert3. Update4. Delete5. Select (query)6. Low level security etc...Ex: FoxPro, ims (information management system) The first databases of kind existed in the form of files. A file is nothing but collection of records. A Record is nothing but collection of information or data. But the file system was not very efficient .it was crippled by slow data search speed. It includes the following Drawbacks. 1.Security 2.Data Redundancy 3.Data Integrity 4.Concurrency Control 5.Slow in Process6. File system: in a dbms database, data must be stored in the form of files onlyNote: basic property of file system is independent and individual, means each and every file isunique AND relation is not possible between data files 7. Low level security, No Login name No Password.RDBMS (Relational Database Management System):
  • 2. Suresh 2 • Data must be stored in the form of tables only • Relation between Tables is possibleTable: It is collection of columns and rows, X axis directions are rows and Y axis directions arecolumnsRelation: Creating internal dependencies between Database TablesEx of RDBMS:1. Sqlserver2. Oracle3. Db2 (Database 2000, IBM)4. Mysql (open source)5. ms-access6. Postgresql (open source)7. Sybase8. Tera dataEtc.....Terminology:1. Table -- Entity2. Column (field) -- Attribute3. Row (record) -- Tupple4. Duplicate data (Repeated data) – Data RedundancyMetadata: Data about data, it describes characteristics of dataEx: Description of a tableSyn: sp_help <TN>Ex: sp_help EMPNote: <TN> stands for Table nameData models:1. Hierarchy data model2. Network data model3. Relational data modelNote: Currently all RDBMS Databases following RELATIONAL DATA MODELAdv of Relational Data model: • Relation • Perfect solution for duplicate data and null values • NormalizationNormalization: It is a process of eliminating duplicate data from the database.EF CODD RULES:
  • 3. Suresh 3 Sqlserver 2005:1. It is RDBMS database2. It is a product of Microsoft3. It is case insensitive4. It is platform dependant-- it is compatible for windows OS5. User friendlyHistory: Introduced in 1994 • Sqlserver 4.0 • Sqlserver 5.0 • Sqlserver 6.0 • Sqlserver 6.5 • Sqlserver 7.0 • Sqlserver 8.0(2000) • Sqlserver 9.0(2005) • Sqlserver 10.0(2008)Editions (flavors):1. Enterprise edition2. Standard edition3. Developer edition4. Mobile edition5. Personal edition (express edition)  freeSoftware Requirements:1. OS • Windows xp sp2 or sp3 • Windows server 2000 • Windows server 2003 • Windows server 2008 • Windows Vista • Windows 7
  • 4. Suresh 42. Windows installer: It is a default component of Windows; we can download it fromwww.microsoft.com3. IIS (internet information services): • It is an application server from MICROSOFTHardware requirements:1. Processor:It supports both 32 bit, 64 bitEx: 1. Pentium 4 2. Amd athlon2. Hard disk: • 500 mb (MICROSOFT) • 1 GB (Mine)3. Ram: • 512mb(MICROSOFT) • 1 GB(Mine)SQL -- structured query languageSequel-- structured English query language FEATURES OF SQL SERVER:1. Security: Provides login and password to interact with data in database2. Data Redundancy: Less Data reputation3. Data Integrity: Data validation/Data Checking Process facility4. Backup and Recovery(Restore)5. Introducing support for XML6. User defined function are introduced.7. OLAP (online analytical process) services available in SQL server 7.0 are now called as SQL server 2005 analysis servicesThings to Observe: 1. While writing the Queries using T-SQL in SQL Server Management Studio we need not to follow any particular case. Because T-SQL is case insensitive language. 2. After writing the Query, we need to select that query using either mouse or keyboard. 3. Now Press F5 (Execute Key). 4. Then the results are displayed in a separate window called Result window or Result Pane.
  • 5. Suresh 5 5. Use Ctrl+R to Hide/Show the Result window or Result Pane. 6. Use F8 for Object ExplorerNote: 1. SQL SERVER can handle nearly 32767 Databases 2. Each Database can handle nearly 2 billion Database Objects. 3. Each Table can handle nearly 1024 columns 4. Each Table can handle nearly 1 million Rows  SQLSERVER is two parts, they are 1. Tsql :( Transact sql) 2. Tsql programsTool:1. Management studio: It contains two parts, they are1. Cui (Character user interface): • Sqlscripting can be written in *newqury* option • By using execute button or f5 we can execute the script2. Gui (Graphical user interface): • It is Navigations part of the management Studio. • We can connect to GUI by using *summary* option.Path: start programs sqlserver 2005 Management Studio (click)Inside management studio window provide following information1. Server type-- database engine2. servername-- database server name3. authentication--A. Windows’s authentication • This user must be an OS userB. Sqlserver authenticationUN: sa (sysadmin-- DBA)Pw: ******** (Depends Upon Installation)Databases:1. System databases:
  • 6. Suresh 6 • These are inbuilt or default databases • Along with installation of Sqlserver 2005 we can get system databases • System databases monitors entire database engineNote: User can’t create and delete a system databaseA. masterB. modelC. msdbD. tempdbE. MS resources Descriptionmaster Records all the system-level information for an instance of SQL Server.Databasemsdb It is used by SQL Server Agent for scheduling alerts and jobs.DatabasemodelDatabase Template databaseResource It is a read-only database that contains system objects that are included with SQLDatabase Server 2005. System objects are physically persisted in the Resource database, but they logically appear in the sys schema of every database.tempdb It is a workspace for holding temporary objects or intermediate result sets.Database2. User databases: • These database created and maintained by the users explicitlyEx:CREATE DATABASE sureshON PRIMARY(NAME=suresh,FILENAME="C:MSSQLvaddesuresh.mdf",SIZE=100,MAXSIZE=200,FILEGROWTH=25%)Log on(NAME=suresh_log,FILENAME="C:MSSQLvaddesuresh_log.ldf",SIZE=100,MAXSIZE=200,FILEGROWTH=25%)
  • 7. Suresh 7SQL Server Data Types:Character strings:Data type Description Storagechar(n) Fixed-length character string. Maximum 8,000 characters nvarchar(n) Variable-length character string. Maximum 8,000 charactersvarchar(max) Variable-length character string. Maximum 1,073,741,824 characterstext Variable-length character string. Maximum 2GB of text dataUnicode strings:Data type Description Storagenchar(n) Fixed-length Unicode data. Maximum 4,000 charactersnvarchar(n) Variable-length Unicode data. Maximum 4,000 charactersnvarchar(max) Variable-length Unicode data. Maximum 536,870,912 charactersntext Variable-length Unicode data. Maximum 2GB of text dataBinary types:Data type Description Storagebit Allows 0, 1, or NULLbinary(n) Fixed-length binary data. Maximum 8,000 bytesvarbinary(n) Variable-length binary data. Maximum 8,000 bytesvarbinary(max) Variable-length binary data. Maximum 2GBimage Variable-length binary data. Maximum 2GBNumber types:Data type Description Storagetinyint Allows whole numbers from 0 to 255 1 bytesmallint Allows whole numbers between -32,768 and 32,767 2 bytesint Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytesbigint Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes 9,223,372,036,854,775,807decimal(p,s) Fixed precision and scale numbers. 5-17 bytes Allows numbers from -10^38 +1 to 10^38 –1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to
  • 8. Suresh 8 the right of the decimal point. s must be a value from 0 to p. Default value is 0numeric(p,s) Fixed precision and scale numbers. 5-17 bytes Allows numbers from -10^38 +1 to 10^38 –1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0small money Monetary data from -214,748.3648 to 214,748.3647 4 bytesmoney Monetary data from -922,337,203,685,477.5808 to 8 bytes 922,337,203,685,477.5807float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8 bytes The n parameter indicates whether the field should hold 4 or 8 bytes. Float (24) holds a 4-byte field and float (53) holds an 8-byte field. Default value of n is 53.real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytesDate types:Data type Description Storagedatetime From January 1, 1753 to December 31, 9999 with an accuracy of 8 bytes 3.33 millisecondsdatetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 6-8 bytes 100 nanosecondssmalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytesdate Store a date only. From January 1, 0001 to December 31, 9999 3 bytestime Store a time only to an accuracy of 100 nanoseconds 3-5 bytesdatetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytestimestamp Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variableOther data types:Data type Descriptionsql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestampuniqueidentifier Stores a globally unique identifier (GUID)xml Stores XML formatted data. Maximum 2GBcursor Stores a reference to a cursor used for database operations
  • 9. Suresh 9table Stores a result-set for later processingTSQL: This is a 4th generated intermediate language between user and SQL Server. Wheneveruser wants to interact with SQL Server, he has to interact with SQL Server through T-SQL. Itincludes the following Sub LanguagesSublanguages:1. DDL (data definition language)2. DML (data manipulation language)3. DRL (data retrieval language) or QL (query language)4. TCL (transaction control language)5. DCL (data control language) -- DBA1. DDL:Commands:1. Create2. Truncate3. Drop4. Alter1. Create: used to create database, tables and other database objectssyn: create table <tn>(col1 dt(l),col2 dt(l),col3 dt(l))Ex: create table tab1 (id int, ename varchar (20), DOB datetime)Note: • Max length of a table name and column name is 30; it may include alphabets, digits 0 to 9 and special character _ (Underscore). • It is known as "naming conventions". • Max of 1024 columns can be included into a table.2. Truncate: used to delete entire data from a table and its not possible to delete selected orspecific rows from a table by using truncate command.Ex:Assume that Tab1 is a table, contains 10 rows of data, nowEntire data of Tab1 table= 10rowsSelected or specific data of Tab1 table<entire data1 to 9 rows are known as selected or specific dataSyn: truncate table <TN>Ex: truncate table tab1
  • 10. Suresh 103. Drop: used delete a table from the databaseSyn: drop table <TN>Ex: drop table tab14. Alter:Alter+add: used to add a column to the tableSyn: alter table <TN> add column_name DT (l), column_name DT (l)Ex: alter table tab1 add sal numeric (7, 2), comm Numeric (5, 2), address varchar (50)Alter+drop: used delete columns from the tableSyn: alter table <TN> drop column column_nameEx: alter table tab1 drop column addressAlter+alter: used change the data type and length of data type of a columnNote: Column is empty then only we can change data typeSyn: alter table <TN> alter column column_name DT (l)Ex: alter table tab1 alter column id varchar (20)Miscellaneous:System stored procedures: Directly we can execute them when ever required1. Getting description of a table (metadata)Syn: sp_help <TN>Ex: sp_help tab12. Getting description of a database:Syn: sp_helpdb <dbname>Ex: sp_helpdb Suresh3. Displaying list of tables in a databaseSyn: sp_tablesEx: sp_tables4. Changing name of a table
  • 11. Suresh 11Syn: sp_rename <TN>, <new_name>Ex: sp_rename tab1, employ5. Retrieving list of DatabasesSyn: sp_databasesDML:Commands:1. Insert2. Update3. Delete1. Insert: Used to insert (add) data into tablesSyn: insert into <TN> values (col1, col2, col3)Ex: insert into employ values (a12,ramesh,12-apr-07, 3000, 30) Id name DOB sal commNote: while working with char and date time data we should use single quotesInserting null values into table:Student table contains 5 columns; now insert null value into comm columnEx: insert into employ (id, name, DOB) values (a13,ravi,21-jul-06, 2000)Ex: insert into employ values (a14,ramesh,12-apr-06, 5000, null)2. Update: used to update (replace) old data with new data, it is two types they areA. Updating entire data in a column:Syn: update <TN> set column_name=new_valueEx: update employ set sal=5000B. Updating selected data in a column:Syn: update <TN> set column_name=new_value where <condition>Ex: update employ set sal=3000 where id=a123. Delete: used to delete entire data and selected data from a tableA. Deleting entire data from a table:Syn: delete from <TN>Ex: delete from employ
  • 12. Suresh 12B. Deleting selected data from a table:Syn: delete from <TN> where <condition>Ex: delete from employ where id=a14DRL:Commands:1. Select: used to retrieve or display data from table or tablesNote: Retrieving data from single table is 4 types1. Retrieving entire data (all columns and all rows) from a tableSyn: select*from <TN>Ex: select*from employNote: * stands for entire columns of the table2. Retrieving all columns and selected rows from a tableSyn: select*from <TN> where <condition>Ex: select*from employ where id=a123. Retrieving entire data from selected columnsSyn: select col1, col2 from <TN>Ex: select ename, fees from employ4. Retrieving selected rows from selected columnsSyn: select col1, col2 from <TN> where <condition>Ex: select name, fees from employ where id=a13DCL: It is used to control the data between different user accounts. It includes the followingstatements. 1. GRANT Statement 2. REVOKE StatementGrant Statement: This statement is used to grant the permissions (INSERT, SELECT, UPDATE,DELETE) on a specific table to different user accounts.Syntax:GRANT {ALL/SPECIFIC PERMISSIONS} ON TABLENAME
  • 13. Suresh 13 TO USER ACCOUNT (S) [WITH GRANT OPTION] WITH GRANT OPTION: When any user got the permissions on a specific table from other userwith this option, then that user can grant the permissions on that same table to another useraccount. At that time sub user acts as owner.Ex:GRANT ALL ON EMP TO RAMESH WITH GRANT OPTIONFrom the above statement RAMESH user account got all permissions on EMP table from SA useraccount. Mean time RAMESH can give the permissions on EMP to another user accountbecause he got the permissions WITH GRANT OPTION.Ex:GRANT INSERT, SELECT ON EMP TO SURESHNow SURESH can perform select and insert operations on EMP table.But SURESH cannot perform update and delete operations on EMP table because he does nothave the corresponding permissions.Revoke Statement: This statement is used to revoke the permissions (INSERT, SELECT,UPDATE, DELETE) on a specific table from different user accounts.Syntax:REVOKE {ALL/SPECIFIC PERMISSIONS} ON TABLENAME FROM USER ACCOUNT (S) [CASCADE]CASCADE: Using this option we can destroy the communication link between user accountsmore over from the main user it self we can revoke the permissions from all sub users.Ex:REVOKE ALL ON EMP FROM SUBBU CASCADEThe above statement revokes the permissions on EMP table from SUBBU and SURESH. NowSUBBU and SURESH users cannot access EMP table.TCL:Transaction is nothing but a unit of work. We can control these transactions using the followingstatements ROLLBACK Statement COMMIT Statement SAVE TRAN [SACTION]ROLLBACK Statement: This statement is used to cancel a particular performed transaction. Toperform this statement in SQL Server we have to follow any one of the below 2 approaches.Approach 1: SET IMPLICIT_TRANSATIONS ON
  • 14. Suresh 14This approach is only to cancel a single recently performed operation.Ex:SET IMPLICIT_TRANSATIONS ONSELECT * FROM EMPDELETE FROM EMPSELECT * FROM EMPROLLBACKSELECT * FROM EMPApproach 2: Explicit TransactionsTo approach is to cancel recently performed multiple operations.Syntax: BEGIN TRAN ------------- GO ------------- GO ------------- ROLLBACK TRANNote: GO is query separatorEx:BEGIN TRANINSERT INTO DEPT VALUES (50,’TRA’,’AUS’)GOUPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=11GODELETE FROM STUDENT WHERE SNO=101Select the entire transaction and press F5 for one timeROLLBACK TRANThe ROLLBACK statement cancels INSERT on Dept, UPDATE on EMP and DELETE on Studenttables.COMMIT Statement: This statement makes a transaction permanent. It is not possible to rollbackthe committed transaction.Ex:SELECT * FROM EMPDELETE FROM EMPSELECT * FROM EMPCOMMITSELECT * FROM EMPThe COMMIT statement deletes the data from EMP permanently. It is not possible to ROLLBACKthe delete operation.
  • 15. Suresh 15Ex:BEGIN TRANINSERT INTO DEPT VALUES (50,’TRA’,’AUS’)GOUPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=11GODELETE FROM STUDENT WHERE SNO=101Select the entire transaction and press F5 for one timeCOMMIT TRANThe above COMMIT TRAN makes all three transactions permanent. We cannot ROLLBACK thetransactions.SAVE TRAN Statement: This statement is used to COMMIT/ROLLBACK a particular performedtransaction from the set of transactions. It is associated with alphabets in order to save thetransactions.BEGIN TRANSAVE TRAN AINSERT INTO DEPT VALUES (50,’TRA’,’AUS’)SAVE TRAN BUPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=11SAVE TRAN CDELETE FROM STUDENT WHERE SNO=101ROLLBACK TRAN C (The delete operation will be cancelled)COMMIT TRAN B (The update operation performed permanently we cannot rollback)TABLES FOR PRACTICALS:1.CREATE TABLE EMP (EMPNO NUMERIC(4) NOT NULL, ENAME VARCHAR(10), JOB VARCHAR(9), MGR NUMERIC(4), HIREDATE DATETIME, SAL NUMERIC(7, 2), COMM NUMERIC(7, 2), DEPTNO NUMERIC(2));
  • 16. Suresh 16DATA:INSERT INTO EMP VALUES (7369, SMITH, CLERK,7902,17-DEC-1980, 800, NULL, 20);INSERT INTO EMP VALUES (7499, ALLEN, SALESMAN,7698,20-FEB-1981, 1600, 300, 30);INSERT INTO EMP VALUES (7521, WARD, SALESMAN,7698,22-FEB-1981, 1250, 500, 30);INSERT INTO EMP VALUES (7566, JONES, MANAGER,7839,2-APR-1981, 2975, NULL, 20);INSERT INTO EMP VALUES (7654, MARTIN, SALESMAN,7698,28-SEP-1981, 1250, 1400, 30);INSERT INTO EMP VALUES (7698, BLAKE, MANAGER,7839,1-MAY-1981, 2850, NULL, 30);INSERT INTO EMP VALUES (7782, CLARK, MANAGER,7839,9-JUN-1981, 2450, NULL, 10);INSERT INTO EMP VALUES (7788, SCOTT, ANALYST,7566,09-DEC-1982, 3000, NULL, 20);INSERT INTO EMP VALUES (7839, KING, PRESIDENT,NULL,17-NOV-1981, 5000, NULL, 10);INSERT INTO EMP VALUES
  • 17. Suresh 17 (7844, TURNER, SALESMAN,7698,8-SEP-1981,1500, 0, 30);INSERT INTO EMP VALUES (7876, ADAMS, CLERK,7788,12-JAN-1983, 1100, NULL, 20);INSERT INTO EMP VALUES (7900, JAMES, CLERK,7698,3-DEC-1981, 950, NULL, 30);INSERT INTO EMP VALUES (7902, FORD, ANALYST,7566,3-DEC-1981, 3000, NULL, 20);INSERT INTO EMP VALUES (7934, MILLER, CLERK,7782,23-JAN-1982, 1300, NULL, 10);2.CREATE TABLE DEPT (DEPTNO NUMERIC(2), DNAME VARCHAR(14), LOC VARCHAR(13) );DATA:INSERT INTO DEPT VALUES (10,ACCOUNTING, NEW YORK);INSERT INTO DEPT VALUES (20, RESEARCH,DALLAS);INSERT INTO DEPT VALUES (30,SALES, CHICAGO);INSERT INTO DEPT VALUES (40,OPERATIONS, BOSTON);3.CREATE TABLE SALGRADE
  • 18. Suresh 18 (GRADE NUMERIC, LOSAL NUMERIC, HISAL NUMERIC);DATA:INSERT INTO SALGRADE VALUES (1, 700,1200);INSERT INTO SALGRADE VALUES (2, 1201,1400);INSERT INTO SALGRADE VALUES (3, 1401,2000);INSERT INTO SALGRADE VALUES (4, 2001,3000);INSERT INTO SALGRADE VALUES (5, 3001,9999);Operators:1. Arithmetic operators: +, -,*, /1. +:Select sal, sal+1000 from EMP2.-:Select sal, sal-100 from EMP3.*:Select sal, sal*12 from EMP4. /:Select sal, sal/2 from EMP2. Assignment operator’s :( relational operators)=, <> or ! =,>,>=,<,<=
  • 19. Suresh 191. =:Select*from EMP where deptno=202. <> or! =:Select*from EMP where deptno<>203.>:Select*from EMP where sal>30004.>=:Select*from EMP where sal>=30005. <:Select*from EMP where sal<30006. <=:Select*from EMP where sal<=30003. Logical operators: and, or, notEx: in maths two conditions are there, condition A and condition BA and B-- both conditions must be satisfiedA or B-- if anyone satisfied then we can get output1. And:Select*from EMP where sal>3000 and deptno=202. Or:Select*from EMP where sal>3000 or deptno=20Between operator :( Range operator)Ex: select*from EMP where sal between 2000 and 5000Not between:Ex: select*from EMP where sal not between 2000 and 5000In operator :( Minimizes searching time)Select*from EMP where ename in (Scott, Turner’, ‘Suresh)Not in:
  • 20. Suresh 20Select*from EMP where ename not in (scott,turner,suresh)Like operator :( Pattern matching)Ex: select*from EMP where ename like’s%S%-- ename starts with s%s-- ename ends with s%s%-- somewhere s in ename_s%-- second character is s from beginning%s_ -- second from ending is s in enameNote: _ (underscore) denotes one characterNot like operator:Select*from EMP where ename not like’s%Alias: • Second or duplicate name, can be assigned to a table or column • Alias is temporaryEx: • Select sal*12 from EMP • Select sal*12 annual Sal from EMPNote: annual Sal is alias for sal*12Inbuilt functions:1. Aggregate functions :( Group functions)1. Sum ():Select sum (sal) from EMP2. Average ():Select avg (sal) from EMP3. Max ():Select max (sal) from EMP4. Min ():Select min (sal) from EMP5. Count (): it counts number of rows
  • 21. Suresh 21Select count (*) from EMPSelect count (ename) from EMPSelect count (comm) from EMPNote: 1. Count Function doesn’t consider null as a value. 2. COUNT function does not count the rows of the column whose data type is BIGINT, In such situations we have to use COUNT_BIG function6. Standard deviation ():Select stdev (sal) from EMP7. Variance ():Select var (sal) from EMP DISTINCT ( ): This function displays the different values available for a specific column. It considers one NULL value. Ex: SELECT DISTINCT (DEPTNO) AS DIFF_VALUES FROM EMP DIFF_VALUES 10 20 Ex: SELECT COUNT (DISTINCT( DEPTNO)) AS NO_OF_ROWS FROM EMP NO_OF_ROWS 22. Numeric functions:1. Absolute:Select abs (-9.5)O/p: 9.52. Ceiling:Select ceiling (9.01)O/p: 103. Floor:Select floor (9.9)O/p: 9
  • 22. Suresh 224. Square root:Select sqrt (144)O/p: 125. Power:Select power (3, 3)O/p: 27(3*3*3)6. Square:Select square (3)O/p: 9(3*3)7. Pi ():Select pi ()O/p: 3.14(22/7)8. Log:Select log (2)O/p: 0.6931471805599459. Exp:Select exp (2)O/p: 7.38905609893065 10. ROUND (M, N): IT WILL ROUND THE VALUE OF M TO NEAREST WHOLE NUMBER OF IT WILL AROUND.  SELECT ROUND (15.143) 15  SELECT ROUND (16.513) 16  SELECT ROUND (16.816) 17  SELECT ROUND (21.132,1) 21.1  SELECT ROUND (25.143)
  • 23. Suresh 23 253. Character functions :( String functions)1. Length:Select Len (Hyderabad)O/p: 92. Upper:Select upper (Hyderabad)O/p: HYDERABAD3. Lower:Select lower (HYDERABAD)O/P: hyderabad4. Reverse:Select reverse (Malayalam)O/p: MalayalamSelect reverse (school)O/p: loohcs5. Replace:Select replace (hyderabad,hyd,cyb)O/p: cyberabad6. Substring:Select substring (hyderabad, 3, 5)O/p: derab7. ASCII (Character): It gives ASCII value of a characterSelect ASCII (‘A’)O/p: 65Select ASCII (‘a’)O/p: 978. Char (n): It gives character for given ASCII value
  • 24. Suresh 24Select char (98)O/p: bDate time functions:1. Getdate ():Select getdate ()O/p: 2009-07-17 18:11:20.0002. Getutcdate ():Select getutcdate ()O/p: 2009-07-17 12:42:09.2633. Dateadd:Select dateadd (dd, 7, getdate ())O/p: 2010-04-27 15:24:15.8274. Datediff:Select datediff (mm,03/26/04, getdate ())O/p: 735. Date part:Select datepart (yy, getdate ())O/p: 2010Select datepart (mm, getdate ())O/p: 4Select datepart (dd, getdate ())O/p: 206. Date name:Select datename (DW, getdate ())O/p: TuesdaySet operators:a= {1, 2, 3}b= {3, 4, 5}
  • 25. Suresh 251. A union B= {1, 2, 3, 4, 5}2. A union all B= {1, 2, 3, 3, 4, 5}Note: union all retrieves duplicate data3. A intersect B= {3}4. A except B = A minus B= {1, 2}1. Union:SELECT EMPNO FROM EMPUNIONSELECT DEPTNO FROM DEPT2. Union all:SELECT EMPNO FROM EMPUNION ALLSELECT DEPTNO FROM DEPT3. Intersect:SELECT EMPNO FROM EMPINTERSECTSELECT DEPTNO FROM DEPT4. Except:SELECT EMPNO FROM EMPEXCEPTSELECT DEPTNO FROM DEPTGroup by clause: • Used to group similar data in the output • Conjunction of the similar data • Used to divide the table into number of subgroups based on a specific column. • Minimum single group or aggregate function is mandatory • If column contains similar data then only we can use it into group by clause  Display the number of employee working in different jobs of EMP tableEx: Select job, count (job) from EMP Group by job  Display max and min salaries of employees who are working in different deptnos of EMP table
  • 26. Suresh 26Ex: Select deptno, max (sal), min (sal) from EMP Group by (deptno)Ex: SELECT DEPTNO, MAX (SAL) AS HISAL, MIN (SAL) AS LOSAL, SUM (SAL) AS TOTSAL,AVG (SAL) AS AVGSAL FROM EMPGROUP BY DEPTNOHaving clause: • It is an arithmetical expression • It can be used as an extension of group by clause and we can’t use where clause after group by clause • This clause is used to evaluate a condition with group by clause. Generally for evaluating conditions we will use WHERE clause, but where clause does not support by group by clause.Ex: Select job, count (deptno) from EMP Group by job Having count (deptno)>2Ex: SELECT DEPTNO, MAX (SAL) AS HISAL, MIN (SAL) AS LOSAL,SUM (SAL) AS TOTSAL, AVG (SAL) AS AVGSAL FROM EMPGROUP BY DEPTNO HAVING AVG (SAL)>10000Order by clause: • It is temporary sorting of the data either in ascending order or in Descending order • Default is ascending orderAscending:Ex: Select*from EMP order by salDescending:Ex: Select*from EMP order by sal descClause precedence:1. Where clause2. Group by clause3. Having clause4. order by clauseJoins:
  • 27. Suresh 27 • Used to retrieve data from multiple tables • Joins plays major role in performance tuning • Joins comes under temporary relations • We need a common column or common data column in multiple tables • Two tables are there, they are EMP and DEPT am creating joins between them • Both tables contains a common column i.e. deptno, so that we can create Joins between EMP, DEPT tables • Formula: no. of joins=no. of tables-1Types of JOINS:1. Inner join :( Equi join)We are retrieving data from EMP, DEPT tablesEx:Select empno, ename, sal, d.deptno, dname, loc from EMP eInner join DEPT d on e.deptno=d.deptnoNote: Query retrieves equal number of rows from both tables2. Outer join: This is three types1. Left outer join:Select empno, ename, sal, d.deptno, dname, loc from EMP eLeft outer join DEPT d on e.deptno=d.deptnoIt retrieves condition satisfies and non satisfied data from left side table of the condition i.e. EMP,it retrieves only condition satisfied data from right side table of the condition i.e. DEPT2. Right outer join:Select empno, ename, sal, d.deptno, dname, loc from EMP eRight outer join DEPT d on e.deptno=d.deptnoIt retrieves condition satisfied from left side table of the condition i.e. EMP, it retrieves conditionsatisfied data and non satisfied data from right side table of the condition i.e. DEPT3. Full outer join:This is combination of both right and left outer joins.Select empno, ename, sal, d.deptno, dname, loc from EMP eFull outer join DEPT d on e.deptno=d.deptnoIt retrieves condition satisfied and non satisfied data from both tables.
  • 28. Suresh 283. Non-equi join: EMP table contains a column sal, in SALGRADE table, we got two columnslosal and hisal so that we can define a join condition.Select empno, ename, sal, grade from EMP e, SALGRADE s wheree.sal between s.losal and s.hisalBy using above query we can map employees and their grades.4. Cross join :( Cartesian product)a= (1, 2, 3)b= (4, 5, 6)A*B=3*3=9EMP table contains 14 rowsDept table contains 4 rowsCross join of EMP, DEPT tables produces 56 rowsEx:Select*from EMP cross join DEPT Creating a table by copying data and structure from another table:Syn:Select*into <TN> from <existing_table>Ex:Select*into EMP1 from EMPEx: (Oracle)Create table EMP1 as select*from EMP; Creating a table by copying sturucture from another table: In this by defining false condition we can avoid copying of data.Syn:Select*into <TN> from <existing_tabel> where <false_condition>Ex:Select*into EMP2 from EMP where 1=2SUB-QUERIES:
  • 29. Suresh 29 • It is a Combination of multiple queries or select statements. • Query with in a query is known as Sub-QuerySyn:Select statement (Select statement) Outer query inner queryTypes:1. Simple or single row sub query: • It returns only single row to the userEx: Retrieve second highest sal from EMP tableSelect max (sal) from EMP where sal< (select max (sal) from EMP)2. Nested sub query: • It is also simple sub query • It returns single rowEx: Retrieve third highest sal from EMP tableSelect max (sal) from EMP where sal< (select max (sal) from EMP whereSal< (select max (sal) from EMP))Distinct: It eliminates duplications temporarily.Ex: A. Select sal from EMP B. Select distinct (sal) from EMP  Formula for retrieving n highest salaries from EMP table: Select max (sal) from EMP e where n= (select count (distinct (sal)) from EMP b where e.sal<b.sal)  N is a number which indicates position of the sal
  • 30. Suresh 30  N starts from zero  n=n-1  Formula for Min sal: Select min (sal) from EMP e where n= (select count (distinct (sal)) fromEMP b where e.sal>b.sal)3. Co-related sub query:  It can return single and multiple rows to the userI want to retrieve deptno 20 data from EMP table, for that I want Satisfy the condition in dept tableEx:Select*from EMP where deptno= (select deptno from DEPT where dname=accounting) Note: If a sub query sends multiple values to its nearest main query then we have to use IN operator between Main query and Sub query. Ex: WAQ to display employee details, who are working under RAM dept. SELECT * FROM EMP WHERE DEPTNO= (SELECT DEPTNO FROM EMP WHERE ENAME=’RAM’) Ex: WAQ To display employee details, whose salary is greater than highest salary of 10th department SELECT * FROM EMP WHERE SAL> (SELECT MAX (SAL) FROM EMP WHERE DEPTNO=10) Ex: WAQ To display employee details, whose salary is greater than average salary of RAM department SELECT * FROM EMP WHERE SAL> (SELECT AVG (SAL) FROM EMP WHERE DEPTNO= SELECT DEPTNO FROM EMP WHERE ENAME=’RAM’)Constraints:  Set of rules which are used to improve functionality of tables  These are inbuilt rules  We can impose constraints on columnsAdv:1. Creating permanent relations between tables2. We can avoid duplications and null values
  • 31. Suresh 313. We can create permanent conditionsNote: We can create a constraint along with table creation this is of two types:1. Column level Constraint: It can be created on single column2. Table level Constraint: It can be created on multiple columnsNote: We can add a constraint to the existing tableTypes:1. Primary key2. Unique constraint3. Check constraint4. Not null5. Foreign key (Referential integrity)1. Primary key:Properties: • It is unique • It is not null  Column level Primary Key:Syn: create table <TN> (col1 DT (l) constraint con_name primary key, col2 DT (l), col3 DT (l))Ex: create table t1 (id int constraint p_key primary key, name varchar (20), DOB datetime) • In this we can create a constraint on single column only  Table level Primary key:syn: create table <tn>(col1 dt(l),col2 dt(l),col3 dt(l), constraint con_name primary key(col1,col2))Ex: create table t2 (id int, name varchar (20), DOB datetime, constraint p_key3 primary key (id,name)) • We can create single constraint on multiple columns • Max of single primary key can be created on a table • If single primary key is working on multiple columns then it is known as "composite primary key"2. Unique constraint:Properties:
  • 32. Suresh 32 • Unique • It accepts single null valueSyn: create table <TN> (col1 DT (l) constraint con_name unique, col2 DT (l), col3 DT (l))Ex: create table t3 (id int constraint u_con unique, dname varchar (20), loc varchar (20))3. Check constraint: used to impose permanent conditions on columnsSyn: create table <tn>(col1 dt(l),col2 dt(l) constraint con_name check(condition),col3 dt(l))Ex: create table t4 (id int, sal numeric (7, 2) constraint check_con check (sal>3000), commissionnumeric (5, 2))4. Not null: it doesn’t accept null valuesSyn: create table <TN> (col1 DT (l) constraint con_name not null)Ex: create table t5 (id int constraint n_null not null)5. Foreign key: • It always references values from either primary key or unique constraint and there are no properties for foreign key. • It also known as referential integrity • This reference will be stored into database permanently, so that • It is comes under permanent relation • Generally primary key and foreign are a part of different tables • Primary key table is known as parent or master table • Foreign key table is known as child or detail table • We can create primary key and foreign key in single table, that is known as "self referential integrity"Note: 1. Primary key and foreign key columns data types must be same. 2. If the value existing in primary key then only we can insert same value into foreign key. 3. Foreign key accepts null values when it is referencing from unique constraintsyn: create table <tn>(col1 dt(l),col2 dt(l),col3 dt(l), constraint con_name foreignkey(col1)references <tn2>(col1))
  • 33. Suresh 33Ex: create table t6 (id int, address varchar (50), job varchar (20), constraint f_key foreign key (id)references t1 (id))Adding constraint to a table:Syn: alter table <TN> add constraint con_name type_constraint (col_list)Ex: alter table t2 add constraint p_key3 primary key (id)Dropping constraint:Syn: alter table <TN> drop constraint con_nameEx: alter table t2 drop constraint p_key3Information regarding constraints of a table:Syn: sp_helpconstraint <TN>Ex: sp_helpconstraint t1Normalization:Normalization is process of splitting the base table into multiple tables based on the theory ofFunctional Dependency. ORNormalization is repetitive process in order to identify the functional dependencies among thecolumns and to remove them. If any functional dependency is occurred after the normalizationprocess again we have to start the same process until all functional dependencies have beenremoved.To do this Normalization we have to follow rules or conditions called Normal Forms.Un-Normalized TableEMPNO PROJNO ENAME PNAME SAL BUD DEPTNO DNAME LOC11 (P1, P2) ---- (Pn1, Pn2) ----- ----- 10 -------- -----22 (P2, P3) ---- (Pn2, Pn3) ----- ----- 10 -------- -----33 (P1, P3) ---- (Pn1, Pn3) ----- ----- 20 -------- -----EMPNO and PROJNO are Primary Keys called ‘COMPOSITE PRIMARY KEY’FIRST NORMAL FORM (1NF): According to first normal form table should contain only singlevalues columns. But in the above un-normalized table the columns PROJNO and PNAMEcontains multiple values.
  • 34. Suresh 34To make the table into first normal form we should have to split the multiple values into singlevalues.EMPNO PROJNO ENAME PNAME SAL BUD DEPTNO DNAME LOC11 P1 ---- Pn1 ----- ----- 10 -------- -----11 P2 ---- Pn2 ----- ----- 10 -------- -----22 P2 ---- Pn2 ----- ----- 10 -------- -----22 P3 ---- Pn3 ----- ----- 10 -------- -----33 P1 ---- Pn1 ----- ----- 20 -------- -----33 P3 ---- Pn3 ----- ----- 20 -------- -----SECOND NORMAL FORM (2NF):According to second normal form table should be in 1NF and we should have to remove PartialFunctional Dependency.In the above table DEPTNO non-key column dependent part of the Primary key column i.e.EMPNO. It means there existed Partial functional dependency.To make the table into second normal form we have to divide the table into multiple tables.PROJ-INFOPROJNO PNAME BUD P1 Pn1 ------ P2 Pn2 ------ P3 Pn3 ------EMP-INFOEMPNO ENAME SAL DEPTNO DNAME LOC11 ---- ---- 10 ------ -----22 ---- ---- 10 ------ -----33 ---- ---- 20 ------ -----THIRD NORMAL FORM (3NF):According to second normal form table should be in 2NF and we should have to removeTransitive Functional Dependency.In the above EMP-INFO table non-key column DNAME dependent part on the other non- keycolumn i.e.DEPTNO. It means there existed Transitive functional dependency.To make the table into third normal form we have to divide the table into multiple tables.
  • 35. Suresh 35PROJ-INFOPROJNO PNAME BUD P1 Pn1 ------ P2 Pn2 ------ P3 Pn3 ------EMP-INFO DEPT-INFOEMPNO ENAME SAL DEPTNO DNAME LOC11 ---- ---- 10 ------ -----22 ---- ---- 20 ------ -----33 ---- ----Views:A View is nothing but an image table or virtual table, which is created for a base table. A view canbe created by taking all values from the base table or by taking only selected values from basetable. There are two types’ views available in SQL Server. 1. Simple Views 2. Complex ViewsNote: If we perform any modifications in base table, then those modifications automaticallyeffected in view and vice-versa.1. Simple Views: Creating View by taking only one single base table.Syntax:CREATE VIEW VIEWNAME [WITH ENCRYPTION]AS SELECT * FROM TABLENAME [WHERE CONDITION] [WITH CHECK OPTION]Ex:CREATE VIEW V1 AS SELECT * FROM EMPINSERT INTO V1 VALUES (55,’RAVI’, 10000, 10)The above insert statement inserts the values into base table EMP as well as into view V1.Ex:CREATE VIEW V2 AS SELECT * FROM EMP WHERE DEPTNO=10INSERT INTO V2 VALUES (66,’BABBU’, 25000, 10)The above insert statement inserts the values into base table EMP as well as into viewV2.
  • 36. Suresh 36INSERT INTO V2 VALUES (77,’AMAR’, 15000, 20)The above insert statement inserts the values into only base table EMP but not into viewV2 because according to the definition of V2 user supplied values are invalid values. It meansinvalid values are inserting into base table EMP. To stop this kind of operations we have to createthe view with ‘WITH CHECK OPTION’.Ex:CREATE VIEW V3 AS SELECT * FROM EMP WHERE DEPTNO=10 WITH CHECK OPTIONINSERT INTO V3 VALUES (88,’TEJA’, 25000, 20)The above insert statement cannot insert the values into base table EMP as well as into view V3.SP_HELPTEXT: This stored procedure is used to display the definition of a specific view.Syntax:SP_HELPTEXT VIEWNAMEEx: SP_HELPTEXT V1Output: CREATE VIEW V1 AS SELECT * FROM EMPWITH ENCRYPTION: Once we create any view with ‘WITH ENCRYPTION’ then we cannot findthe definition of that particular view using SP_HELPTEXT stored procedure because thisencryption option hides the definition.Ex:CREATE VIEW V4 WITH ENCRYPTIONAS SELECT * FROM EMP WHERE DEPTNO=20SP_HELPTEXT V4Output: The text for object v4 is encryptedTo decrypt the definition of view V4 we have to follow the below approach 1. Replace CREATE with ALTER 2. Remove WITH ENCRYPTION keywordEx:ALTER VIEW V4 AS SELECT * FROM EMP WHERE DEPTNO=20SP_HELPTEXT V4CREATE VIEW V4 AS SELECT * FROM EMP WHERE DEPTNO=202. Complex Views:
  • 37. Suresh 37Creating View by taking multiple base tables.Ex:CREATE VIEW EMP_DEPT_VIEW AS SELECT EMP.EMPNO, EMP.ENAME, DEPT.DEPTNO,DEPT.DNAME FROM EMP, DEPT WHERE EMP.DEPTNO=DEPT.DEPTNOSyntax to create view based on another views:SQL SERVER enables users to create views based on another view. We can create view basedon another view up to 32 levelsSyntax:CREATE VIEW VIEWNAME [WITH ENCRYPTION] AS SELECT * FROM VIEWNAME [WHERECONDITION] [WITH CHECK OPTION]Ex:CREATE VIEW V5 AS SELECT * FROM V1 WHERE DEPTNO=10Syntax to Drop the Views:DROP VIEW VIEWNAME […N]Ex: DROP VIEW V1, V2, V3, V4, V5Indexes: Indexes in SQL server is similar to index in text book... Indexes are used to improve the performance of queries. • INDEXES ARE GENERALLY CREATED FOR FOLLOWING COLUMNS 1. Primary key column 2. Foreign key column: frequently used in join conditions. 3. Column which are frequently used in where clause 4. Columns, which are used to retrieve the data in sorting order. • INDEXED CANNOT BE CREATED FOR FOLLOWING COLUMNS 1. The columns which are not used frequently used in where clause. 2. Columns containing the duplicate and null values 3. Columns containing images, binary information, and text information. TYPES OF INDEXES: • CLUSTERED INDEX • NON-CLUSTERED INDEX CLUSTERED INDEX: only one clustered index is allowed per table. The order of values in a table order of values in index is also same. When cluster index is created on table data is arranged in ascending order cluster index will occupy 5% of the table.
  • 38. Suresh 38 Syntax: CREATE [UNIQUE] CLUSTERED INDEX INDEXNAME ON TABLENAME (COLUMN) Ex: CREATE CLUSTERED INDEX CI ON EMP (EMPNO) Note: If we want to maintain unique values in clustered/non clustered indexed column then specify UNIQUE keyword along with CLUSTERED INDEX/NONCLUSTERD INDEX NONCLUSTERED INDEX: It is the default index created by the server the physical order of the data in the table is different from the order of the values in index. Max no. Of non- clustered indexed allowed for table is 249 Syntax: CREATE [UNIQUE] NONCLUSTERED INDEX INDEXNAME ON TABLENAME (COLUMN1…) Ex: CREATE NONCLUSTERED INDEX NCI ON EMP (ENAME, SAL) Ex: CREATE UNIQUE NONCLUSTERED INDEX UI ON DEPT (DNAME) COMPOSITE INDEX: If a Unique NonClustered index is created on more than one column then that concept is called composite index.CREATE UNIQUE NONCLUSTERED INDEX COI ON DEPT (DEPTNO, DNAME)DEPTNO DNAME 10 SALES 20 HR 30 IR 10 HR (Accepted) 20 SALES (Accepted) 30 IR (Repeated, Not accepted)SP_HELPINDEX: This stored procedure is used to display the list of indexes, which have beenplaced on different columns of a specific table.Ex: SP_HELPINDEX EMPSyntax to drop the index:DROP INDEX TABLENAME.INDEXNAMEEx:DROP INDEX DEPT.UISynonym:
  • 39. Suresh 39 • It is a database object • It is a second or duplicate name which can be assigned to a table • It will not occupies any space, just it is a second name of the table • Trough synonyms we can impose securities i.e. we can hide actual table namesSyn: create synonym syn_name for <TN>Ex: create synonym syn_1 for EMPRetrieving data:Syn: select*from syn_nameEx: select*from syn_1Dropping:Syn: drop synonym <TN>Ex: drop synonym syn_1RULES AND DEFAULTS: CREATING DEFAULT: Default is one of the database objects used to declare default values globally. Syntax: CREATE DEFAULT DEFAULTNAME AS NUMERICVALUE/STRING VALUE Ex: CREATE DEFAULT D1 AS ‘UNKNOWN’ BINDING THE DEFAULT TO COLUMN: Syntax: SP_BINDDEFAULT DEFAULTNAME, ‘TABLENAME.COLUMN’ Ex: SP_BINDDEFAULT D1, ‘DEPT.LOC’ SP_BINDEFAULT D1, ‘EMP.ENAME’ INSERT INTO DEPT (DEPTNO, DNAME) VALUES (10,ACCOUNTING’) SELECT * FROM DEPT WHERE DEPTNO =10 DEPTNO DNAME LOC 10 ACCOUNTING UNKNOWN INSERT INTO EMP (EMPNO, SAL, DEPTNO) VALUES (100, 5000,20) SELECT EMPNO, ENAME, DEPTNO FROM EMP WHERE EMPNO =100
  • 40. Suresh 40 EMPNO ENAME DEPTNO 100 UNKNOWN 20 UNBINDING THE DEFAULT FROM THE BINDING COLUMN: Syntax: SP_UNBINDEFAULT ‘TABLENAME...COLUMN’ SP_UNBINDEFAULT ‘ DEPT.LOC’ SP_UNBINDEFAULT ‘ EMP.ENAME’ DROPPING THE DEFAULT: Syntax: DROP DEFAULT DEFAULTNAME DROP DEFAULT D1 CREATING RULES: Rule is just check constraint but it is placed on columns globally. Syntax: CREATE RULE RULENAME AS EXPRESSION Ex: CREATE RULE R1 AS @ X >=10 AND @ X <= 60 BINDING THE RULE: SP_BINDEFAULT RULENAME, ‘ TABLE.COLUMN’ SP_BINDEFAULT R1, ‘DEPT.DEPTNO’ INSERT INTO DEPT (DEPTNO) VALUES (70) ERROR UNBINDING THE RULES: SP_UNBIND RULE ‘DEPT.DEPTNO’ DROPPING THE RULES:
  • 41. Suresh 41 DROP RULE RULENAME DROP RULE R1TSQL Programs:Variable: whose can be varied is known as a variableTypes:1. Local variable: once we declared local variable then it can be used into single programEx: @x int2. Global variable: once we declared global variable then it can be used into many no. ofprogramsEx: @@y intConstant: whose value can’t be variedEx: 1, 2,3,4,5Note: tsql programs also known as tsql batches, these are two types1. Named batches2. Unnamed batchesStructure:DeclareDeclaration and initiation of variablesBeginBody of the programEnd1. Declare: User can declare variables according to the requirement of the batch and can assign initialvalues to variablesEx: declare @x int Set @x=102. Begin:It contains actual code i.e.Logic
  • 42. Suresh 42ExceptionsConditional statementsOutputOutput: print output3. End: Ending of the batch  WAP to display the word welcome to databaseBeginPrint welcome to databaseEnd  WAP to calculate sum of two numbersDeclare @x intSet @x=20Declare @y intSet @y=10Declare @z intBeginSet @z=@x+@yPrint @zEndConditional Statements:1. If. Else:Syn:DeclareVariable declaration and initiationBeginIf conditionOutputElseOutputEnd  WAP to find out greatest number among two numbersDeclare @x int Set @x=20Declare @y int Set @y=10BeginIf @x>@yPrint x is greatestElsePrint y is greatestEnd
  • 43. Suresh 432. If. Elseif... Else:Syn:DeclareVariable declaration and initiationBeginIf conditionOutputElse if conditionOutputElseOutputEnd  WAP to find out greatest number among three numbersDeclare @x intSet @x=20Declare @y intSet @y=10Declare @z intSet @z=5BeginIf @x>@y and @x>@zPrint x is greatestElse if @y>@x and @y>@zPrint y is greatestElsePrint z is greatestEnd3. While:Syn:DeclareVariable declaration and initiationWhile conditionBeginBody of the programEnd  WAP to display numbers from 1 to 10 with increment of 1DECLARE @counter INTSET @counter=1WHILE @counter <= 10BEGINPRINT @counterSET @counter=@counter+1ENDCursors:
  • 44. Suresh 44Cursor is a logical area, which is used to retrieve a particular nth record. Selecting a particular nthrecord is not possible through physical area (Table). In such situations one logical area (Cursor)we can create and then we can select a particular nth record. Cursors are used to storetransaction information temporarily.Types of Cursors: 1. STATIC CURSOR 2. DYNAMIC CURSOR 3. KEYSET CURSOR 4. FORWARD_ONLY CURSORDEPT_TABLE:DEPTNO DNAME LOC10 SALES HYD20 HR CHE30 IR BAN40 A/C MUMSyntax:Syntax to declare the Cursor:DECLARE CURSORNAME CURSOR CURSORTYPE FOR SELECT * FROM TABLENAMESyntax to open the Cursor:OPEN CURSORNAMESyntax to fetch the records from Cursor:FETCH {FIRST/NEXT/PRIOR/LAST/ABSOLUTE N/RELATIVE N} FROM CURSORNAMESyntax to close the Cursor:CLOSE CURSORNAMESyntax to de allocates the Cursor:DEALLOCATE CURSORNAMEFIRST: Fetches first record from the cursorNEXT: Fetches next record from the current position of the cursorPRIOR: Fetches previous record from the current position of the cursorLAST: Fetches last record from the cursorABSOLUTE N: Fetches nth record from the top of the cursor if n is positive fetches the nth recordfrom bottom of the cursor if n is negative. Where n is an integer
  • 45. Suresh 45RELATIVE N: Fetches nth next record from current position of the cursor if n is positive fetchesnth previous record from the current position of the cursor if n is negative where n is an integer.1. STATIC CURSOR:This is the logical area in which dynamic updations not possible. If we want those updations inlogical area we close the cursor and we need to reopen it.1.DECLARE SC CURSOR STATIC FOR SELECT * FROM DEPTOPEN SCFETCH FIRST FROM SC10 SALES HYDUPDATE DEPT SET DEPTNO=15 WHERE DEPTNO=10FETCH FIRST FROM SC10 SALES HYDCLOSE SCOPEN SCFETCH FIRST FROM SC15 SALES HYDFETCH NEXT FROM SC20 HR CHEFETCH PRIOR FROM SC15 SALES HYDFETCH LAST FROMSC40 A/C MUMFETCH ABSOLUTE 2 FROM SC20 HR CHEFETCH ABSOLUTE –2 FROM SC30 IR BANFETCH FIRST FROM SC15 SALES HYDFETCH RELATIVE 2 FROM SC30 IR BANFETCH RELATIVE –2 FROM SC15 SALES HYDCLOSE SCDEALLOCATE SC2. DYNAMIC CURSOR:
  • 46. Suresh 46This is the logical area in which dynamic updations possible. We need to close and reopen thecursor for the modified valuesEx:DECLARE DC CURSOR DYNAMIC FOR SELECT * FROM DEPTOPEN SCFETCH FIRST FROM DC15 SALES HYDUPDATE DEPT SET DEPTNO=10 WHERE DEPTNO=15FETCH FIRST FROM DC10 SALES HYDCLOSE DCDEALLOCATE DCNote: ABSOLUTE N will not be supported by the dynamic cursor because dynamic updations arepossible.3. KEYSET CURSOR:This is the logical area, which is useful only when there is a primary key in the table. This logicalarea holds only Primary key column values. Based on the key column values in the logical area(Cursor) the rest column values are coming from physical area (Table).Ex:DECLARE KC CURSOR KEYSET FOR SELECT * FROM DEPTOPEN KCFETCH FIRST FROM KC10 SALES HYDUPDATE DEPT SET LOC=’SRNAGAR’ WHERE LOC=’HYD’FETCH FIRST FROM KC10 SALES SRNAGARUPDATE DEPT SET DEPTNO=15 WHERE DEPTNO=10FETCH FIRST FROM KC0 NULL NULLCLOSE KCOPEN KCFETCH FIRST FROM KC15 SALES HYDCLOSE KCDEALLOCATE KC
  • 47. Suresh 47Note: Dynamic updations are not possible on key column of the keyset cursor, we have to closethe cursor and we need to reopen it for the modified values.4. FORWARD_ONLY CURSOR:This is the most unused logical area because it supports only NEXT operation.Ex:DECLARE FC CURSOR FORWARD_ONLY FOR SELECT * FROM DEPTOPEN FCFETCH FIRST FROM FCError MessageFETCH NEXT FROM FC15 SALES HYDCLOSE SCDEALLOCATE FCNOTE:If the cursor does not found any value in its searching process then it will display thecorresponding column values.1. BATCH TO FETCH MULTIPLE RECORDS FROM STATIC CURSORStep1: DECLARE SC CURSOR STATIC FOR SELECT * FROM DEPTStep2: DECLARE @N INT OPEN SC SET @N=2 WHILE (@N<=4) BEGIN FETCH ABSOLUTE @N FROM SC SET @N=@N+1 ENDStep3: CLOSE SC DEALLOCATE SCOUTPUT:DEPTNO DNAME LOC20 HR CHEDEPTNO DNAME LOC30 IR BAN
  • 48. Suresh 48DEPTNO DNAME LOC40 A/C MUMStored Procedures: • It is a database object • After successful compilation it will be stored into a precompiled programming unit • So that with out compilation we can use same stored procedure any number of times • User can get reusability • It is major part performance tuning • Used complete a task in databaseTypes:1. System stored procedures:Ex:sp_tablessp_helptable <TN>sp_helpdb <database name>sp_renamesp_addumpdevice2. User stored procedure: • defined by the users explicitly • variable are known as "parameters" • parameters are two types1. In :( default) used to pass the values2. Output: used to get the valuesNote: stored procedure can return multiple values through its output parameter Syntax: CREATE PROC [EDURE] PROCEDURENAME [@PARA 1 DATATYPE (SIZE)[=DEFAULT_VALUE][OUTPUT] @PARA 2 DATATYPE (SIZE)[=DEFAULT_VALUE][VALUE],….] AS BEGIN SELECT STATEMENT END
  • 49. Suresh 49 Syntax to execute the user defined stored procedure: EXEC [UTE] PROCEDURENAME [VALUE1, VALUE2…]Drop:Drop procedure pro_namePrograms:  Create a stored procedure to insert data into dept tableCreate procedure insert_dept @dno int,@name varchar (20),@loc varchar (20)AsBeginInsert into dept (deptno, dname, loc) values (@dno, @name, @loc)EndExecution:Exec insert_dept 50,csc,hyderabadResult:Select*from dept  Create a stored procedure to update dname, loc according to the given deptno of dept tableCreate procedure update_dept @dno int, @name varchar (20),@loc varchar (20)AsBeginUpdate dept set dname=@name,loc=@loc where deptno=@dnoEndExecution:Exec update_dept 50,eee,indiaResult:Select*from dept Note: The number of values supplied through EXEC statement must be equal to the number parameters.  Write a procedure to select the data from EMP table. CREATE PROCEDURE P1 AS BEGIN SELECT * FROM EMP
  • 50. Suresh 50 END EXEC P1  Write a procedure to select the data from EMP table based on user supplied DEPTNO. CREATE PROCEDURE P2 @X INT AS BEGIN SELECT * FROM EMP WHERE DEPTNO=@X END EXEC P2 20  Write a procedure to add two numbers CREATE PROCEDURE P3 @A INT=10,@B INT=20 AS BEGIN DECLARE @C INT SET @C=@A+@B PRINT @C END EXEC P3 Output: 30 EXEC P3 25, 45 Output: 70 Note: Server will give highest priority to the user supplied values rather than default values.User Defined Functions :( UDF’S) • It is a database object • Used to complete calculations in database • It is like stored procedure after successful compilation it will stored into database as a pre • compiled programming unit • User’s gets reusability facility i.e. without compilation users can go for execution • It contains only one parameterIn parameter: used to pass the values 1. Through return statement it can send value to the user 2. Udf’s can return single value with data type
  • 51. Suresh 51 Functions created by user are called user defined functions Types of user defined functions: 1. SCALAR VALUED FUNCTIONS 2. TABLE VALUED FUNCTIONS 1. Scalar valued functions: These functions will return a scalar value to the calling environment Syntax: CREATE FUNCTION < FUNCTION_NAME> (@PARA 1 DATA TYPE , @ PARA 2 DATATYPE…) RETURNS <DATATYPE> AS BEGIN DECLARE @VARIABLE DATATYPE -------- ---------- RETURN @VARIABLE END Syntax to execute the user defined function: SELECT/PRINT DBO.FUNCTIONNAME (VALUE1, VALUE2…) Note: The number of values supplied through PRINT/SELECT statement must be equal to the number parameters.  Write a function to find the product of two numbers CREATE FUNCTION F1 (@ A INT, @B INT) RETURNS INT AS BEGIN DECLARE @ C INT SET @C = @A * @B RETURN @C END SELECT/PRINT DBO.F1 (3,5)  Write function to find the net salary of an employee read EMPNO though parameter and display the net to return value CREATE FUNCTION F2 (@ VNO INT) RETURNS INT AS BEGIN DECLARE @ VSAL INT, @VCOM INT, @NET INT SELECT @VSAL = SAL, @VCOM=COM FROM EMP WHERE EMPNO =@VNO IF @ VCOM IS NULL BEGIN PRINT ‘COMMISION IS NULL’ SET @NET = @VSAL
  • 52. Suresh 52 END ELSE BEGIN SET @ NET = @VSAL + @VCOM END RETURN (@NET) END PRINT/SELECT DBO.F2(22) 2. Table valued function: These functions will return entire table to the calling environment. Syntax: CREATE FUNCTION <FUNCTION_NAME> (PARA 1 DATA TYPE ……….) RETURNS TABLE AS BEGIN <FUNCTION BODY> RETURN (SELECT STATEMENT) END  Write a function to return entire dept table CREATE FUNCTION F3() RETURNS TABLE AS BEGIN RETURN (SELECT * FROM DEPT) END SELECT * FROM F3() DEPT DNAME LOC  CREATE FUNCTION F4() RETURN TABLE AS BEGIN RETURN(SELECT ENAME, DNAME FROM EMP, DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO) END SELECT * FROM F4() ENAME DNAME SMITH RESEARCH MILLER ACCOUNTING
  • 53. Suresh 53  Create function to convert datetime data into charDefault datetime format: yyyy-mm-dd HH: MI: SS: MS’  2009-07-31 -- is it datetime data in sqlserver 2005? NoCREATE FUNCTION DateOnly (@InDateTime date time)RETURNS varchar (10)ASBEGIN DECLARE @MyOutput varchar (10) SET @MyOutput = CONVERT (varchar (10), @InDateTime, 101) RETURN @MyOutputENDNote: Convert is inbuilt function used to convert data from one data type to anotherTo call our function, execute: SELECT dbo.DateOnly (GETDATE ())Drop:Syn:Drop function fun_nameTRIGGERS:Two types of Triggers are there in SQLSERVER 2005, they are1. DDL TRIGGERS: Can be created on database Servers and databases.2. DML TRIGGERS: Can be created on Tables and Views.DML Triggers:DML triggers respond to user INSERT, UPDATE, DELETE operations against a table or a view.When a data modification event occurs, the trigger performs a set of actions defined within thetrigger. Similar to stored procedures, triggers are defined in Transact-SQL and allow a full rangeof activities to be performed.A DML trigger can be defined specifically as FOR UPDATE, FOR INSERT, FOR DELETE, or anycombination of the three. UPDATE triggers respond to modifications against one or morecolumns within the table, INSERT triggers respond to new data being added to the database, andDELETE triggers respond to data being deleted from the database.There are two types of DML triggers: AFTER and INSTEAD OF.AFTER triggers are only allowed for tables, and they execute after the data modification hasbeen completed against the table.INSTEAD OF triggers execute instead of the original data modification and can be created forboth tables and views.
  • 54. Suresh 54DML triggers allow you to perform actions in response to data modifications in a table.For example, you can create a trigger that populates an audit table based on the operationperformed, or perhaps use the trigger to decrement the value of a quantity. Although this ability totrigger actions automatically is a powerful feature, there are a few things to keep in mind beforeyour use of triggers proliferates:• Triggers can often become a hidden and hence forgotten problem. When troubleshootingPerformance or logical issues, DBAs can forget that triggers are executing in the background.Make sure that your use of triggers is “visible” in your data documentation.• If you can ensure that all your data modifications flow through a stored procedure, I wouldstrongly recommend you perform all activities within the stored procedure, rather than use aTrigger. For example, if you need to update a quantity in a related table, after inserting a salesrecord; why not put this logic in the stored procedure instead? The advantages are manageability(One place to look) and supportability (one place to troubleshoot), when the Procedure needsmodifications or performs unexpected actions.• Always keep performance in mind and this means writing triggers that execute quickly.Long-running triggers can significantly slow down data modification operations. Take particularcare in putting triggers into databases with frequent data modifications.• Non-logged updates do not cause a DML trigger to fire (for example WRITETEXT, TRUNCATETABLE and bulk insert operations).• Constraints usually run faster than a DML trigger, so if your business requirements can befulfilled by a constraint, use constraints instead. AFTER triggers run after the data modificationhas already occurred, so they cannot be used to prevent a constraint violation.• Don’t allow result sets from a SELECT statement to be returned within your trigger. Mostapplications can’t consume these in an elegant fashion, and embedded queries can hurt theTrigger’s performance.Parts of Trigger: 1. Triggering Statement 2. Triggering Restriction 3. Triggering ActionNote: Triggering Action is different from remaining parts, because Trigger fires implicitlywhenever an event occurs against to the Triggering Condition.Things to Observe: • When user creates an after Trigger on any table for INSERT operation then server arranges a temporary table “INSERTED” for holding recently inserted values. • When user creates an after Trigger on any table for DELETE operation then server arranges a temporary table “DELETED” for holding recently deleted values. • When user creates an after Trigger on any table for UPDATE operation then server arranges two temporary tables “INSERTED, DELETED” for holding old and new values of UPDATE operation.
  • 55. Suresh 55Syntax of After Trigger: CREATE TRIGGER TRIGGERNAME ON TABLE NAME FOR/ AFTER {INSERT/ UPDATE/ DELETE} AS BEGIN SQL STATEMENT ENDSyntax for Instead of Trigger:Create trigger <Trigger_name> on <TN> or <View_name> instead of INSERT OR UPDATE ORDELETE AsBeginBody of the programEndDrop:Syntax: Drop trigger <Trigger_name>Retrieve list of Triggers on a Table:Syn: sp_helptrigger <TN>Ex: sp_helptrigger EMPTo view the SQL behind a specific triggerSyn: sp_helptext <Trigger_name>Create a trigger for generate alertCreate trigger tri_emp on EMP after insertAsBeginPrint one row insertedEndResult:Insert into EMP (empno) values (1)Create a trigger for copying data from Temp table to Original tableCREATE TRIGGER deleteorder_trigger ON ordersAFTER DELETEASBEGININSERT INTO orders_archive (order_id, order_date, cust_id)SELECT order_id, order_date, cust_id FROM DELETEDEndNote:
  • 56. Suresh 56 1. Create Orders, Orders_archive tables before running above program. 2. Orders, Orders_archive tables contain same structure. 3. DELETED is a temporary tableEx:CREATE TRIGGER vendor_trigger ON EMPAFTER INSERT, UPDATEASBEGINUPDATE EMP SET ename=Upper (ename)WHERE empno IN (SELECT empno FROM INSERTED)END Instead of Trigger: Ex: CREATE TRIGGER T4 ON DEPT INSTEAD OF INSERT,UPDATE, DELETE AS BEGIN PRINT ‘THESE OPERATIONS ARE NOT ALLOWED’ END The above trigger fires automatically and shows a message THESE OPERATIONS ARE NOT ALLOWED, when user try to perform INSERT, UPDATE, DELETE operations on DEPT table. DDL TRIGGERS (2005 Triggers): These triggers are fired when user performs DDL operations in the database and these triggers belong to database. It means we can define triggers on the current database. Syntax: CREATE TRIGGER TRIGGERNAME ON DATABASE FOR/ AFTER {DROP,/ALTER/ CREATE} AS BEGIN SQL STATEMENT. END 1. USE PUBS CREATE TRIGGER DROP_TRG ON DATABASE FOR DROP_TABLE AS BEGIN PRINT ‘TABLE DROPPED’ END 2. USE PUBS
  • 57. Suresh 57 CREATE TRIGGER DROP_TRG ON DATABASE INSTEAD OF DROP_TABLE AS BEGIN PRINT ‘U CANNOT DROP THE TABLE’ENDDIFFERENCE BETWEEN ORACLE & SQL Server: ORACLE SQL Server DESCRIPTION%TYPE data type No equivalent The %TYPE data type of Oracle lets you create a variable and have that variables data type be defined by a table or view column or a PL/SQL package variable. There is no equivalent for Oracles %TYPE datatype in T-SQL, but it can be simulated (not very conveniently though) using User Defined Data types (UDT). Here is an example: EXEC sp_addtype MyType, smallint, NULL CREATE TABLE MyTable (i MyType) CREATE PROC MyProc AS BEGIN DECLARE @i MyType ENDBEFORE triggers INSTEAD OF Use INSTEAD OF trigger in SQL Server as an equivalent to triggers Oracles BEFORE trigger. For more information on INSTEAD OF triggers, see SQL Server Books OnlineDECODE() CASE DECODE can be conveniently simulated using the T-SQL CASEfunction expression expression. Heres an example: SELECT Sport, CASE Sport WHEN Cricket THEN England WHEN Hockey THEN India WHEN Base Ball THEN America ELSE NULL END AS Originating Country FROM SportsDESCRIBE sp_help or There are a lot of alternatives for Oracles DESCRIBE, in SQL sp_columns Server. You could use the system stored procedure sp_help for detailed information about a tables columns and other properties.
  • 58. Suresh 58 If sp_help is providing you with too much information, then try the ODBC catalog stored procedure, sp_columns. There are a bunch of other useful sp_help* stored procedures available in SQL Server. You can find more information about those in SQL Server Books Online. If none of those procedures are suitable for your requirements, then you could query the system view INFORMATION_SCHEMA.COLUMNS, to get the desired information. You could wrap your code inside a stored procedure named DESCRIBE, if you wish. As a last resort, you could even query system tables like sysobjects and syscolumns, but this is not a recommended approach.DUAL table No equivalent There is no DUAL table in SQL Server. In fact, you dont need one in SQL Server, as you can have a SELECT statement without a FROM clause. For example, consider the following SELECT statement in Oracle: SELECT Something FROM DUAL In SQL Server, the same result can be obtained by the following command: SELECT Something If you are porting some code from Oracle into SQL Server and if you dont want to remove all references to DUAL table, then just create a DUAL table in your database using the following commands: CREATE TABLE DUAL ( DUMMY varchar(1) ) INSERT INTO DUAL (DUMMY) VALUES (X)INTERSECT Not supported Use EXISTS clause to generate the same result.operator The following example illustrates the simulation of Oracles INTERSECT operator: SELECT OrderID, OrderDate FROM Orders O WHERE EXISTS ( SELECT 1 FROM RefundsTable R
  • 59. Suresh 59 WHERE O.OrderID = R.OrderID )MINUS operator Not supported Use NOT EXISTS clause in your SELECT statement to generate the same result. The following example illustrates the simulation of Oracles MINUS operator: SELECT OrderID, OrderDate FROM Orders O WHERE NOT EXISTS ( SELECT 1 FROM RefundsTable R WHERE O.OrderID = R.OrderID )Nested tables Not supported Oracle 8i and prior versions didnt support this feature and is introduced in Oracle 9i. This feature basically enables you to store a table, within a column. It is like having an array of records in your database columns. SQL Server has no concept of nested tables. As a workaround, You could store your sub-tables or child tables in the form of XML inside a char, nchar, varchar, nvarchar, text or ntext type column, and parse it as needed, at runtime. See OPENXML, sp_xml_preparedocument, sp_xml_removedocument in SQL Server 2000 Books Online. Another possible workaround would be to store comma separated values (CSV). Note that this is against the basic rules of normalization. Columns are nomore atomic, with nested tables. From a design point of view, best thing to do would be, to create different tables for representing different entities and link them with primary and foreign key relationships. This will also make searching easier.Packages Not supported No equivalent in SQL Server for Oracles Packages and Package variables conceptPL/SQL T-SQL Every database product implements and extends the standard PROGRAMMING SQL. Oracles implementation of SQL is called PL/SQL, while Microsofts is called T-SQL (Transact-SQL)Row level security No equivalent Though there is no inbuilt support in SQL Server for row level permissions, you can implement it using view and system functions. For more information and a working example, read this article:
  • 60. Suresh 60 Implementing row level permissions/security in SQL Server databasesrownum pseudo No equivalent Though there is no rownum or rowid in SQL Server, there arecolumn several ways in which a row number can be generated. For some examples, read this article: Q186133 INF: How to Dynamically Number Rows in a Select StatementSELECT...FOR UPDLOCK hint Use the locking hint UPDLOCK in your SELECT statement.UPDATE See SQL Server Books Online for more information.Sequences IDENTITY It is much simpler in SQL Server to generate a sequence value for a primary key or a non-key column. You just need to turn on the IDENTITY property of column. IDENTITY property can be set to columns of the following data types: tinyint, smallint, int, bigint, decimal, numeric Try this example to see how it works: CREATE TABLE foo ( i int IDENTITY(1, 1) j int ) INSERT INTO foo (j) VALUES (911) INSERT INTO foo (j) VALUES (999)SQL *Plus Query Analyzer/ For connecting to SQL Server and executing queries and SSMS modifying data, use the built-in Query Analyzer. It is much more powerful and friendlier than Oracles SQL *PlusSTART No equivalent Though theres no direct equivalent in T-SQL for Oracles STARTWITH...CONNECT WITH...CONNECT BY, there are several ways and efficientBY clause techniques for processing and querying hierarcical data. For more information, read this article: Working with hierarchical data in SQL Server databasesSynonym Views You can simulate Oracle Synonyms in SQL Server using Views. For example, the following creates a view that returns the OrderID and OrderDate from Orders table. CREATE VIEW vOrders AS SELECT OrderID, OrderDate FROM Orders
  • 61. Suresh 61 Now you can select data from the view, using the following SELECT statement: SELECT * FROM vOrders The following example will create a view which is equivalent to Oracles TABS synonym or USER_TABLES data dictionary view (For simplicity, I am only including the table name in the view definition): CREATE VIEW TABS AS SELECT name AS table_name FROM sysobjects WHERE type = U Now you can execute the following SELECT statement to return all user table names: SELECT table_name FROM TABST-SQL Enhancements in 2008:Every new version of SQL Server comes with several T-SQL features and enhancements.SQL Server 2008 is no exception. In the newest version of SQL Server, Microsoft has respondedto developer requests in a big way. SQL Server 2008 supports brand new developer conveniencefeatures like single statement declaration and initialization, new data types to manipulate andquery date-based and spatial data, new statements like MERGE that add much neededfunctionality to T-SQL and a whole lot more. Once you’ve made the move to SQL Server 2008,you’ll undoubtedly want to take advantage of the new features and functionality to solve commonproblems. 1. Separate Variable Declaration and Initialization The first of these new features is single statement variable declaration and initialization. In the past, developers had to declare new variables in one or more DECLARE statements and assign values to the variables in one or more SET or SELECT statements as shown in below Listing. DECLARE @x int, @y int, @z int SET @x=1 SET @y=2 SET @z=3 With single statement declaration and initialization, you can combine these two steps into a single step as shown in below Listing DECLARE @x int =1,@y int=2, @z int =3 2. Calculating and Assigning Values with C-Style Assignment T-SQL has further improved with the addition of several C-Style assignment operators.
  • 62. Suresh 62Operator Description+= Addition with assignment, or string concatenation with assignment-= Subtraction with assignment*= Multiplication with assignment/= Division with assignment%= Modulo with assignment Ex: DECLARE @x int=4, @y int=25, @s1 varchar(20)=’Sql’ SET @x *= @y SET @s1+= ‘SERVER’ SELECT @x, @s1 3. NEW INSERT STATEMENTSYNTAX:INSERT INTO TABLE_NAMEVALUES(VALUE1, VALUE2,……),(VALUE1, VALUE2,…..),(VALUE1,VALU2,……..)EX:INSERT INTO EMPVALUES(11,’RAM’, 30000, 10),(22,’RAJ’, 20000, 20)Like in SQL Server 2005 we need not to write multiple INSERT statements for multiple records.With in single INSERT statement we can insert multiple records into the table at a time 4. MERGE Statement It is one of the DML statement placed newly in SQL Server 2008 Merge Statement is a combination statement that can perform INSERT, UPDATE, DELETE statements based on whether rows that match the selection criteria exist in the target table or not. This Merge statement takes Target and Source Tables, When Source rows are matched with Target it will update the rows of source table into target table otherwise it will insert the rows of source table into target table. Always merge statement takes a temp table as its source and base table as its target table. Using this Merge statement we can combine the rows of a source table to target table.
  • 63. Suresh 63 Syntax: MERGE Target_Table as target USING Source_table as source ON condition WHEN MATCHED THEN UPDATE SET column=source.column,……….. WHEN TARGET NOT MATCHED THEN INSERT VALUES (source.column1, source.column2,) 4. New Data Types In 2008 SQL Server 2008 provides new data types that support storage, manipulation and querying of new forms of data. Some, like the date data type which stores a simple date with out the time component. Others like the geometry data type, which allows storage and querying of spatial data, have only recently addressed. Date and Time Data Types SQL Server supports four brand new date and time data types, which includes 1. date 2. time 3. datetime2 4. datetimeoffsetThe date data type finally allows us to store date only without the time component. It canalso store a much larger range of dates than datetime and smalldatetime data types.The date data type can handle dates from January 1, 1 CE (0001-01-01) to December 31,9999 CE (9999-12-31) Ex: DECLARE @d1 date=’0014-08-19’ DECLARE @d2 date=’1983-02-26’ SELECT @d1 as DATE1,@d2 as DATE2 DATEDIFF (YEAR, @d1, @d2) as YEARDIFFERENCE In contrast to the date data type, the time data type lets you to store time only data. The range for the time data type is defined on 24 hour clock, from 00:00:00.0000000 through 23:59:59.9999999 with user defined fractional second precision of up to seven digits. Ex: DECLARE @start_time time (1) =’06:25:19.1’ --1 digit fractional precision DECLARE @end_time time=’18:25:19.1234567’ --default fractional precision SELECT @start_time as STARTTIME, @end_time as ENDTIME
  • 64. Suresh 64 DATEADD (HOUR, 6, @start_time) as STARTTIMEPLUS, DATEDIFF (HOUR,@start_time,@end_time) as ENDSTARTDIFF The cleverly named datetime2 data type is an extension to the standard datetime data type. The datetime2 combines the benefits of the new date and time data types, giving you the wide date range of the date data type and the greater fractional second precision of the time data type. Ex: DECLARE @start_dt2 datetime2=’1972-07-06T07:13:28.8235670’ DECLARE @end_dt2 datetime2=’2009-12-14T03:14:13.2349872’ SELECT @start_dt2 as start_dt2, @end_dt2 as end_dt2 The new datetimeoffset data type builds on datetime2 by adding the ability to store offsets relative to the International Telecommunication Union(ITU) standard for Coordinated Universal Time(UTC) with your date and time data type. 5. The Hierarchyid Data Type The hierarchyid data type offers to represent hierarchical data in the database. This new data type offers built-in support for representing your hierarchical data using one of the simplest models available: materialized paths Hierarchyid Data Type Methods Method DescriptionGetAncestor(n) Retrieves the nth ancestor of the hierarchyid node instanceGetDescendent(n) Retrieves the nth descendent of the hierarchyid node instanceGetLevel() Gets the level of the hierarchyid node instance in the hierarchyGetRoot() Gets the root node of the hierarchyid instance in the hierarchyIsDescendent(node) Returns 1 if a specified node is descendentParse(String) Converts the given canonical string, in forward slash- separated format to a hierarchyid path.Reparent(old_root,new_root) Reparents a node by moving nodes from old_root to new_rootToString() Converts a hierarchyid instance to a canonical forward slash-separated string representation 5. The Spatial Data Type SQL Server 2008 includes two new data types for storing, querying, and manipulating spatial data. • Geometry • GeographyGeometry data type is designed to represent flat-earth, or Euclidean, spatial data.Geography data type supports round earth or ellipsoidal, spatial data.
  • 65. Suresh 65QUERIES:1. Display the dept information from department table. Select * from DEPT;2. Display the details of all employees. Select * from EMP;3. Display the name and job for all employees. Select ename, job from EMP;4. Display name and salary for all employees. Select ename, sal from EMP;5. Display employee number and total salary for each employee. Select empno, sal+comm from EMP;6. Display the names of all employees who are working in department number 10. Select ename from EMP where deptno=10;7. Display the names of all employees working as clerks and drawing a salary more than 3000. select ename from EMP where job=’CLERK’ and sal>3000;8. Display employee number and names for employees who earn commission. Select empno, ename from EMP where comm is not null and comm>0;9. Display names of employees who do not earn any commission. Select empno, ename from EMP where comm is null and comm=0;10. Display the names of employees who are working as clerk, salesman or analyst and drawing a salary more than 3000. Select ename from EMP where (job=’CLERK’ or job=’SALESMAN’ or job=’ANALYST’) and sal>3000; (Or) Select ename from EMP where job in (‘CLERK’,’SALESMAN’,’ANALYST’) and sal>3000;11. Display the names of employees who are working in the company for the past 5 years. Select ename from EMP where sysdate-hiredate>5*365;12. Display the list of employees who have joined the company before 30th June 90 or after 31st dec 90. Select * from EMP where hiredate between ‘30-jun-1990’ and ‘31- dec-1990’;
  • 66. Suresh 6613. Display the names of employees working in department number 10 or 20 or 40 or employees working as clerks, salesman or analyst. Select ename from EMP where deptno in (10, 20, 40) or job in (‘CLERK’,’SALESMAN’,’ANALYST’);14. Display the names of employees whose name starts with alphabet S. Select ename from EMP where ename like ‘S%’;15. Display employee names for employees whose name ends with alphabet. Select ename from EMP where ename like ‘%S’;16. Display the names of employees whose names have second alphabet A in their names. Select ename from EMP where ename like ‘_S%’;17. Display the names of employees whose name is exactly five characters in length. Select ename from EMP where length (ename) =5; (Or) Select ename from EMP where ename like _____;18. Display the names of employees who are not working as SALESMAN or CLERK or ANALYST. Select ename from EMP where job not in (‘CLERK’,’SALESMAN’,’ANALYST’);19. Display the total number of employees working in the company. Select count (*) from EMP;20. Display the maximum salary from EMP table. Select max (sal) from EMP;21. Display the minimum salary from EMP table. Select min (sal) from EMP;22. Display the average salary from EMP table. Select avg (sal) from EMP;23. Display the maximum salary being paid to CLERK. select max (sal) from EMP where job=’CLERK’;24. Display the maximum salary being paid in dept no 20. Select max (sal) from EMP where deptno=20;25. Display the min Sal being paid to any SALESMAN. select min (sal) from EMP where job=’SALESMAN’;26. Display the average salary drawn by managers. select avg (sal) from EMP where job=’MANAGER’;
  • 67. Suresh 6727. Display the names of employees in order of salary i.e. the name of the employee earning lowest salary should appear first. Select ename from EMP order by sal;28. Display the names of employees in descending order of salary. Select ename from EMP order by sal desc;29. Display the details from EMP table in order of EMP name. Select ename from EMP order by ename;30. Display empno, ename, deptno, and sal. Sort the output first based on name and within name by deptno and within deptno by Sal; Select * from EMP order by ename, deptno, sal;31. Display name, Sal, hra, pf, da, total Sal for each employee. The output should be in the order of total Sal, hra 15% of Sal, da 10% of sal, pf 5% of sal total salary will be (sal*hra*da)-pf. select ename,sal,sal*15/100 HRA, sal*5/100 PF, sal*10/100 DA,sal+sal*15/100-sal*5/100+sal*10/100 TOTAL_SALARY from emp32. Display dept numbers and total number of employees within each group. select deptno,count(*) from emp group by deptno;33. Display the various jobs and total number of employees with each job group. select job, count(*) from emp group by job;34. Display department numbers and total salary for each department. select deptno, sum(sal) from emp group by deptno;35. Display department numbers and maximum salary for each department. select deptno, max(sal),min(sal) from emp group by deptno;36. Display the various jobs and total salary for each job. select job, sum(sal) from emp group by job;37. Display each job along with minimum sal being paid in each job group. select job, min(sal) from emp group by job;38. Display the department numbers with more than three employees in each dept. select deptno, count(*) from emp group by deptno having count(*)>3;39. Display the various jobs along with total sal for each of the jobs where total sal is greater than 40000. select job, sum(sal) from emp group by job having sum(sal)>40000;40. Display the various jobs along with total number of employees in each job. The output should contain only those jobs with more than three employees. select job, count(*) from emp group by job having count(*)>3;
  • 68. Suresh 6841. Display the name of emp who earns highest sal. select ename from emp where sal=(select max(sal) from emp);42. Display the employee number and name of employee working as CLERK and earning highest salary among CLERKS. select empno, ename from emp where job=CLERK and sal=(select max(sal) from emp where job=CLERK);43. Display the names of the salesman who earns a salary more than the highest salary of any clerk. select ename from emp where job=’SALESMAN’ and sal > (select max(sal) from emp where job=CLERK);44. Display the names of clerks who earn salary more than that of James of that of sal lesser than that of Scott. select ename from emp where job=CLERK and sal<(select sal from emp where ename=SCOTT) and sal>(select sal from emp where ename=JAMES);45. Display the names of employees who earn a Sal more than that of James or that of salary greater than that of Scott. select ename from emp where sal < (select sal from emp where ename=SCOTT) and sal > (select sal from emp where ename=JAMES);46. Display the names of the employees who earn highest salary in their respective departments. select * from emp e where sal = (select max(sal) from emp where deptno=e.deptno)47. Display the names of employees who earn highest salaries in their respective job groups. select * from emp e where sal in (select max(sal) from emp group by job having e.job=job)48. Display the employee names who are working in accountings dept. select ename from emp where deptno = (select deptno from dept where dname=”ACCOUNTING”); (or) select ename from emp where deptno in (select deptno from dept where dname=”ACCOUNTING”);49. Display the employee names who are working in Chicago. select ename from emp where deptno = (select deptno from dept where loc=’CHICAGO’);50. Display the job groups having total salary greater then the maximum salary for managers. select job, sum(sal) from emp group by job having sum(sal) > (select max(sal) from emp where job=MANAGER);51. Display the names of employees in Upper case.
  • 69. Suresh 69 select upper(ename) from emp;52. Display the names of employees in lower case. select lower(ename) from emp;53. Replace every occurrence of alphabet A with B in the string Allen’s (user translate function). select replace(Allens,A,b) from dual;54. Display the information from EMP table. Wherever job ‘manager’ is found it should be displayed as boss(replace function). select empno, ename, replace(job, MANAGER, Boss) JOB from emp;55. Display empno, ename, deptno from EMP table. Instead of display department numbers display the related department name (use decode function). select e.empno, e.ename, d.dname from emp e,dept d where e.deptno = d.deptno;56. Display the common jobs from department number 10 and 20. select job from emp where deptno=10 and job in(select job from emp where deptno=20); (or) select job from emp where deptno=10 intersect select job from emp where deptno=20;57. Display the jobs found in department number 10 and 20 eliminate duplicate jobs. select distinct(job) from emp where deptno=10 and job in(select job from emp where deptno=20); (or) select job from emp where deptno=10 intersect select job from emp where deptno=20;58. Display the jobs which are unique to dept no 10. select job from emp where deptno=10 minus select job from emp where deptno!=10; (or) select job from emp where deptno = 10 and job not in (select job from emp where deptno<>10);59. Display the details of those who do not have any person working under them. select empno from emp where empno not in (select mgr from emp where mgr is not null);60. Display the details of employees who are in sales dept and grade is 3. select * from emp where sal>=(select losal from salgrade where grade=3) and sal<=(select hisal from salgrade where grade=3) and deptno=(select deptno from dept where dname=SALES);61. Display those who are not managers and who are managers any one. select * from emp where empno in(select mgr from emp) union
  • 70. Suresh 70 select * from emp where empno not in(select mgr from emp where mgr is not null);62. Display those employees whose name contains not less than 4 chars. Select * from emp where length(ename)>4;63. Display those departments whose name start with ‘S’ while location name end with ‘O’. select * from dept where dname like S% and loc like %O;64. Display those employees whose manager name is JONES. select * from emp where mgr=(select empno from emp where ename=JONES);65. Display those employees whose salary is more than 3000 after giving 20% increment. select * from emp where sal*120/100 > 3000; (or) select * from emp where sal+sal*20/100 > 3000;66. Display all employees with there dept name. select ename, dname from emp e, dept d where e.deptno = d.deptno;67. Display ename who are working in sales dept. select empno, ename from emp where deptno=(select deptno from dept where dname=SALES);68. Display employee name, deptname, salary and comm. for those Sal in between 2000 to 5000 while location is Chicago. select empno,ename,deptno from emp where deptno=(select deptno from dept where loc=CHICAGO) and sal between 2000 and 5000;69. Display those employees whose salary greater than his manager salary. select * from emp e where sal>(select sal from emp where empno=e.mgr);70. Display those employees who are working in the same dept where his manager is working. select * from emp e where deptno = (select deptno from emp where empno=e.mgr);71. Display those employees who are not working under any manger. select * from emp where mgr is null or empno=mgr;72. Display grade and employees name for the dept no 10 or 30 but grade is not 4, while joined the company before 31-dec-82. select empno,ename,sal,deptno,hiredate,grade from emp e,salgrade s where e.sal>=s.losal and e.sal<=s.hisal and deptno in(10,30) and grade<>4 and hiredate<01-dec-1981;73. Update the salary of each employee by 10% increments that are not eligible for commission.
  • 71. Suresh 71 update emp set sal=sal+(sal*10/100) where comm is null;74. Delete those employees who joined the company before 31-dec-82 while there dept location is ‘NEW YORK’ or ‘CHICAGO’. delete from emp where hiredate<31-dec-1982 and deptno in (select deptno from dept where loc in(NEW YORK,CHICAGO));75. Display employee name, job, deptname, location for all who are working as managers. select ename,job,dname,loc from emp e, dept d where e.deptno=d.deptno and empno in (select mgr from emp);76. Display those employees whose manager names is Jones, and also display there manager name. select e.empno, e.ename, m.ename MANAGER from emp e, emp m where e.mgr=m.empno and m.ename=JONES;77. Display name and salary of ford if his Sal is equal to high Sal of his grade. select ename,sal from emp e where ename=FORD and sal=(select hisal from salgrade where grade=(select grade from salgrade where e.sal>=losal and e.sal<=hisal));78. Display employee name, his job, his dept name, his manager name, his grade and make out of an under department wise. select d.deptno, e.ename, e.job, d.dname, m.ename, s.grade from emp e, emp m, dept d, salgrade s where e.deptno=d.deptno and e.sal between s.losal and s.hisal and e.mgr=m.empno order by e.deptno;79. List out all the employees name, job, and salary grade and department name for every one in the company except ‘CLERK’. Sort on salary display the highest salary. select empno, ename, sal, dname, grade from emp e, dept d, salgrade s where e.deptno=d.deptno and e.sal between s.losal and s.hisal and e.job<>CLERK order by sal;80. Display employee name, his job and his manager. Display also employees who are without manager. select e.ename, e.job, m.ename Manager from emp e,emp m where e.mgr=m.empno union select ename,job,no manager from emp where mgr is null;81. Find out the top 5 earner of company. select * from emp e where 5>(select count(*) from emp where sal>e.sal) order by sal desc;82. Display the name of those employees who are getting highest salary. select empno,ename,sal from emp where sal=(select max(sal) from emp);
  • 72. Suresh 7283. Display those employees whose salary is equal to average of maximum and minimum. select * from emp where sal=(select (max(sal)+min(sal))/2 from emp);84. Display count of employees in each department where count greater than 3. select deptno, count(*) from emp group by deptno having count(*)>3;85. Display dname where at least 3 are working and display only dname. select dname from dept where deptno in (select deptno from emp group by deptno having count(*)>3);86. Display name of those managers name whose salary is more than average salary of company. select ename, sal from emp where empno in(select mgr from emp) and sal > (select avg(sal) from emp);87. Display those managers name whose salary is more than an average salary of his employees. select ename, sal from emp e where empno in(select mgr from emp) and e.sal>(select avg(sal) from emp where mgr=e.empno);88. Find out the last 5(least) earner of the company? select * from emp e where 5>(select count(*) from emp where sal<e.sal) order by sal;89. Find out the number of employees whose salary is greater than there manager salary? select count(*) from emp e where sal>(select sal from emp where empno=e.mgr);90. Display those manager who are not working under president but they are working under any other manager? select * from emp e where mgr in(select empno from emp where ename<>KING);91. Delete those department where no employee working? delete from dept d where 0=(select count(*) from emp where deptno=d.deptno);92. Delete those records from EMP table whose deptno not available in dept table? delete from emp where deptno not in(select deptno from dept);93. Display those earners whose salary is out of the grade available in Sal grade table? select * from emp where sal<(select min(losal) from salgrade) or sal>(select max(hisal) from salgrade);94. Display employee name, Sal, comm. and whose net pay is greater than any other in the company?
  • 73. Suresh 73 Select ename, sal, comm from emp where sal+sal*15/100-sal*5/100 +sal*10/100 = (select max(sal+sal*15/100-sal*5/100+sal*10/100) from emp);95. Display those employees who are working in sales or research? select * from emp where deptno in(select deptno from dept where dname in(SALES,RESEARCH));96. Display the grade of Jones? select grade from salgrade where losal<=(select(sal) from emp where ename=JONES) and hisal>=(select(sal) from emp where ename=JONES);97. Delete those records where no of employee in a particular department is less than 3? delete from emp where deptno in(select deptno from emp group by deptno having count(*)>3);98. Display the department name the no of characters of which is equal to no of employees in any other department? Select dname from dept where len (dname) in (select count(*) from emp group by deptno);99. Display those employees who are working as manager? select * from emp where empno in(select mgr from emp);100. Count the no of employees who are working as manager (use set operation)? select count(*) from emp where empno in(select mgr from emp);101. Display the name of then dept those employees who joined the company on the same date? select empno,ename,hiredate,deptno from emp e where hiredate in (select hiredate from emp where empno<>e.empno);102. Display the manager who is having maximum number of employees working under him? Select mgr from emp group by mgr having count(*)=(select max(count(mgr)) from emp group by mgr);103. Produce the output of the EMP table “EMPLOYEE_AND_JOB” for ename and job? select * from EMPLOYEE_AND_JOB;104. Print the details of all the employees who are sub ordinate to Blake. Select * from emp where mgr=(select empno from emp where ename=BLAKE);105. Display those who working as manager using co related sub query. Select * from emp where empno in(select mgr from emp);106. Display those employees whose manger name is Jones and also with his manager name.
  • 74. Suresh 74 Select * from emp where mgr=(select empno from emp where ename=JONES) union select * from emp where empno=(select mgr from emp where ename=JONES);107. Find out how many mangers are there with out listing them. Select count (*) from EMP where empno in (select mgr from EMP);108. Check whether all employees number are indeed unique. select count(empno),count(distinct(empno)) from emp having count(empno)=(count(distinct(empno)));109. List out the lowest paid employees working for each manager, exclude any groups where min sal is less than 1000 sort the output by sal. select e.ename,e.mgr,e.sal from emp e where sal in(select min(sal) from emp where mgr=e.mgr) and e.sal>1000 order by sal;110. find out the all employees who joined the company before their manager. Select * from emp e where hiredate<(select hiredate from emp where empno=e.mgr);111. list out the all employees by name and number along with their manager’s name and number also display ‘No Manager’ who has no manager. select e.empno,e.ename,m.empno Manager,m.ename ManagerName from emp e,emp m where e.mgr=m.empno union select empno,ename,mgr,No Manager from emp where mgr is null;112. find out the employees who earned the highest Sal in each job typed sort in descending Sal order. select * from emp e where sal =(select max(sal) from emp where job=e.job);113. find out the employees who earned the min Sal for their job in ascending order. select * from emp e where sal =(select min(sal) from emp where job=e.job) order by sal;114. find out the most recently hired employees in each dept order by hire date select * from emp order by deptno, hiredate desc;115. display ename, sal and deptno for each employee who earn a Sal greater than the avg of their department order by deptno select ename,sal,deptno from emp e where sal>(select avg(sal) from emp where deptno=e.deptno) order by deptno;116. display the department where there are no employees select deptno,dname from dept where deptno not in(select distinct(deptno) from emp);117. display the dept no with highest annual remuneration bill as compensation. select deptno,sum(sal) from emp group by deptno having sum(sal) = (select max(sum(sal)) from emp group by deptno);
  • 75. Suresh 75118. display avg sal figure for the dept select deptno,avg(sal) from emp group by deptno;119. Write a query of display against the row of the most recently hired employee. display ename hire date and column max date showing. select empno,hiredate from emp where hiredate=(select max (hiredate) from emp);120. display employees who can earn more than lowest Sal in dept no 30 select * from emp where sal>(select min(sal) from emp where deptno=30);121. find employees who can earn more than every employees in dept no 30 select * from emp where sal>(select max(sal) from emp where deptno=30); select * from emp where sal>all(select sal from emp where deptno=30);122. find all dept’s which have more than 3 employees select deptno from emp group by deptno having count(*)>3;123. Create a copy of emp table. Create table emp1 as select * from emp;124. Select ename if ename exists more than once. select distinct(ename) from emp e where ename in(select ename from emp where e.empno<>empno);125. display all enames in reverse order. select ename from emp order by ename desc;126. List out the employees ename, sal, PF from emp Select ename,sal,sal*15/100 PF from emp;127. Create table emp with only one column empno Create table emp (empno number(5));128. Add this column to emp table ename Varchar(20). alter table emp add ename varchar2(20) not null;129. OOPS! I forgot to give the primary key constraint. Add it now. alter table emp add constraint emp_empno primary key (empno);130. Now increase the length of ename column to 30 characters. alter table emp modify ename varchar(30);131. Add salary column to emp table. alter table emp add sal numeric(7,2);
  • 76. Suresh 76132. I want to give a validation saying that sal cannot be greater 10,000(note give a name to this column). alter table emp add constraint emp_sal_check check (sal<10000);133. Add column called as mgr to your emp table. Alter table emp add mgr numeric (5);134. Oh! This column should be related to empno. Give a command to add this constraint Alter table emp add constraint emp_mgr foreign key(empno);135. Add dept no column to your emp table Alter table emp add deptno numeric (3);136. This dept no column should be related to deptno column of dept table Alter table emp1 add constraint emp1_deptno foreign key (deptno) references dept (deptno);137. Create table called as new emp. Using single command create this table as well as to get data into this table (use create table as) Select*into newemp from EMP;138. Create table called as newemp. This table should contain only empno,ename, dname create table newemp as select empno,ename,dname from emp e , dept d where e.deptno=d.deptno;139. Provide a commission to employees who are not earning any commission. update emp set comm=300 where comm is null;140. If any employee has commission his commission should be incremented by 10% of his salary. update emp set comm=comm*10/100 where comm is not null;141. Display employee name and department name for each employee. select ename,dname from emp e, dept d where e.deptno=d.deptno;142. Display employee number, name and location of the department in which he is working. Select empno, ename, loc from emp e, dept d where e.deptno=d.deptno;143. Display employee name and his manager name. Select e.ename, m.ename from emp e, emp m where e.mgr=m.empno;144. Display the department name along with total salary in each department. Select deptno, sum(sal) from emp group by deptno;145. Display the department name and total number of employees in each department. select deptno,count(*) from emp group by deptno;
  • 77. Suresh 77
  • 78. Suresh 78