<<

DATABASE

Database is an important constituent for collection and storage of data. Data provided information after processing on them. To managing record and important data server used. is a unit of work in database management system. Database transaction must follow term ACID (Atomicity, Consistency, Isolation, Durability). Any transaction started then till it completion, that transaction follow ACID, for successful and no error. The ability to modify the schema definition in one level should not affect the schema definition in the next higher level is called Data Independence. The application is independent of the storage structure and access strategy of data. Two types of Data Independence are:

1. Logical Data Independence: It is more difficult to achieve. Modification in logical level should affect the level. 2. Physical Data Independence: Modification in physical level should not affect the logical level.

ACID Property

Means atomicity, consistency, isolation and durability.

Atomicity: Each transaction is said to be “atomic". Means if any part of transaction fail then whole transaction failed. In a word say "ALL OR NOTHING". The failure of transaction commonly depend on Hard disk fail, System crash.

Consistency: Consistency means only valid data will be written to the database. If any transaction violate any consistency rule of database the whole transaction is Rollback, means it starts again beginning. Each state in transaction must be consistent for database.

Isolation: If two transactions occurs at a time then both are not impact to each other, separate completion of each transaction. The isolation property does not ensure which transaction will execute first, merely that they will not interfere with each other. If second transaction depend on first then it will done, and data after completion of traction.

Durability: Ensures that any transaction committed to the database will not be lost. Durability is ensured through the use of database backups and transaction logs that facilitate the restoration of committed transactions in spite of any subsequent software or hardware failures.

KEYS

A database key is a attribute utilized to sort and identify data in some manner. There are many keys:

1. : The primary key is a attribute of a relational uniquely identifies the each tuple of a table or each record in the table. It can either be a normal attribute that is guaranteed to be unique. Such as Social Security Number in a table with no more than one record per person. Examples: Imagine we have a employees table that contains a record for each employee at a organization. The employee's unique employee ID number would be a good choice for a primary key in the employees table. The employee's first and last name would not be a good choice, as there is always the chance that more than one employee might have the same name.

2. : These keys are used to create relationships between tables. Natural relationships exist between tables in most database structures. Example: Let’s assume that the Departments table uses the Department Name as the primary key. To create a relationship between the two tables, we add a new column to the Employees table called Department. We then fill in the name of the department to which each employee belongs. We also inform the database management system that the Department column in the Employees table is a foreign key that references the Departments table. The database will then enforce by ensuring that all of the values in the Departments column of the Employees table have corresponding entries in the Departments table.

3. , Alternate key and Composite key: Any number of attributes that are uniquely identifying a in a table is “candidate key” for the table. We one of the candidate key as Primary key. All candidate keys which are not chosen as "primary key" are “Alternate keys”. The key which uniquely identify the rows of the table and which is made up of more than one attribute is called “composite key”. For Example: In a class we have to select Class Representative. So A, B, C and D stand for that post. So A, B, C and D are candidate for Class Representative so these are candidate key. We select B as Class Representative so B is primary key and A, C and D can be Class Representative but not selected as a Class Representative so they are alternative choice. So A, C and D are alternate key. When two students of class work together in a project then they are composite key for the class.

LEVELS OF ABSTRACTION

Physical Level: Physical level is the lower level of abstraction. Its define how data is stored in database.

Logical Level: The next higher level of abstraction, its describe what data be store and each logical operation done at this level, links and concept apply here.

View Level: This is the higher level describe only part of entire database for a particular user.

NORMALIZATION

Some rules that should followed to achieve a good are:

1. Each table should have an identifier. 2. Each table should store data for a single type entity 3. Columns that should store data for a single type of entity. 4. The repetition of values or columns should be avoided.

To remove the redundancy of a table as called Normalization. In other words duplicity or repetitions of data never occur in database. Normalization is mainly minimizing redundancy, insertion, deletion and update anomalies. Normalization achieve through functional dependency. Normalization is much type.

Functional Dependency: Functional dependencies (FDs) are used to specify formal measures of the "goodness" of relational designs and used to define normal forms for relations. FDs are constraints that are derived from the meaning and interrelationships of the data attributes. FDs are derived from the real-world constraints on the attributes For example: A set of attributes X functionally determines a set of attributes Y if the value of X determines a unique value for Y X-->Y holds if whenever two tuples have the same value for X, they must have the same value for Y If t1[X] =t2[X], then t1[Y] =t2[Y] in any instance r(R) X-->Y in R specifies a constraint on all relation instances r(R)

Fully Functional dependency: A functional dependency X --> Y is full functional dependency if any attribute A removed from X. It means that the dependency does not hold any more then it is not Fully Functional dependence. Means each attribute is functionally dependent.

All categories are in sequential order: 1.1NF: There is no repetition of values and data in table known as 1NF. In other words the 1NF disallows composite attributes, multivalued attributes, and nested relations, attributes whose values for an individual tuple are non-atomic.

2.2NF: A relation schema R is in 2NF when it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key.

3.3NF: A relation schema R is in 3NF ,It is in 2NF and no non-prime attribute A in R is transitively dependent on the primary key. Transitive dependent means if there a set of attribute Z that are neither a primary or candidate key and both X-->Z and Y-->Z holds.

4.BCNF: 3NF inadequate in some situation then it was not satisfactory for the table:

1. That had multiple candidate keys. 2. Where the multiple candidate keys were composite. 3. Where the multiple candidate keys were overlapped.

A relation schema R is in BCNF, It is in 3NF and additional constraints that for every FD X -> A, X must be a candidate key. "A relation is in the Boyce-Codd normal form (BCNF) if and only if every determinant is a candidate key "

5.4NF: A relation schema R is said to be in 4NF, it is in BCNF and for every Multivalued dependency X --> Y that holds over R, Either X is subset or equal to (or) XY = R. or X is a super key.

