SQL Server Material1
SQL Server Material1
Information: Processing of data is known as information. DataBase : A database can be defined as collection of interrelated records.
(OR)
A database is an application that manages data and allows fast storage and retrieval of that data.
(OR)
A database is a collection of information that is organized so that it can easily be accessed, managed, and updated.
Page 1
External Level
Conceptual Level
Internal Level
Hardware Level
System DataBases:
These databases contain system tables, system procedures and some other system level information. Ex: master, model, msdb, tempdb.
Page 2
Enterprise Manager
1) it is wizard based 2) it is more time consuming 3) Administrators use enterprise manager for backup and Security.
Page 3
SQL PL/SQL
T-SQL
Oracle
SQL Server
SQL is ANSI standard T-SQL (Transact SQL) is Microsoft own standard used to communicate with only SQL Server SQL is Non-Procedural Language T-SQL is set based language(Procedural) SQL offering only one statement at one time of execution T-SQL offers group of statements to execute at a time. Note : SQL can be used with SQLServer ,Oracle and Sybase .But T-SQL can be used for SQL Server.
Page 4
pressF5 After creating the database employee if you want to use created database then Syntax: use <database name> Example: use employee pressF5
Character Data Type: Each character takes 1 byte. 1) char(size) fixed length 2) varchar(size) variable length
Page 6
In 8-bit representation we can store 2 power 8 of characters In Unicode data types we can store 2 power of 16 characters. In Unicode data types each character takes 2 bytes.Towork with global data we have to use Unicode types. Additional Data Types:
1) 2) 3) 4)
SQL_variant (new)we can store any type of data Table (new) to store table of data Timestamp 8 Unique identifier 16
DML(Data Manipulation Language) : It contains insert , delete , update DCL(Data Control Language) : It contains Grant , Revoke
Example #2: create emp table with the following conditions: Empno should be unique and it should not allow any null values Ename should not be null Deptno should be considered as foreign key
Create table emp ( Empno int primary key, Ename varchar(15) not null, Deptno int foreign key references dept(deptno), Sal int ) Example #3: Create dept table with the following fields: deptno, dname, dloc Create table dept ( Deptno int primary key, Dname varchar (15) not null, Dloc varchar (15) not null ) Example # 4: Create a table to implement composite primary key Create table demo
Page 9
( Col1, Col2, Col3, Col4, Constraint pk_demo primary key(col1,col3) ) Example#5: Create a table to implement auto number Create table <table name>(column 1 int identity(1,1),column2 int) Column1 will starts from 1 and it will be incremented by 1
Syntax: Alter table <tablename> Alter column <column name> <new_datatype> Ex: Alter table emp Alter column ename varchar(15)
8)Droping a constraint:
Syntax: alter table <tablename> Drop constraint <constraintname> Ex: alter table emp Drop constraint pk_emp
9)droping a table:
syntax: drop table <tablename> Ex: Drop table Employee
10)droping Database:
Syntax : drop database <database name> Ex: Drop database Sample
Page 12
Alter table <tablename> NOCHECK constraint <constraint name> Ex: alter table emp NOCHECK constraint pk_emp
Page 13
16)Droping triggers:
Syntax : Drop trigger <triggername>
17)Droping views:
Syntax : Drop view <viewname> Ex: Drop view Employee
Truncate:
This command is used to remove all the values from the table permanently. We cannot use where clause with this command. Syntax: Truncate table <tablename> Ex: Truncate table Employee
SQL INSERT INTO: The SQL INSERT INTO syntax has 2 main forms and the result of either of them is adding a new row into the database table. The first syntax form of the INSERT INTO SQL clause doesn't specify the column names where the data will be inserted, but just their values: INSERT INTO Table1 VALUES (value1, value2, value3)
The second form of the SQL INSERT INTO command, specifies both the columns and the values to be inserted in them:
INSERT INTO Table1 (Column1, Column2, Column3) VALUES (Value1, Value2, Value3)
As you might already have guessed, the number of the columns in the second INSERT INTO syntax form must match the number of values into the SQL statement, otherwise you will get an error. If we want to insert a new row into our Customers table, we are going to use one of the following 2 SQL statements: INSERT INTO Customers VALUES ('Peter', 'Hunt', 'peter.hunt@tgmail.net', '1/1/1974', '626 888-8888')
INSERT INTO Customers (FirstName, LastName, Email, DOB, Phone) VALUES ('Peter', 'Hunt', 'peter.hunt@tgmail.net', '1/1/1974', '626 888-8888')
Page 15
The result of the execution of either of the 2 INSERT INTO SQL statements will be a new row added to our Customers database table: FirstName John Steven Paula James Peter LastName Smith Goldfish Brown Smith Hunt Email John.Smith@yahoo.com goldfish@fishhere.net pb@herowndomain.org jim@supergig.co.uk peter.hunt@tgmail.net DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 1/1/1974 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888 626 888-8888
If you want to enter data for just a few of the table columns, youll have to use the second syntax form of the SQL INSERT INTO clause, because the first form will produce an error if you havent supplied values for all columns. To insert only the FirstName and LastName columns, execute the following SQL statement:
SQL UPDATE: The SQL UPDATE general syntax looks like this: UPDATE Table1 SET Column1 = Value1, Column2 = Value2 WHERE Some_Column = Some_Value
The SQL UPDATE clause changes the data in already existing database row(s) and usually we need to add a conditional SQL WHERE clause to our SQL UPDATE statement in order to specify which row(s) we intend to update.
Page 16
If we want to update the Mr. Steven Goldfish's date of birth to '5/10/1974' in our Customers database table
UPDATE Customers SET DOB = '5/10/1974' WHERE LastName = 'Goldfish' AND FirstName = 'Steven' If we dont specify a WHERE clause in the SQL expression above, all customers' DOB will be updated to '5/10/1974', so be careful with the SQL UPDATE command usage. We can update several database table rows at once, by using the SQL WHERE clause in our UPDATE statement. For example if we want to change the phone number for all customers with last name Smith (we have 2 in our example Customers table), we need to use the following SQL UPDATE statement: UPDATE Customers SET Phone = '626 555-5555' WHERE LastName = 'Smith'
After the execution of the UPDATE SQL expression above, the Customers table will look as follows:
DOB
Phone
SQL DELETE: So far weve learnt how to select data from a database table and how to insert and update data into a database table. Now its time to learn how to remove data from a database. Here comes the SQL DELETE statement! The SQL DELETE command has the following generic SQL syntax: DELETE FROM Table1 WHERE Some_Column = Some_Value
If you skip the SQL WHERE clause when executing SQL DELETE expression, then all the data in the specified table will be deleted. The following SQL statement will delete all the data from our Customers table and well end up with completely empty table:
If you specify a WHERE clause in your SQL DELETE statement, only the table rows satisfying the WHERE criteria will be deleted:
Page 18
The SQL query above will delete all database rows having LastName 'Smith' and will leave the Customers table in the following state: FirstName Steven Paula LastName Email Goldfish goldfish@fishhere.net Brown pb@herowndomain.org DOB Phone 4/4/1974 323 455-4545 5/24/1978 416 323-3232
SQL SELECT:
The SQL SELECT statement is used to select data from a SQL database table. This is usually the very first SQL command every SQL newbie learns and this is because the SELECT SQL statement is one of the most used SQL commands. SQL SELECT syntax:
SELECT Column1, Column2, Column3, FROM Table1 The list of column names after the SQL SELECT command determines which columns you want to be returned in your result set. If you want to select all columns from a database table, you can use the following SQL statement:
When the list of columns following the SELECT SQL command is replaced with asterix (*) all table columns are returned. Word of caution here, its always better to
Page 19
explicitly specify the columns in the SELECT list, as this will improve your query performance significantly. The table name following the SQL FROM keyword (in our case Table1) tells the SQL interpreter which table to use to retrieve the data.
The list of column names after the SQL SELECT command determines which columns will be copied, and the table name after the SQL INTO keyword specifies to which table to copy those rows. If we want to make an exact copy of the data in our Customers table, we need the following SQL SELECT INTO statement: SELECT * INTO Customers_copy FROM Customers
SQL DISTINCT:
The SQL DISTINCT clause is used together with the SQL SELECT keyword, to return a dataset with unique entries for certain database table column. We will use our Customers database table to illustrate the usage of SQL DISTINCT.
Page 20
For example if we want to select all distinct surnames from our Customers table, we will use the following SQL DISTINCT statement:
The result of the SQL DISTINCT expression above will look like this: LastName Smith Goldfish Brown
SQL WHERE:
The SQL WHERE clause is used to select data conditionally, by adding it to already existing SQL SELECT query. We are going to use the Customers table from the previous chapter, to illustrate the use of the SQL WHERE command.
DOB
Phone
If we want to select all customers from our database table, having last name 'Smith' we need to use the following SQL syntax: SELECT * FROM Customers WHERE LastName = 'Smith' The result of the SQL expression above will be the following: FirstName LastName Email John Smith John.Smith@yahoo.com James Smith jim@supergig.co.uk DOB Phone 2/4/1968 626 222-2222 20/10/1980 416 323-8888
In this simple SQL query we used the "=" (Equal) operator in our WHERE criteria: LastName = 'Smith'
But we can use any of the following comparison operators in conjunction with the SQL WHERE clause: <> (Not Equal) SELECT * FROM Customers WHERE LastName <> 'Smith'
Page 22
>= (Greater or Equal) SELECT * FROM Customers WHERE DOB >= '1/1/1970'
< (Less than) SELECT * FROM Customers WHERE DOB < '1/1/1970'
<= (Less or Equal) SELECT * FROM Customers WHERE DOB =< '1/1/1970'
LIKE (similar to) SELECT * FROM Customers WHERE Phone LIKE '626%'
Page 23
Note the LIKE syntax is different with the different RDBMS (SQL Server syntax used above). Check the SQL LIKE article for more details.
Between (Defines a range) SELECT * FROM Customers WHERE DOB BETWEEN '1/1/1970' AND '1/1/1975'
SQL LIKE: We will use the Customers table to illustrate the SQL LIKE clause usage:
The SQL LIKE clause is very useful when you want to specify a search condition within your SQL WHERE clause, based on a part of a column contents. For example if you want to select all customers having FirstName starting with 'J' you need to use the following SQL statement:
If you want to select all Customers with phone numbers starting with '416' you will use this SQL expression:
The '%' is a so called wildcard character and represents any string in our pattern. You can put the wildcard anywhere in the string following the SQL LIKE clause and you can put as many wildcards as you like too. Note that different databases use different characters as wildcard characters, for example '%' is a wildcard character for MS SQL Server representing any string, and '*' is the corresponding wildcard character used in MS Access. Another wildcard character is '_' representing any single character. The '[]' specifies a range of characters. Have a look at the following SQL statement: SELECT * FROM Customers WHERE Phone LIKE '[4-6]_6%'
This SQL expression will return all customers satisfying the following conditions:
The Phone column starts with a digit between 4 and 6 ([4-6]) Second character in the Phone column can be anything (_)
Page 25
The third character in the Phone column is 6 (6) The remainder of the Phone column can be any character string (%)
Here is the result of this SQL expression: FirstName John Paula James LastName Smith Brown Smith Email John.Smith@yahoo.com pb@herowndomain.org jim@supergig.co.uk DOB 2/4/1968 5/24/1978 20/10/1980 Phone 626 222-2222 416 323-3232 416 323-8888
The result of the above SQL expression will be the following: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith Email John.Smith@yahoo.com goldfish@fishhere.net pb@herowndomain.org jim@supergig.co.uk DOB 2/4/1968 4/4/1974 5/24/1978 20/10/1980 Phone 626 222-2222 323 455-4545 416 323-3232 416 323-8888
Page 26
As you can see the rows are sorted in ascending order by the DOB column, but what if you want to sort them in descending order? To do that you will have to add the DESC SQL keyword after your SQL ORDER BY clause: SELECT * FROM Customers ORDER BY DOB DESC
The result of the SQL query above will look like this:
If you don't specify how to order your rows, alphabetically or reverse, than the result set is ordered alphabetically, hence the following to SQL expressions produce the same result: SELECT * FROM Customers ORDER BY DOB SELECT * FROM Customers ORDER BY DOB ASC
You can sort your result set by more than one column by specifying those columns in the SQL ORDER BY list. The following SQL expression will order by DOB and LastName: SELECT * FROM Customers
Page 27
The result of the SQL query above is: FirstName John LastName Email Smith John.Smith@yahoo.com DOB Phone 2/4/1968 626 222-2222
The following row in our Customer table, satisfies the second of the conditions (LastName = 'Smith'), but not the first one (FirstName = 'John'), and that's why it's not returned by our SQL query:
FirstName James
LastName Smith
Email jim@supergig.co.uk
DOB 20/10/1980
The SQL OR statement is used in similar fashion and the major difference compared to the SQL AND is that OR clause will return all rows satisfying any of the conditions listed in the WHERE clause.
Page 28
If we want to select all customers having FirstName 'James' or FirstName 'Paula' we need to use the following SQL statement:
You can combine AND and OR clauses anyway you want and you can use parentheses to define your logical expressions. Here is an example of such a SQL query, selecting all customers with LastName 'Brown' and FirstName either 'James' or 'Paula':
SELECT * FROM Customers WHERE (FirstName = 'James' OR FirstName = 'Paula') AND LastName = 'Brown'
The result of the SQL expression above will be: FirstName Paula LastName Email Brown pb@herowndomain.org DOB Phone 5/24/1978 416 323-3232
SQL IN:
Page 29
The SQL IN clause allows you to specify discrete values in your SQL WHERE search criteria. THE SQL IN syntax looks like this: SELECT Column1, Column2, Column3, FROM Table1 WHERE Column1 IN (Valu1, Value2, ) Lets use the EmployeeHours table to illustrate how SQL IN works: Employee John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown Date 5/6/2004 5/6/2004 5/6/2004 5/7/2004 5/7/2004 5/7/2004 5/8/2004 5/8/2004 5/8/2004 Hours 8 8 8 9 8 10 8 8 9
Consider the following SQL query using the SQL IN clause: SELECT * FROM EmployeeHours WHERE Date IN ('5/6/2004', '5/7/2004')
This SQL expression will select only the entries where the column Date has value of '5/6/2004' or '5/7/2004', and you can see the result below:
Employee
Date
Hours
Page 30
John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown
8 8 8 9 8 10
We can use the SQL IN statement with another column in our EmployeeHours table:
The result of the SQL query above will be: Employee John Smith Tina Crown Tina Crown Date 5/7/2004 5/7/2004 5/8/2004 Hours 9 10 9
SQL BETWEEN:
The SQL BETWEEN & AND keywords define a range of data between 2 values. The SQL BETWEEN syntax looks like this:
FROM Table1 WHERE Column1 BETWEEN Value1 AND Value2 The 2 values defining the range for SQL BETWEEN clause can be dates, numbers or just text. In contrast with the SQL IN keyword, which allows you to specify discrete values in your SQL WHERE criteria, the SQL BETWEEN gives you the ability to specify a range in your search criteria. We are going to use the familiar Customers table to show how SQL BETWEEN works:
Consider the following SQL BETWEEN statement: SELECT * FROM Customers WHERE DOB BETWEEN '1/1/1975' AND '1/1/2004'
The SQL BETWEEN statement above will select all Customers having DOB column between '1/1/1975' and '1/1/2004' dates. Here is the result of this SQL expression:
SQL ALIASES:
SQL aliases can be used with database tables and with database table columns, depending on task you are performing. SQL column aliases are used to make the output of your SQL queries easy to read and more meaningful: SELECT Employee, SUM(Hours) As SumHoursPerEmployee FROM EmployeeHours GROUP BY Employee In the example above we created SQL alias SumHoursPerEmployee and the result of this SQL query will be the following: Employee John Smith Allan Babel Tina Crown SumHoursPerEmployee 25 24 27
Consider the following SQL statement, showing how to use SQL table aliases: SELECT Emp.Employee FROM EmployeeHours AS Emp Here is the result of the SQL expression above: Employee John Smith Allan Babel Tina Crown The SQL table aliases are very useful when you select data from multiple tables.
SQL COUNT:
Page 33
The SQL COUNT aggregate function is used to count the number of rows in a database table. The SQL COUNT syntax is simple and looks like this: SELECT COUNT(Column1) FROM Table1 If we want to count the number of customers in our Customers table, we will use the following SQL COUNT statement:
SQL MAX:
The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain column. The SQL MAX function syntax is very simple and it looks like this:
If we use the Customers table from our previous chapters, we can select the highest date of birth with the following SQL MAX expression:
Page 34
SQL MIN:
The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column. The SQL MIN function syntax is very simple and it looks like this:
If we use the Customers table from our previous chapters, we can select the lowest date of birth with the following SQL MIN expression:
SQL AVG:
The SQL AVG aggregate function selects the average value for certain table column. Have a look at the SQL AVG syntax:
Page 35
SELECT AVG(Column1) FROM Table1 If we want to find out what is the average SaleAmount in the Sales table, we will use the following SQL AVG statement:
SQL SUM:
The SQL SUM aggregate function allows selecting the total for a numeric column. The SQL SUM syntax is displayed below:
We are going to use the Sales table to illustrate the use of SQL SUM clause: Sales:
Page 36
CustomerID 2 1 3 3 4
Consider the following SQL SUM statement: SELECT SUM(SaleAmount) FROM Sales
This SQL statement will return the sum of all SaleAmount fields and the result of it will be: SaleAmount $978.67
Of course you can specify search criteria using the SQL WHERE clause in your SQL SUM statement. If you want to select the total sales for customer with CustomerID = 3, you will use the following SQL SUM statement:
Page 37
$222.95
Employee John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown John Smith Allan Babel Tina Crown
Date 5/6/2004 5/6/2004 5/6/2004 5/7/2004 5/7/2004 5/7/2004 5/8/2004 5/8/2004 5/8/2004
Hours 8 8 8 9 8 10 8 8 9
If the manager of the company wants to get the simple sum of all hours worked by all employees, he needs to execute the following SQL statement: SELECT SUM (Hours) FROM EmployeeHours
Page 38
But what if the manager wants to get the sum of all hours for each of his employees? To do that he need to modify his SQL query and use the SQL GROUP BY statement:
The result of the SQL expression above will be the following: Employee John Smith Allan Babel Tina Crown Hours 25 24 27
As you can see we have only one entry for each employee, because we are grouping by the Employee column. The SQL GROUP BY clause can be used with other SQL aggregate functions, for example SQL AVG:
Page 39
The result of the SQL statement above will be: Employee John Smith Allan Babel Tina Crown Hours 8.33 8 9
In our Employee table we can group by the date column too, to find out what is the total number of hours worked on each of the dates into the table:
Here is the result of the above SQL expression: Date 5/6/2004 5/7/2004 5/8/2004 Hours 24 27 25
SQL HAVING:
The SQL HAVING clause is used to restrict conditionally the output of a SQL statement, by a SQL aggregate function used in your SELECT list of columns. You can't specify criteria in a SQL WHERE clause against a column in the SELECT list for which SQL aggregate function is used.
SELECT Employee, SUM (Hours) FROM EmployeeHours WHERE SUM (Hours) > 24 GROUP BY Employee The SQL HAVING clause is used to do exactly this, to specify a condition for an aggregate function which is used in your query: SELECT Employee, SUM (Hours) FROM EmployeeHours GROUP BY Employee HAVING SUM (Hours) > 24 The above SQL statement will select all employees and the sum of their respective hours, as long as this sum is greater than 24. The result of the SQL HAVING clause can be seen below: Employee John Smith Tina Crown Hours 25 27
SQL JOIN:
The SQL JOIN clause is used whenever we have to select data from 2 or more tables. To be able to use SQL JOIN clause to extract data from 2 (or more) tables, we need a relationship between certain columns in these tables. We are going to illustrate our SQL JOIN example with the following 2 tables:
Customers:
Page 41
Phone 626 222Smith John.Smith@yahoo.com 2/4/1968 2222 323 455Goldfish goldfish@fishhere.net 4/4/1974 4545 416 323Brown pb@herowndomain.org 5/24/1978 3232 416 323Smith jim@supergig.co.uk 20/10/1980 8888
DOB
Sales: CustomerID 2 1 3 3 4 Date 5/6/2004 5/7/2004 5/7/2004 5/13/2004 5/22/2004 SaleAmount $100.22 $99.95 $122.95 $100.00 $555.55
As you can see those 2 tables have common field called CustomerID and thanks to that we can extract information from both tables by matching their CustomerID columns. Consider the following SQL statement: SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer FROM Customers, Sales WHERE Customers.CustomerID = Sales.CustomerID GROUP BY Customers.FirstName, Customers.LastName
The SQL expression above will select all distinct customers (their first and last names) and the total respective amount of dollars they have spent.
Page 42
The SQL JOIN condition has been specified after the SQL WHERE clause and says that the 2 tables have to be matched by their respective CustomerID columns. Here is the result of this SQL statement: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith SalesPerCustomers $99.95 $100.22 $222.95 $555.55
The SQL statement above can be re-written using the SQL JOIN clause like this: SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer FROM Customers JOIN Sales ON Customers.CustomerID = Sales.CustomerID GROUP BY Customers.FirstName, Customers.LastName
There are 2 types of SQL JOINS: INNER JOINS and OUTER JOINS. If you don't put INNER or OUTER keywords in front of the SQL JOIN keyword, then INNER JOIN is used. In short "INNER JOIN" = "JOIN" (Note that different databases have different syntax for their JOIN clauses). The INNER JOIN will select all rows from both tables as long as there is a match between the columns we are matching on. In case we have a customer in the Customers table, which still hasn't made any orders (there are no entries for this customer in the Sales table), this customer will not be listed in the result of our SQL query above.
Page 43
If the Sales table has the following rows: CustomerID 2 1 Date 5/6/2004 5/6/2004 SaleAmount $100.22 $99.95
And we use the same SQL JOIN statement from above: SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer FROM Customers JOIN Sales ON Customers.CustomerID = Sales.CustomerID GROUP BY Customers.FirstName, Customers.LastName
We'll get the following result: FirstName John Steven LastName Smith Goldfish SalesPerCustomers $99.95 $100.22
Even though Paula and James are listed as customers in the Customers table they won't be displayed because they haven't purchased anything yet. But what if you want to display all the customers and their sales, no matter if they have ordered something or not? Well do that with the help of SQL OUTER JOIN clause. The second type of SQL JOIN is called SQL OUTER JOIN and it has 2 subtypes. LEFT OUTER JOIN and RIGHT OUTER JOIN.
Page 44
The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most databases), selects all the rows from the first table listed after the FROM clause, no matter if they have matches in the second table.
If we slightly modify our last SQL statement to: SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer FROM Customers LEFT JOIN Sales ON Customers.CustomerID = Sales.CustomerID GROUP BY Customers.FirstName, Customers.LastName
and the Sales table still has the following rows: CustomerID 2 1 Date 5/6/2004 5/6/2004 SaleAmount $100.22 $99.95
The result will be the following: FirstName John Steven Paula James LastName Smith Goldfish Brown Smith SalesPerCustomers $99.95 $100.22 NULL NULL
As you can see we have selected everything from the Customers (first table). For all rows from Customers, which dont have a match in the Sales (second table), the SalesPerCustomer column has amount NULL (NULL means a column contains nothing).
Page 45
The RIGHT OUTER JOIN or just RIGHT JOIN behaves exactly as SQL LEFT JOIN, except that it returns all rows from the second table (the right table in our SQL JOIN statement).
Cross Join:
When no join condition is specified then it is called as cross join Ex: select * from dept cross join emp
DATA INTEGRITY
1)
Entity Integrity: This can be achieved with the help of primary key , unique constraints.
2) Domain Integrity: This can be achieved with the help of Not null , Default and Check constraints 3) Referential Integrity: This can be achieved with the help of foreign key constraint Foreign key is used to establish relationships among the tables
Sub Queries:
These are used to combine two statements.We have two types of sub queries.They are as follows Nested Sub queries: In case of nested sub query outer query depends on inner query Ex:
Page 46
select dname from dept where deptno=(select deptno from emp where empno=1001) Correlated-Sub Queries: In case of nested sub query inner query depends on outer query Ex: select a.* from emp a where a.sal>(select avg(b.sal) from emp b where a.deptno=b.deptno)
Page 47
DateTime Functions:
GetDate() It gives current date and time 1) Select getdate() 2) Select DatePart(mm , getdate()) O/p: 12 give month 3) Select DatePart(yy , getdate()) O/p: 2006 gives year 4) Select DateName(dw , getdate()) O/p; Thursday 5) Select datename(mm , gatdate()) O/p: December Ex: Adding days , months ,years to the current date and time 1) Select DateAdd(mm , 5 , getdate()) It adds 5months to the current date 2) Select DateAdd(dd , 10 ,getdate()) It adds 10 days to the current date 3) Select DateAdd(yy , 2 , getdate()) It adds 2 years to the current year
String Functions:
1) Select ASCII(b) 98 2) Select CHAR (98) b
Page 48
3) Select UNICODE (H) 72 4) Select NCHAR (72) H 5) Select LEN(HELLO) 5 6) Select LOWER (HAI) hai 7) Select UPPER (hai) HAI 8) Select LTRIM ( hello) hello It removes blank spaces 9) Select RTRIM (hello ) hello 10) Select LEFT (HELLO,2) HE 11) Select RIGHT (HELLO,2) LO 12) select SUBSTR (helloworld, 3, 4) From third letter it takes 4 chars llow 13) Select REPLACE (HELLO,L,S) HESSO
Aggregate Functions:
1) Select Min (column name/set of values)
Page 49
Gives min value 2) select Max (column name/set of values) Gives maximum value 3) Select Sum (column name / set of values) Gives sum of values 4) Select count (*) Gives no. of occurrences 5) Select Avg(column name / set of values) Gives average
NORMALISATION
Normalisation is the the process of breaking relation into smaller and meaningful parts.It is used to eliminate anomalies like insertion , deletion ,updation etc.. We have different types of normal forms. They are as follows: 1) First Normal Form: 4) no multiple columns 5) no repeating groups
2) Second Normal Form:
It should be in the first normal form Every non-key column should depend on entire primarykey column( no partial dependency)
3) Third Normal Form:
VIEWS
It is a virtual table It is also called as stored query It doesnt contain any data Any changes to the database table will be reflected into the view automatically Advantages: Easy to use Less network bandwidth consumption Views are used to filter the data from tables It Provides security Creation of views: Syntax : Create view <viewname> As <Sql statement> Ex: Create view emp_view As Select * from emp Inserting new row into view: Syntax: insert into <viewname> values(value1,value2,..,value n)
Page 51
Ex: insert into emp_view values(1002,varma,20,54000) Deleting a row from view: Syntax: Delete from <viewname> where <condition> Ex: Delete from emp_view where empno=1001 Updating a column in theview: Syntax: Update <view name> set <colname>=<value> where <condition> EX: Update emp_view set sal=sal+1000 where empno=1002 Nested Views: A view created based on another view is called as nested view Syntax: Create view <viewname> As Select * from <existing viewname> where <condition> Ex: Create view emp_nested_view As Select * from emp_view where ename like s%
Page 52
Programming Basics:
Variables: We have two types of variables.They are as follws Global variables: SQLServer internally maintains setoff variables for its own processing Ex: print @@servername It displays servername Print @@version It displays version Print @@rowcount It gives no. of rows affected Print @@identity It gives last inserted identity value in the current context Print @@error It stores error information of last T-SQL statement Local Variables: Syntax: Declare @variablename <datatype> Set @variablename=<value> Ex: declare @n int Set @n=20 Print value of n=+ cast(@n as char) Ex: declare @str varchar(5)
Page 53
Set @str=Hello Print @str Table variables: Syntax: Declare @tablename table(col1,col2..) Ex: Declare @T1 table(empno int , ename varchar(10), sal int) Insert into T1 values(1001,gaayu,12000) Select * from T1 Note: - Table variable life time is very less because memory for table variable is allocated only at one time of execution of total script.Once script is executed next second memory will be destroyed.
Conditional Statements:
Syntax: if <condition> Begin <statements> End Else Begin <statements> End Ex: declare @a int , @b int Set @a=10 Set @b=20 If @a>@b Print A is Big Else Print B is Big
Page 54
Iteration Statements:
Syntax: while <condition> Begin Statement 1 Statement2 . Ex : declare @i int Set @i=1 while @i<=10 Begin Print cast(@i as char) Set @i=@i+1 End
Statements End Ex1: create function add_num(@a int ,@b int)returns int As Begin Return(@a+@b) End Execution: 1) Exec add_num 10,20 parameters 2) declare @sum int Set @sum=dbo.add_num(10,20) Print sum=+ cast(@sum as char)
Ex2: create function getdeptname(@empno1 int)returns varchar(15) As Begin Return(select dname from dept where deptno=(select deptno from emp where empno=@empno1)) End Execution: Select * from dept where dname=dbo.getdeptname(1001)
STORED PROCEDURES
It is a sub program It doesnt return any value It is a pre-compiled code This will be executed without any compilation
Page 56
Advantages: It provides reusability This will reduce network-traffic It improves performance of the application Syntax: create procedure <procedure name>(parameter(s)) As Begin Statements End Execution: exec <procedurename> <parameters>
1) create a procedure to retrieve data from employee table Syntax: Create proc/procedure <procedurename> As Select * from <tablename> Ex: Create proc select_emp() As Select * from emp press F5 Execution: exec select_emp
Page 57
2) create a procedure to insert new row into emp table Syntax: Create proc/procedure <procedurename> (@parameter1 datatype, @parameter2 datatype, .. @parameter n datatype) As Begin Insert into <tablename>(columnname1,columnname2,.,columnname n) values(@parameter1, @parameter2,.., @parameter n) End Ex: Create proc insert_emp(@empno1 int,@ename1 varchar(10),@sal1 int) As Insert into emp values(@empno1,@ename1,@sal1) press F5 Execution: exec insert_emp 1002 , gaayu , 12000 3) Create a procedure to delete a row from emp table Syntax: Create proc/procedure <procedurename> (@parameter1 datatype) As Begin Delete from <tablename> where <condition> End Ex: Create proc delete_emp(@empno1 int)
Page 58
As Delete from emp where empno=@empno1 Press F5 Execution : exec delete_emp 1001 4) Create a procedure to update a column from emp table Syntax: Create proc/procedure <procedurename> (@parameter1 datatype, @parameter2 datatype, .. @parameter n datatype) As Begin Update <tablename> set columnname=<condition> where columnname=<condition> End Ex: Create proc update_emp(@empno1 int , @sal1 int) As Update emp set sal=sal+@sal1 where empno=@empno1 Press F5 Execution: exec update_emp 1002,1000 5) Create a procedure to verify user account info with the database Create proc checkuser(@uname varchar(10) , @pwd varchar(10) , @f int out) As Begin
Page 59
Set @f = (select count(*) from login where user_name=@uname and password=@pwd) End Press F5
TRANSACTIONS
Transaction can be defined as logical unit of work. It contains set of operations.Every transaction follows ACID. AAtomicity CConsistency IIsolation DDurability Atomicity: It guerrantees that if all the operations are completed successfully then only transaction is commited.If any operation is failed then transaction should be rollback. Consistency: It is nothing but providing correct data to the transaction.This can be achieved through Locks Isolation: The failure of ane transaction should not effect the another transaction in the system. Durability: The result of every commited transaction shold be persisted into the database server .This can be achieved through Log files. We have two types of transactions. Implicit transactions Explicit transactions Implicit transactions : Every DML statement creates one transaction implicitly.These transactions are Auto commit (no chance of rollback) To rollback the implicit transaction we have set state as ON
Page 60
Set implicit_transaction ON Delete from emp where deptno=10 Rollback transaction. Explicit transaction: We can create transactions explicitly by using TCL(Transaction control language) commands. TCL commands: Begin transaction Save transaction rollback transaction commit transaction Save point: It allows you to rollback the transactions upto particular statement.A transaction can have any number of save points. Ex: Begin transaction Update emp set sal=sal+500 where deptno=10 Save transaction p1 Declare @n int Delete from emp where deptno=20 Set @n=@@rowcount If @n>2 begin print sorry cannot be deleted print transaction cancelled Rollback transaction p1 End Commit transaction
Page 61
Page 62