6.5NF: A relation schema R is said to be in 5 NF, it is in 4NF and relation schema R is said to be 5NF if for every dependency {R1, R2, ..., Rn} that holds R, one the following is true Ri = R for some i. and The join dependency is implied by the set of FD, over R in which the left side is key of R. Demoralization

The intentional introduction of redundancy in a table in order to improve performance is called demoralization. The decision to demoralize results in a trade- off performance and . Demoralization increases disk utilization.

OTHER DATABASE MODELS

Relational

Data represent in form of column and row, column means attribute and row means touples present instance of data. This Database model came into existence with help of mathematical concepts. Its using some other concepts like normalization, touple .

E-R Model in Database

E-R model stands for Entity-Relationship model. This is based on real world that consists of basic objects called entities and of relationship among these objects. Entity in database, which existence in real world with number of attributes. In a table attribute know as column. Relationship is a logical thing which relates entities. The E-R diagram shows structure of E-R model.

Object Oriented Database Model

This model is based on collection of objects. An object is instance variables which store value and bodies of code, that codes are called method. These codes have written to operate the objects. Objects that contain same types of values and the same methods are grouped together into classes. In other words classes are a group of object. This model also follows the some concept related to the OOPs Hierarchical model of Database

The word hierarchy means tree form relationship, like a tree with branches. Means Relationship formed like tree structure in a database called hierarchical model. With this database you form relationship among many tables with certain concept. It has a downward link to describe the nesting and they are arranged in a particular order down the same level of the list.

Network model

This model provides greater flexibility and easy access to data. This model provide logical relationship among many parent database. But implementing this model is more difficult due to time consuming and cost. Its flexible because through link easily accessing of information.

XML Database

XML databases came into existence in 2000. This database lets you organize data irrespective of whether it is organized or not. This data can exported and serialized into the desired format. Two major classes of XML database exist: 1. XML-enabled 2. Native XML

Codd's Twelve Rules

1. The information rule: This rule require all information to be represented as data values in the rows and column of table.

2. The guaranteed access rule: Every data value in a relational database should be logically accessible by specifying a combination of table name and column name.

3. Systematic treatment of NULL values: DBMS support NULL values ,in case when user leave the column in the table.

4. Active online catalog based on : DBMS maintain system catalog. System catalog is a collection of system table.

5. The comprehensive data rule: System must support following functions :

1. Data definition 2. View definition 3. Data manipulation operation 4. Security and integrity constraints 5. Transaction management operation

6. The view update rule: All views that are theoretically updated must be updated by the system.

7. High level , update and : Means update at a time many rows values. Data are treated as set ,which are easily delete, update and insert. 8. Physical data independence: Application programs must remain unimpaired when any changes are made in storage representation or across methods.

9. Logical data independence: Changes should not affect the user's ability to work with the data.

10. Integrity independence: Integrity constraints must be storable in the system catalog.

11. Distribution independence: Database must allow manipulation of distributed data located on different computer system.

12. Nonsubversion rule: This rule state that different language bypass the integrity rule and constraints

MS SQL Server

Fully Web Enabled

You can use HTTP to send queries to the server. It provides various feature and facility to accesses data on web.

Highly Scalable and Reliable

SQL sever use scale up and scale out feature to fulfill requirement . In Scale up SQl server use 32 bit Processors and 64GB of RAM to increase the load. In scale out SQL distribute database and data load across the server. When suddenly system crash ,RDBMS recover data quickly with minimum loss. This feature called reliability.

Client Server Architecture (Two Tier Architecture)

Data Sharing, Reduce Duplication and maintenance

SQL

• Language to access data object from the SQL server • Stands for Structured • SQL addresses data in sets of rows and column rather than addressing individual component or a single data • SQL support automatic navigation to target the data means user find data without knowing how to get this data and how to store the data • Using this user never waste the time on representation of data, user only concentrate on logic

Data types

Dtatype Range Used to store -2^31 (-2,147,483,648) to 2^31 - int Integer data (whole numbers) 1 (2,147,483,647) -2^15 (-32,768) to 2^15 - 1 smallint Integer data (32,767) tinyint 0 to 255 Integer data -2^63 (- 9,223,372,036,854,775,808) to bigint Integer data 2^63-1 (9,223,372,036,854,775,807) float -1.79E + 308 to 1.79E + 308 Floating precision data -2^63 (-922,337,203,685,477.5808) money to 2^63 - 1 Monetary data (+922,337,203,685,477.5807) smallmoney -214,748.3648 to +214,748.3647 Monetary data January 1, 1753, to December 31, datatime Date and time data 9999 smalldatatimeJanuary 1, 1900, to June 6, 2079 Date and time data n characters, n can be 1 to char(n) Fixed length character data 8000 n characters, where n can be 1 to varchar(n) Variable length character data 8000 Maximum length of 2^31 - 1 text Character string (2,147,483,647) characters Maximum length of 2^30 - 1 ntext Variable length Unicode data (1,073,741,823) characters bit 1 or 0 value Integer data with 0 or 1 Maximum length of 2^31 - 1 Variable length binary data to image (2,147,483,647) bytes store images real -3.40E + 38 to -1.18E - 38 Floating precision number binary Maximum length of 8,000 bytes Fixed length binary data varbinary Maximum length of 8,000 bytes Variable length binary data nchar Maximum length of 4,000 characters Fixed length Unicode data nvarchar Maximum length of 4,000 characters Variable length Unicode data Contain rows of different sql_varient Maximum storage size of8016 bytes datatypes except text, ntext, image, timestamp and sql_variant unique number in a database that timestamp Maximum storage size of 8 bytes get updated every time a row that contains it is inserted or updated

1. DDL () 2. DML (Data manipulation language) 3. DCL and TCL 4. Displaying Rows Using Logical & List Operators 5. Displaying Rows Using Comparison & Range Operators 6. Displaying Rows Using String Operator 7. IS NULL and IS NOT NULL keywords & Clause 8. Limits the rows by using 9. TOP keyword & DISTINCT keyword 10. Using Aggregate Functions 11. Using GROUP BY Clause 12. Using COMPUTE BY Clause 13. Using String Functions 14. DATE Functions 15. Mathematical Functions 16. Some System Functions 17. Joins 18. Inner Join 19. Outer Join 20. Cross Join 21. Equi Join 22. Natural Join 23. Self Join 24. Sub queries with EXITS Clause 25. Queries with modified Comparison Operators 26. Extracting Data Into Another Table 27. Using UNION Operator 28. How to create a Data Base in SQL server 29. .mdf, .ndf and .ldf extension files 30. Viewing, Renaming and Deleting a Database 31. Data Integrity 32. Creating Constraints 33. PRIMARY KEY Constraint 34. The UNIQUE Constraint 35. The FOREIGN KEY Constraint 36. The CHECK Constraint 37. The DEFAULT Constraint 38. INDEXES 39. CLUSTERED Index 40. NONCLUSTERED Index 41. How to Create an Index 42. Programming in SQL Server 43. The IF...ELSE Statement and BEGIN...END Statement 44. The CASE statement and WHILE statement 45. Stored Procedures 46. How To Create

DDL (Data Definition Language)

Data Definition Language (DDL) statements are used to define the database structure or schema. DDL statements are used to build and modify the structure of your tables and other objects in the database. When you execute a DDL statement, it takes effect immediately.

1. CREATE: To create objects in the database

CREATE TABLE ( , ... );

2. ALTER: Alters the structure of the database

ALTER TABLE ADD CONSTRAINT PRIMARY KEY ();

The foreign key constraint is a bit more complicated, since we have to specify both the Foreign Key attributes in this (child) table, and the Primary Key attributes that they link to in the parent table.

ALTER TABLE ADD CONSTRAINT FOREIGN KEY () REFERENCES ();

DROP: Delete objects from the database

DROP TABLE ;

ALTER TABLE DROP CONSTRAINT ;

4. TRUNCATE: Remove all records from a table, including all spaces allocated for the records are removed

5. COMMENT: Comments added to the .

6. RENAME: Rename an object of the Database DML (Data manipulation language)

.DML statements are used to work with the data in tables. SELECT, INSERT, UPDATE, DELETE statements are consider as a DML statement.

1. SELECT: SQL server provide the SELECT statement to retrieve data from database. The keywords SELECT, FROM and WHERE makeup the basic SELECT statement . SELECT statement promote the server to querying single table or multiple tables in Database and prepare a result and return to the client application.

Selecting Columns

The column name from a table specified in the SELECT statement separated by a comma (,) and there is no need to insert a comma after the last column name.

SELECT column_name 1,column_name 2....column_name n FROM table_name

The above query retrieve the column data which you pass in the query from table which you pass after From keyword.

Selecting All Columns

The SELECT statement used with an asterisk (*) symbol to display all column of the table

SELECT * FROM table_name

2. INSERT: The insert statement is used to add new rows to a table. There will need a separate INSERT statement for every row. The statement of Insert will be:

INSERT INTO table_name VALUES (value 1, ... value n);

• The number of attributes and the data type of each attribute • Character type values are always enclosed in single quotes • Number values are never in quotes • Date values are often in the format 'yyyy-mm-dd' (for example, '2010- 12-24')

3. UPDATE: The update statement is used to change values that are already in a table.

UPDATE table_name SET attribute_name 1 = value 1, attribute_name 2 = value 2....attribute_name n = value n WHERE ; • If the WHERE clause is omitted, then the specified attribute is set to the same value in every row of the table • Set multiple attribute values at the same time with a comma-delimited list of attribute_name=value pair

DELETE: The delete statement does just that, for rows in a table.

DELETE FROM table_name WHERE condition;

If the WHERE clause is omitted, then every row of the table is deleted

5. CALL: Call a PL/SQL

6. EXPLAIN PLAN: Explain access path to data

7. LOCK TABLE: Control concurrency

DCL ()

• DCL stands for Data Control Language • Used to create roles • Used to create permissions

1. GRANT: Gives user to access database means user privilege to database.

2. REVOKE: Withdraw access privileges given with the GRANT command

TCL (Transactional Control Language)

• TCL is stands for Transactional Control Language • It is used to manage different transactions occurring within a database

COMMIT: This Statement used to save work done by the user.

2. SAVEPOINT: Identify the point which you can later roll back in a transaction.

3. ROLLBACK: Restore database to original.

4. SET TRANSACTION: Change transaction options like isolation level and what rollback segment to use

Using Logical Operator

Multiple search condition done by using logical operator. They are:

1. OR: Any of the specified search condition is true. SELECT column_list FROM table_name WHERE condition_expression OR condition_expression

Return all rows specific to the conditions, even if any one of the condition is true.

2. AND: When all specified search conditions are true.

SELECT column_list FROM table_name WHERE condition_expression AND condition_expression

Return all rows specific to the conditions, when both conditions are true.

3. NOT: Neutralizes the expression that follow it.

SELECT column_list FROM table_name WHERE condition_expression {OR/AND} NOT condition_expression

Return all rows specific to the conditions, except the rows that match the condition specified after the NOT operatoor.

Using List Operator

SQl provides IN and NOT IN operators. IN operator that allowed the selection of values that match any one of the values in a list. NOT IN operator restrict the selection of values that match any one of the values in a list.

SELECT column_list FROM table_name WHERE condition list_operator('value_list') list_operator is any valid list operator. value_list is the list of values to be included or excluded in the condition

For Example:

SELECT * FROM publishers WHERE state IN ('MA','DC')

SELECT * FROM publishers WHERE state NOT IN ('MA','DC')

Using Comparison Operators Comparison operator allow row retrieval from a table based on the condition specified in the WHERE clause.

SELECT column_list FROM table_name WHERE expression1 comparison_operator expression2

Operator Description = Equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to <>,!= Not equal to !> Not greater than !< Not less than () Controls precedence

For Example:

SELECT pub_id FROM publishers WHERE city='Boston'

Using Range Operators

The range operator is used to retrieve data between range . The range operator are:

1. BETWEEN: Specified an inclusive range to search.

SELECT column_list FROM table_name WHERE expression1 BETWEEN expression1 AND expression1

For Example: Below query return the attribute list value between 2000 and 5000

SELECT * FROM titles WHERE advance BETWEEN 2000 AND 5000

2. NOT BETWEEN: This key word used to exclude the rows from the specified range in the result set.

SELECT column_list FROM table_name WHERE expression1 NOT BETWEEN expression1 AND expression1 For Example: Below query return the attribute list value which not between 2000 and 5000

SELECT * FROM titles WHERE advance NOT BETWEEN 2000 AND 5000

Using String Operator

String operator provide a LIKE keyword to search for a string with wild card mechanism.

Wildcard Description % Represents any string of Zero or more character _ Represent the single character [] Represent any single character within the specified range [^] Represent any single character not within the specified range

For Example:

SELECT * FROM titles WHERE type LIKE 'bus%'

Return all attribute from the titles table in which the type starts with 'bus'

SELECT * FROM titles WHERE type LIKE 'bu_'

Return all attribute from the titles table in which the type of book is the three character long and starts with 'bu'. Increase the '_' keyword increase the number of characters.

SELECT * FROM titles WHERE type LIKE 'b[us]%'

Return all attribute from the titles table in which the type of book is starts with 'b' and contain u and s on the second position followed by any number of character.

SELECT * FROM titles WHERE type LIKE 'b[^s]%' Return all attribute from the titles table in which the type of book is starts with 'b' and does not contain s on the second position followed by any number of character.

Some Examples

Expression Returns LIKE '%ty%' All names that have the letters 'ty' in them LIKE '_ty' All three letter names ending with 'ty' LIKE '[AD]%' All name that begin with "A" or "K"

Using IS NULL & IS NOT NULL

In SQL server, NULL is a unknown value means the data is not available. The NULL can be retrieve from the table using IS NULL keyword in the WHERE clause.

Note: NO two NULL values are equal. You can not compare one NULL value to other.

SELECT column_list FROM table_name WHERE column_name unknown_value_operator

Where unknown_value_operator is either the keyword IS NULL or IS NOT NULL.

Example:

SELECT * FROM publishers WHERE state IS NULL

Returns the all attributes of publisher table where state attribute contain NULL

SELECT * FROM publishers WHERE state IS NOT NULL

Returns the all attributes of publisher table where state attribute does not contain NULL

Using ORDER BY Clause

It retrieve and display the data in specific order. ASC is the default sort order.

SELECT column_list FROM table_name ORDER BY column_name ASC/DESC For Example:

SELECT * FROM publishers ORDER BY pub_name DESC

Return all attributes of publishers able in order to descending alphabetically order with respect to pub_name attribute

Using TOP keyword

The TOP clause used with the SELECT statement. It is used to limits the number of rows returned in the result set

SELECT [TOP n] column_mame FROM table_name WHERE search_conditions

'n'=number of rows that you want to retrieve.

For Example:

SELECT TOP 5 pub_id,pub_name,country FROM publishers WHERE country LIKE 'U%' ORDER BY pub_id DESC

Returns all top 5 rows ,pub_id, pub_name and country, from the publishers table in descending order with respect to pub_id.

Using DISTINCT keyword

It also used to limit the result set. The DISTINCT keyword remove the duplicate row from the returned result set. It used with the SELECT statement.

SELECT DISTINCT column_mame FROM table_name WHERE search_conditions

For Example:

SELECT DISTINCT country FROM publishers WHERE city LIKE 'B%'

Return country name which started with a 'B' alphabet but no repetition, means no duplicate value of country.

Using Aggregate Functions These function are specially executed for the mathematical expression.

Function Parameters Description Name (ALL, DISTINCT Return the average of value in a numeric AVG Expression) expression (ALL, DISTINCT Return the number of values in an COUNT Expression) expression Returns the no. of rows returned by the COUNT (*) query MAX (expression) Return the highest value in the expression MIN (expression) Return the lowest value in the expression (ALL, DISTINCT Return the total of value in a numeric SUM Expression) expression

The AVG, COUNT, MAX, MIN and SUM function ignore NULL values, whereas the COUNT (*) function counts the NULL values

Examples Description SELECT 'avg'=AVG (discount) Returns the average value of the discount FROM discounts SELECT 'sum'=SUM (discount) Returns the sum value of the discount FROM discounts SELECT 'min'=MIN (discount) Returns the minimum value of the discount in FROM discounts discounts table SELECT 'max'=MAX (discount) Returns the maximum value of the discount in FROM discounts discounts table SELECT 'count'=COUNT Return the number of discount value in discounts (discount) table FROM discounts

Using GROUP BY Clause

Group clause summarize the result set in to a groups defined in the query using aggregate function.

SELECT column1, column2, ... column_n, aggregate_function (expression) FROM table_name WHERE conditions GROUP BY ALL column1, column2, ... column_n

expressions describe the column name (s) or expressions on which the result set of the SELECT statement is to be grouped.

ALL is a keyword used to include those groups that do not meet the search condition. For Example:

SELECT type, 'avg'=AVG(advance) FROM titles WHERE type LIKE 'b%' GROUP BY ALL type

Out Put type avg ------business 5000.0000 mod_cook NULL popular_comp NULL psychology NULL trad_cook NULL UNDECIDED NULL

Return all type from table but the 'avg' display only those type which started with ' b'. Means this keyword used to display all groups, including those exclude from WHERE clause. The ALL keyword is meaningful for those query that contain WHERE clause.

For Example:

SELECT type,'pub Id'=pub_id, 'avg'=AVG (price) FROM titles GROUP BY type,pub_id

Return the 'type' and 'pub Id' and 'avg' , which calculated from titles table.

For Example:

SELECT type, 'avg'=AVG(advance) FROM titles WHERE title_id IN ('BU1032','PC1035') GROUP BY ALL type

Out Put type avg ------business 5000.0000 mod_cook NULL popular_comp 7000.0000 psychology NULL trad_cook NULL UNDECIDED NULL

Using COMPUTE Clause • Used to generate summary rows using aggregate function in the query results. • COMPUTE BY clause can be used to calculate summary values of the result set on a group of data. • The main difference between GROUP BY and COMPUTE BY Clause is, GROUP BY Clause is used to generate a group summary report and does not produce individual table rows in the result set whereas COMPUTE BY Clause generate the summary report with individual data rows from the table.

SELECT column_name FROM table_name ORDER BY column_name COMPUTE aggregate_function (column_name) BY column_name 1...column_name n

For Example:

SELECT type, advance FROM titles ORDER BY type COMPUTE AVG (advance) BY type

Out Put

Some points regarding the use of the COMPUTE and COMPUTE BY

• The DISTINCT keyword cannot be used with the aggregate function • All columns referred to in the COMPUTE clause must appear in the select column list • The ORDER BY Clause must be used whenever the COMPUTE BY Clause is used • The ORDER BY Clause can be eliminate only when the COMPUTE BY Clause is used • The column listed in the COMPUTE BY Clause must match the columns used in the ORDER BY Clause • More than one COMPUTE clause can be used in the SELECT statement to produce a result with subtotals and grand total • The different aggregate function can be used on more than one column with the COMPUTE BY Clause • More than one column or expression can be specified after the COMPUTE BY clause. The order of columns or expression used in the COMPUTE BY clause must match the order of columns or expression specified in the ORDER BY Clause.

Using String Functions

This function use to format data that will meet specific requirements. Mostly they are used with the char and varchar data types. It used for implicit convert data to char to varchar.

SELECT function_name (parameter) function_name is the name of the string function. parameter are required parameters for the string function.

Function Parameters Example Description name Return 65 the ASCII ASCII (character_expression) SELECT ASCII ('ADI') code of the leftmost character 'A' Return A the character CHAR (integer_expression) SELECT CHAR (65) equivalent of the ASCII code value Returns 5, the standing SELECT position of the specified CHARINDEX ('pattern', expression) CHARINDEX ('O','HELLO') pattern in the expression Return the four SELECT SOUNDEX (character_expression) character code to SOUNDEX ('ADITYA') compare the string DIFFERENCE(character_expression1 SELECT Difference function , DIFFERENCE ('ADITYA','ADI') compare the SOUNDEX character_expression2) value of two string and return a value from 0 to 4. The value 4 is best match. Return 'ADIT', which is the part of character (character_expression, SELECT LEFT string equal in size to integer_expression) LEFT ('ADITYA','4') the integer_expression character from the left Return 6, the no of LEN (character_expression) SELECT LEN ('ADITYA') character in the (character_expression) Return 'aditya', after the converting LOWER (character_expression) SELECT LOWER ('ADITYA') (character_expression) to the lower case Return 'ADITYA' without leading spaces. LTRIM (character_expression) SELECT LTRIM (' ADITYA') It removes leading blanks from the character expression Return 4, the standing position of the first ("%pattern%, SELECT occurrence of the PATINDEX expression") PATINDEX ('%TY%','ADITYA') pattern in the specified expression, or zero if pattern is not found Return 'AYTIDA' , the SELECT REVERSE (character_expression) reverse of the REVERSE ('ADITYA') (character_expression) (character_expression, SELECT Return 'ITYA' , the part RIGHT integer_expression) RIGHT ('ADITYA',4) of the character string. Return 'ADITYA' without leading spaces. RTRIM (character_expression) SELECT LTRIM ('ADITYA ') It removes leading blanks from the character expression Returns 'ADITYA TIWARI'. Two space SELECT SPACE (integer_expression) are inserted between 'ADITYA'+SPACE(2)+'TIWARI' the first and second word STR (float_expression, SELECT STR (123.45,6,2) Return '123.45'. It [length,[decimal]]) converts numeric data to character data where the length is the total length ,including the decimal point, the sign, the digits, the spaces and the decimal is the number of places to the right of the decimal point

Return 'Asya'. It delete length characters from character_expression1 (character_expression1 from the start and then , SELECT STUFF STUFF inserts start, length, ('Aditya',2,3,'s') character_expression2 character_expression2) into character_expression1 at the start position Returns 'dit', which is part of a character (expression, start, SELECT SUBSTRING string. It returns length SUBSTRING length) ('Aditya',2,3) character from the start position of the expression Return 'ADITYA', after the converting UPPER (character_expression) SELECT UPPER ('aditya') (character_expression) to the upper case

Using DATE Functions

Date function of SQL is:

• Used to manipulate date time values • Perform arithmetic operations • Perform date parsing • Add two date or subtract one date from another

SELECT date_function (parameters)

date_function is the name of date function

parameters are the required parameters of the date function

Function Parameter Description Name (datepart,number,date DATEADD Adds the number of dateparts to the date ) Calculates the number of dateparts between two DATEDIFF (datepart,date1,date2) dates Return datepart from the listed date, as character DATENAME(datepart,date) value (for example: March) DATEPART (datepart,date) Returns datepart from the listed date as an integer GETDATE () Returns current date and time

For Example:

SELECT getdate()

The above statement display the current system date by using getdate() function.

SELECT 'getdate'= DATEADD(yy,2,pubdate) FROM titles

Return the all pubdate from titles table with increment of 2 in each year of the table.

SELECT datepart (yy,pubdate) FROM titles

Return all Date from pubdate of titles table.

Using Mathematical Functions

Mathematical function perform numerical operation on mathematical data. The various mathematical functions are:

Function Name Parameter Description (numeric_expression ABS Return an absolute value ) ACOS,ASIN, ATN (float_expression) Returns the angle in radians whose cosin,sin and tangent is a floating point value Returns the angle in radians whose cosin, COS,SIN,COT,TAN(float_expression) sin, tangent and cot of the angle (numeric_expression Returns the smallest integer greater than or DEGREES ) equal to the specified value Return the exponential value of the specified EXP (float_expression) value (numeric_expression Return the largest integer less than or equal FLOOR ) to the specified value. Return the natural logarithm of the specified LOG (float_expression) value Return the base-10 logarithm of the specified LOG10 (float_expression) value Returns the constant value of PI () 3.141592653589793 (numeric_expression, Return the value of numeric_expression to POWER y) the value of y (numeric_expression RADIANS Convert from degrees to radians ) Return a random float number between 0 and RAND ([seed]) 1 (numeric_expression, returns a numeric expression rounded off to ROUND length) the length specified as an integer expression (numeric_expression SIGN Returns positive, negative or zero ) SQRT (float_expression) Return the square root of the specified value

ROUND (numeric_expression,length)

numeric_expression is the numeric expression to be round off

SELECT 'value'= ROUND (123.452352,3)

Out Put:

Using System Functions

System function provide a method of querying the system tables of SQL server. Function Definition Returns the current host process ID number of a client HOST_ID() process Return the current host computer name of a client HOST_NAME() process Return the user's login name corresponding to the user's SUSER_SID(['login_name']) security identification number Return the database identification number corresponding USER_ID(['name_in_db']) to the username Return the user name corresponding to the database USER_NAME(['user_id']) identification number DB_ID (['db_name']) Return the database ID number of the database DB_NAME(['db_id']) Returns the database name OBJECT_ID ('objname') Returns the database object ID number OBJECT_NAME('object_id') Returns the database object name

JOINS

SQL server provide:

• A method to retrieving a data from more than one table using join at a time • Implemented using SELECT statement, in which the SELECT statement contain the name of columns to be retrieve from the tables • The FROM clause contains the name of the tables from which combined data is to be retrieved • The WHERE specifies the rows to be included in the result set with the help of the join operator

Syntax:

SELECT column name 1, column name 2....column_name n FROM table name [CROSS, INNER, OUTER] JOIN table_name ON [table_name.ref_column_name] join_operator [table_name.ref_column_name] WHERE search_condition column_name specifies the name of the columns from one or more than one table that has to be displayed. table_name specifies the name of the tables from which data to be retrieve. ref_column_name specifies the name of the columns that are used to combined the two tables using the common keys from the respective tables. join_operator specifies the operator used to join the tables When two tables are joined, they must share a common key that defines how the rows in the tables correspond to each other. A primary key is validated against the foreign key when a joined is used.

Whenever a column is referred to in a join condition, it should be referred to either by prefixing it with the table name to which it belongs or by a table .

Table Alias: A table alias is required whenever an ambiguity is possible due to duplicate column names in a multiple tables A tables alias is a keyword defined in the FROM clause of the SELECT statement to uniquely identify the table.

Syntax:

FROM table_name table_alias

Where, table_name specifies the name of the tables that have to be combined in the query table_alias is the keyword used to refer to a table. It must follow the rules of identifiers

Types of JOIN

Inner Join Outer Join Cross Join Equi Join Natural Join Self Join

Inner Join

In inner joining, data from multiple tables is displayed after comparing values present in a common column. Only rows with values satisfying the join condition column are displayed. Rows in both tables that do not satisfy the join condition are not displayed.

SELECT columnm_name FROM table_name JOIN table_name ON [table_name.ref_column_name] join_operator [table_name.ref_column_name]

For Example:

SELECT title, royaltyper, royalty FROM titleauthor JOIN titles titleauthor.title_id=titles.title_id

Return all title, royaltyper, royalty from table in which these attributes are present Outer Join

An outer join displays NULL for the columns of the related table where it does not find matching records

• When the result set contains all rows from one table • The matching rows from other

SELECT columnm_name 1, columnm_name 2....columnm_name n FROM table_name [LEFT,RIGHT] OUTER JOIN table_name ON [table_name.ref_column_name] join_operator [table_name.ref_column_name]

Left Outer Join: Left outer join ensure the inclusion of rows the first table and the matching rows from the second table.

SELECT logo,price,notes FROM pub_info p LEFT OUTER JOIN titles t ON p.pub_id=t.pub_id Right Outer Join: Right outer join ensure the inclusion of rows the second table and the matching rows from the first table.

SELECT logo,price,notes FROM pub_info p RIGHT OUTER JOIN titles t ON p.pub_id=t.pub_id

Cross Join

• A join that included more than one table using keyword CROSS is called cross join • The output of a such type of join is called Cartesian product • In cross join each row of first table is joined to with the each row of second table • The number of rows in the result set is the multiple of the first table rows and second table rows

SELECT column_name 1, column_name 2....column_name n FROM table_name CROSS JOIN table_name

For example:

SELECT * FROM sales CROSS JOIN publishers

returns 168 rows, after cross join 21 rows of sales table and 8 rows of publishers tables

Equi Join

A equi join display redundant column of data in the result set, where two or more tables are compared for equality.

For Example: SELECT * FROM sales s JOIN titles t ON s.title_id=t.title_id JOIN publishers p ON t.pub_id=p.pub_id

Returns the above columns in the result set.

Natural Join

A join that restrict the redundant column from the result set is known as natural join

SELECT t.title, p.pub_name FROM titles t JOIN publishers p ON t.pub_id=p.pub_id

Returns the all title and pub_name from respective tables.

Self Join

A join is said to self join when one row in a table correlates with the other rows in the same table. An alias name can differentiate the two copy of the table. All join operators except the outer join operators can be used in a self join.

For Example:

SELECT t1.title, t2.title, t1.price FROM titles t1 JOIN titles t2 ON t1.price=t2.price WHERE t1.price=2.99

Using EXITS Clause

A sub query used with the EXISTS clause, always returns data in terms of a TRUE or FALSE value. It checks for the existence of a data rows according to the condition specified in the inner query and passes the existence status to the outer query to produce the result set.

For Example: SELECT pub_name FROM publishers WHERE EXISTS (SELECT * FROM titles WHERE type='business')

Out Put

Display the name of publishers who publish business related books.

SELECT title FROM titles WHERE advance > (SELECT avg(advance) FROM titles WHERE type='business')

Out Put

Display the titles of all those books for which the advance amount is greater than the average advance for bussiness related books.

Queries with modified Comparison Operators

SQL server provides the ALL and ANY keywords that can be used to modify the existing comparison operator. The sub query introduced with a modified comparison operator returns zero or more values and can be implemented using the GROUP BY or HAVING clause.

Operator Description >ALL Means greater than the maximum value in the list. column_name>ALL (10,20,30) means 'greater than 30' Means greater than the minimum value in the list. >ANY column_name>ANY (10,20,30) means 'greater than 10' Means any of the values in the list. It acts in the same way as the IN clause =ANY column_name=ANY (10,20,30) means 'equal to either 10 or 20 or 30' Means not equal to any in the list. <>ANY column_name<>ANY (10,20,30) means 'not equal to either 10 or 20 or 30' Means not equal to all the values in the list. It acts in the same way as the NOT IN clause. <>ALL column_name<>ALL (10,20,30) means 'not equal to either 10 and 20 and 30'

For Example:

SELECT title_id ,title FROM titles WHERE price> ALL (SELECT price FROM titles WHERE pub_id='0736')

Out Put:

Display the title_id and title where price is greater than the maximum price of books published by the publisher with the publisher ID 0736

SELECT title_id ,title FROM titles WHERE price>ANY(SELECT price FROM titles WHERE pub_id='0736') Display the title_id and title where price is greater than the minimum price of books published by the publisher with the publisher ID 0736

Extracting Data Into Another Table

A SELECT statement with the INTO clause is used to store the result set in a new table without a data definition process. The SELECT INTO statement creates a new table.

If the table is already exists, then the operation fails.

The command syntax is the,

SELECT columns_list INTO new_table_name FROM table_name 1, table_name 2.. table_name n WHERE condition 1, condition 2..condition n

Where coloumn_list is the list of columns to be included in the new table. new_table_name is the name of the new table where data is to be stored. condition is the conditions on which rows are to be included in the new table.

For Example:

Create a new table from the title table.

SELECT title_id ,title INTO aditya FROM titles WHERE price>15

(8 row(s) affected)

SELECT * FROM aditya

A new table created named aditya

Using UNION Operator

SQL server provide a unique operator known as the UNION operator that is used to combine the result set of two or more queries.

SELECT column_list [ INTO new_table_name] [FROM clause] [WHERE clause] [GROUP BY clause] [HAVING clause]..] UNION [ALL] SELECT column_list [FROM clause] [WHERE clause] [GROUP BY clause] [HAVING clause]..] [ORDER BY clause] [COMPUTE BY clause]

UNION ALL is the operator used to combine two or more queries with duplicate rows from different queries.

For Example:

SELECT au_fname,city,state FROM authors WHERE state='UT' UNION SELECT pub_name,city,state FROM publishers

Out Put:

How to create a Data Base in SQL server

The creation of a database involves the database and determining the size of the database and the files used to store data in the database.

CREATE DATABASE database_name ON [...n] [...n] LOG ON (NAME=logical_file_name, FILENAME='os_file_name', SIZE=size, MAXSIZE=max_size, FILEGROWTH=growth_increment) where, data_base name is the name of new database.

ON specifies the disk files used to store the data portion of the database.

NAME=logical_file_name specifies the logical name for the file.

FILENAME=os_file_name specifies the operating system file name.

SIZE=size specifies the initial size f the file defined in the () list.

MAXSIZE=max_size specifies the maximum size to which the file defined in the list can grow.

FILEGROWTH=growth_incremet specifies the growth increament of the file defined in the list. FILEGROUP filegroup_name name specifies the name of the filegroup.

LOG ON specifies the disk files used to store the log files.

For Example:

CREATE DATABASE aditya ON (NAME=aditya_dat, FILENAME='C:\Program Files\Microsoft SQL Server\MSSQL\DATA\aditya.mdf', SIZE=12, MAXSIZE=100, FILEGROWTH=2) LOG ON (NAME='aditya_log', FILENAME='C:\Program Files\Microsoft SQL Server\MSSQL\DATA\aditya.ldf', SIZE=4 MB, MAXSIZE=50 MB, FILEGROWTH=2 MB)

Out Put:

The CREATE DATABASE process is allocating 12.00 MB on disk 'aditya_dat'. The CREATE DATABASE process is allocating 4.00 MB on disk 'aditya_log'.

Aditya named database created

.mdf, .ndf and .ldf EXTENSIONS FILES

.mdf Extension

• When we create a database, the CREATE command create a data file with extension .mdf is a primary file. • It is a SQL Data files where all the data in the database objects are stored in • Like tables, stored procedures, views, triggers etc. All are stored in the .mdf file of server • This is the reason whey we use .MDF file to attaché the database. Once we attach the .mdf we were able to see all the data exist in that respective database.

..ldf Extension

• .ldf is the log file in the SQL server to see the data • file with extension .ldf • The size of the log file (ldf) is determined my the logging level you have set up on the database • Simple, full, and build logged are the options • Simple being the least, and full being the most, the logged (if in full) will allow you to re-apply transactions to the database incase of a failure • If your looking for some performance improvement, there are a lot of things that can be done

.ndf Extension

• .ndf are secondary databse files • Same as mdf, but you can only have 1 Main database file • This file also could be stored on a separate physical drive • Advantage is that, tables that are relatively static are in another file • Tables that are written frequently are stored in one file • Having to smaller file to write to for transactions will help with throughput.

Viewing, Renaming and Deleting a Database

Viewing a Database

The information regarding database such as owner, size, date of creation, and status can be viewed using the following: sp_helpdb database_name

For Example: sp_helpdb aditya

Renaming Database The name of database can be changed. The database should not be in use when it is being renamed, and it should be set to the single-user mode. sp_rename 'old_name','new_name' where, old_name is the original name of the database new_name is the new name of datbase

Only system administrator can changed the name of a database.

Deleting a Database

A database is deleted when it is no longer required. Only the system administrator and database owner have permission to delete a database.

DROP DATABASE database_name where, database_name is the name of the database

DATA INTEGRITY

There are three most important things when database is accessing:

• Accurate • Consistent • Reliable , means its very tuff to maintain data integrity.

Data integrity ensures the consistency and correctness of data stored in a database. It is broadly classified into the following four categories:

Entity Integrity

Entity integrity ensures that each row can be uniquely identified by an attribute called the primary key. The primary key can not be NULL. For example: there might be two candidates for interview with the same name 'alok'. they can be identified using the unique code assigned to them.

Domain Integrity

Domain integrity ensures that only a valid range of values is allowed to be stored in a column. It can be enforced by restricting the type of data, the range of values, and the format of data.

For Example: Let assume that table BranchOffice, that contain various offices of a company and this table has another column city that store the cities where branch offices are located. Assume that offices are located in 'Delhi', 'Mumbai', 'Chanai'. By enforcing the integrity we ensure that only valid values can be entered in the city column of the BranchOffice table. Referential Integrity

Referential Integrity ensures that the values of the foreign key match with the value of the corresponding primary key.

For Example: In a CollegeStudent table each student has there enrollment number in the column, another table in university database is UniversityStudent which contain Enrollment number that make ensure registration of each student.

User-defined Integrity

User-defined integrity refers to a set by a user, which do not belong to the entity, domain, and referential integrity categories.

For Example: If you want a candidate who is less than 18 years to apply for a post.

CREATING CONSTRAINTS

Constraints can be be enforced at two levels.

• Column level • Table level

A constraints can be defined on a column at the time of creating a table. It can be created with the CREATE TABLE statement.

1. CREATE TABLE statement:

CREATE TABLE table_name column_name CONSTRAINTS constraints_name constraints_type [, CONSTRAITS constraints_name constraints_type] where, column_name is the name of the column on which the constraints is to be defined. constraints_name is the name of the constraints to be created and must follow the rules for the identifier. constraints_type is the type of constraints to be added.

2. ALTER TABLE statement:

ALTER TABLE table_name [WITH CHECK or WITH NOCHECK] ADD CONSTRAINTS constraints_name constraints_type where, table_name is the name of the table that is to be altered for adding a constraints. WITH CHECK and WITH NOCHECK specifies whether the existing data is to be checked or not checked for a newly added constraints or a re-enabled constraints constraints_name specifies the name of the constraints to be created and must follow the rule for identifier. constraints_type specifies the type of constraints.

DROPPING CONSTRAINTS

A constraints dropped using the ALTER TABLE statement in the Query Analyzer.

All constraints defined in the table are dropped automatically when the table is dropped

ALTER TABLE table_name DROP CONSTRAINTS constraints_name where, table_name is the name of the table that constraints to be dropped. constraints_name is the name of the constraints to be dropped.

TYPES OF CONSTRAINTS

[1] PRIMARY KEY constraints

[2] UNIQUE constraints

[3] FOREIGN KEY constraints

[4] CHECK constraints

[5] DEFAULT constraints

PRIMARY KEY constraints

A Primary Key constraints is defined on a column whose values uniquely identify rows in a table. These columns are referred to as the primary key columns. A primary key column can not contain NULL values since it is used to uniquely identify rows in a table. the primary key ensure entity integrity.

You can define a PRIMARY KEY constraints at the time of a table creation, or you can add it later by altering the table. While defining a PRIMARY KEY constraints, you need to specify a name for the constraints. If a name is not specified, SQL server automatically assigns a name to the constraints.

CREATE TABLE table_name (column_name data_type CONSTRAINT constraints_name PRIMARY KEY),..

For Example: CREATE TABLE employee (emp_name char (4) CONSTRAINT pfemp_name PRIMARY KEY)

The above command creates a table employee with emp_name as the primary key. The name of the constraints is pfemp_name.

Out Put

Primary key also created after creating a table by following command:

ALTER TABLE employee ADD CONSTRAINT Pfemp_name PRIMARY KEY (emp_id)

For Example: