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 Databases server used. Database transaction 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 view 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 from 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 update 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. Primary key: The primary key is a attribute of a relational table 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. Foreign Key: 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 column 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 referential integrity by ensuring that all of the values in the Departments column of the Employees table have corresponding entries in the Departments table. 3. Candidate key, Alternate key and Composite key: Any number of attributes that are uniquely identifying a row in a table is “candidate key” for the table. We select 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 database design are: 1. 2. 3. 4. Each table should have an identifier. Each table should store data for a single type entity Columns that should store data for a single type of entity. 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 relation 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. 2. 3. That had multiple candidate keys. Where the multiple candidate keys were composite. 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 join 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.

that codes are called method. This Database model came into existence with help of mathematical concepts. Entity in database. column means attribute and row means touples present instance of data. The decision to demoralize results in a tradeoff performance and data integrity. E-R Model in Database E-R model stands for Entity-Relationship model. The E-R diagram shows structure of E-R model. Object Oriented Database Model This model is based on collection of objects. These codes have written to operate the objects. OTHER DATABASE MODELS Relational Database Model Data represent in form of column and row.Demoralization The intentional introduction of redundancy in a table in order to improve performance is called demoralization. Objects that contain same types of values and the same methods are grouped together into classes. Its using some other concepts like normalization. In a table attribute know as column. This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Relationship is a logical thing which relates entities. Demoralization increases disk utilization. This model also follows the some concept related to the OOPs . touple relational calculus. An object is instance variables which store value and bodies of code. which existence in real world with number of attributes. In other words classes are a group of object.

High level insert. Data are treated as set . This database lets you organize data irrespective of whether it is organized or not.Hierarchical model of Database The word hierarchy means tree form relationship. 7. Means Relationship formed like tree structure in a database called hierarchical model. XML-enabled 2. 5. The view update rule: All views that are theoretically updated must be updated by the system. 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. Native XML Codd's Twelve Rules 1. Two major classes of XML database exist: 1. 3. Active online catalog based on relational model: DBMS maintain system catalog. But implementing this model is more difficult due to time consuming and cost. The information rule: This rule require all information to be represented as data values in the rows and column of table. 5. Data definition View definition Data manipulation operation Security and integrity constraints Transaction management operation 6.in case when user leave the column in the table. Its flexible because through link easily accessing of information. Systematic treatment of NULL values: DBMS support NULL values . 4. . 2. 4. update and insert. It has a downward link to describe the nesting and they are arranged in a particular order down the same level of the list.which are easily delete. This model provide logical relationship among many parent database. XML Database XML databases came into existence in 2000. The comprehensive data sublanguage rule: System must support following functions : 1. With this database you form relationship among many tables with certain concept. 2. update and delete: Means update at a time many rows values. Network model This model provides greater flexibility and easy access to data. like a tree with branches. System catalog is a collection of system table. This data can exported and serialized into the desired format. 3.

RDBMS recover data quickly with minimum loss. Highly Scalable and Reliable SQL sever use scale up and scale out feature to fulfill requirement . This feature called reliability. Distribution independence: Database must allow manipulation of distributed data located on different computer system. . Integrity independence: Integrity constraints must be storable in the system catalog. It provides various feature and facility to accesses data on web. Physical data independence: Application programs must remain unimpaired when any changes are made in storage representation or across methods. 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. When suddenly system crash . 10. 9. 12. In Scale up SQl server use 32 bit Processors and 64GB of RAM to increase the load.8. Logical data independence: Changes should not affect the user's ability to work with the data. 11. In scale out SQL distribute database and data load across the server. Client Server Architecture (Two Tier Architecture) Data Sharing.

223. 1900. user only concentrate on logic Data types Range Used to store -2^31 (-2.5808) money to 2^63 .808) to bigint Integer data 2^63-1 (9.647) bytes store images real -3.036.18E . where n can be 1 to varchar(n) Variable length character data 8000 Maximum length of 2^31 .3648 to +214.203.337.741.372.1 ntext Variable length Unicode data (1.748.40E + 38 to -1.477.000 bytes Fixed length binary data varbinary Maximum length of 8.79E + 308 to 1.767) tinyint 0 to 255 Integer data -2^63 (9. to December 31.748.036.1 Variable length binary data to image (2.1 Monetary data (+922. to June 6.854.823) characters bit 1 or 0 value Integer data with 0 or 1 Maximum length of 2^31 .203.685.38 Floating precision number binary Maximum length of 8.5807) smallmoney -214.685. where n can be 1 to char(n) Fixed length character data 8000 n characters.147.Reduce Duplication and maintenance SQL • Language to access data object from the SQL server • Stands for Structured Query Language • 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.223.147. 1753.073.483.147.337. datatime Date and time data 9999 smalldatatimeJanuary 1.1 smallint Integer data (32.775.483.483.79E + 308 Floating precision data -2^63 (-922.477.648) to 2^31 int Integer data (whole numbers) 1 (2. 2079 Date and time data n characters.807) float -1.647) characters Maximum length of 2^30 .3647 Monetary data January 1.775.768) to 2^15 .483.372.854.1 text Character string (2.647) -2^15 (-32.000 bytes Variable length binary data Dtatype .147.

12. 16. 15.nchar nvarchar sql_varient timestamp Maximum length of 4. 20. 4. 14. 23. 5. 7. image. . 25. 26.000 characters Fixed length Unicode data Maximum length of 4. 29. 27. 21. 30. 31. 3. 24. 9. 18. Renaming and Deleting a Database Data Integrity Creating Constraints PRIMARY KEY Constraint The UNIQUE Constraint The FOREIGN KEY Constraint The CHECK Constraint The DEFAULT Constraint 1. 19. 22. 35. timestamp and sql_variant unique number in a database that Maximum storage size of 8 bytes get updated every time a row that contains it is inserted or updated DDL (Data Definition Language) DML (Data manipulation language) DCL and TCL Displaying Rows Using Logical & List Operators Displaying Rows Using Comparison & Range Operators Displaying Rows Using String Operator IS NULL and IS NOT NULL keywords & ORDER BY Clause Limits the rows by using TOP keyword & DISTINCT keyword Using Aggregate Functions Using GROUP BY Clause Using COMPUTE BY Clause Using String Functions DATE Functions Mathematical Functions Some System Functions Joins Inner Join Outer Join Cross Join Equi Join Natural Join Self Join Sub queries with EXITS Clause Queries with modified Comparison Operators Extracting Data Into Another Table Using UNION Operator How to create a Data Base in SQL server . 8. 36. 10. ntext. 17. .mdf. 11.ndf and . 33. 2. 13.000 characters Variable length Unicode data Contain rows of different Maximum storage size of8016 bytes datatypes except text. 37. 32. 28. 34.ldf extension files Viewing. 6.

40. 39.. 1. When you execute a DDL statement. 2. 4. including all spaces allocated for the records are removed 5. it takes effect immediately. CREATE: To create objects in the database CREATE TABLE <table_name> ( <attribute_name 1> <data_type 1>. DROP: Delete objects from the database DROP TABLE <table_name>.. and the Primary Key attributes that they link to in the parent table. ALTER: Alters the structure of the database ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> PRIMARY KEY (<attribute_list>). 41.38.. since we have to specify both the Foreign Key attributes in this (child) table. 44.ELSE Statement and BEGIN. <attribute_name n> <data_type n>). 42. 45. DDL statements are used to build and modify the structure of your tables and other objects in the database. ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> FOREIGN KEY (<attribute_list>) REFERENCES <parent_table_name> (<attribute_list>).. INDEXES CLUSTERED Index NONCLUSTERED Index How to Create an Index Programming in SQL Server The IF. ALTER TABLE <table_name> DROP CONSTRAINT <constraint name>. COMMENT: Comments added to the data dictionary.END Statement The CASE statement and WHILE statement Stored Procedures How To Create Stored Procedure DDL (Data Definition Language) Data Definition Language (DDL) statements are used to define the database structure or schema. . 46. 6.. TRUNCATE: Remove all records from a table. The foreign key constraint is a bit more complicated.. RENAME: Rename an object of the Database . 43.

. SELECT statement promote the server to querying single table or multiple tables in Database and prepare a result and return to the client application.column_name 2. '201012-24') 3. . INSERT.. Selecting All Columns The SELECT statement used with an asterisk (*) symbol to display all column of the table SELECT * FROM table_name 2. DELETE statements are consider as a DML statement. . • 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.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. UPDATE table_name SET attribute_name 1 = value 1. Selecting Columns The column name from a table specified in the SELECT statement separated by a comma (. The keywords SELECT....) and there is no need to insert a comma after the last column name. SELECT column_name 1. FROM and WHERE makeup the basic SELECT statement . UPDATE: The update statement is used to change values that are already in a table. 1..attribute_name n = value n WHERE condition. UPDATE. INSERT: The insert statement is used to add new rows to a table. The statement of Insert will be: INSERT INTO table_name VALUES (value 1.. attribute_name 2 = value 2. There will need a separate INSERT statement for every row. SELECT.DML statements are used to work with the data in tables.DML (Data manipulation language) . SELECT: SQL server provide the SELECT statement to retrieve data from database. value n)..

OR: Any of the specified search condition is true. 4. 2. then every row of the table is deleted 5. 2. for rows in a table. 3. 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. 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. EXPLAIN PLAN: Explain access path to data 7. LOCK TABLE: Control concurrency DCL (Data Control Language) • • • DCL stands for Data Control Language Used to create roles Used to create permissions 1. DELETE FROM table_name WHERE condition. 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. They are: 1. .• If the WHERE clause is omitted. ROLLBACK: Restore database to original. GRANT: Gives user to access database means user privilege to database. If the WHERE clause is omitted. SAVEPOINT: Identify the point which you can later roll back in a transaction. CALL: Call a PL/SQL 6.

SELECT column_list FROM table_name WHERE condition list_operator('value_list') list_operator is any valid list operator. 2. value_list is the list of values to be included or excluded in the condition For Example: SELECT * FROM publishers WHERE state IN ('MA'. Using List Operator SQl provides IN and NOT IN operators. 3. SELECT column_list FROM table_name WHERE condition_expression {OR/AND} NOT condition_expression Return all rows specific to the conditions. when both conditions are true. even if any one of the condition is true. NOT: Neutralizes the expression that follow it.'DC') Using Comparison Operators . AND: When all specified search conditions are true. NOT IN operator restrict the selection of values that match any one of the values in a list.'DC') SELECT * FROM publishers WHERE state NOT IN ('MA'. SELECT column_list FROM table_name WHERE condition_expression AND condition_expression Return all rows specific to the conditions.SELECT column_list FROM table_name WHERE condition_expression OR condition_expression Return all rows specific to the conditions. IN operator that allowed the selection of values that match any one of the values in a list. except the rows that match the condition specified after the NOT operatoor.

Comparison operator allow row retrieval from a table based on the condition specified in the WHERE clause. The range operator are: 1. BETWEEN: Specified an inclusive range to search. 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 . SELECT column_list FROM table_name WHERE expression1 comparison_operator expression2 Operator = > < >= <= <>. 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.!= !> !< () 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 .

SELECT * FROM titles WHERE type LIKE 'b[^s]%' . Wildcard % _ [] [^] 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]%' 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 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.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.

SELECT column_list FROM table_name ORDER BY column_name ASC/DESC . 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. Note: NO two NULL values are equal. You can not compare one NULL value to other. Some Examples Expression LIKE '%ty%' LIKE '_ty' LIKE '[AD]%' Returns All names that have the letters 'ty' in them All three letter names ending with 'ty' All name that begin with "A" or "K" Using IS NULL & IS NOT NULL In SQL server. 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. NULL is a unknown value means the data is not available.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. ASC is the default sort order. The NULL can be retrieve from the table using IS NULL keyword in the WHERE clause.

It used with the SELECT statement.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.pub_id. For Example: SELECT TOP 5 pub_id. The DISTINCT keyword remove the duplicate row from the returned result set. from the publishers table in descending order with respect to pub_id.pub_name. Using Aggregate Functions . 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. pub_name and country. means no duplicate value of country.country FROM publishers WHERE country LIKE 'U%' ORDER BY pub_id DESC Returns all top 5 rows . 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. Using DISTINCT keyword It also used to limit the result set.

MIN and SUM function ignore NULL values.. ALL is a keyword used to include those groups that do not meet the search condition.. Function Name AVG COUNT COUNT MAX MIN SUM Parameters (ALL. COUNT. whereas the COUNT (*) function counts the NULL values Examples SELECT 'avg'=AVG (discount) FROM discounts SELECT 'sum'=SUM (discount) FROM discounts SELECT 'min'=MIN (discount) FROM discounts SELECT 'max'=MAX (discount) FROM discounts SELECT 'count'=COUNT (discount) FROM discounts Description Returns the average value of the discount Returns the sum value of the discount Returns the minimum value of the discount in discounts table Returns the maximum value of the discount in discounts table Return the number of discount value in discounts table Using GROUP BY Clause Group clause summarize the result set in to a groups defined in the query using aggregate function.. aggregate_function (expression) FROM table_name WHERE conditions GROUP BY ALL column1.. column2. . column2. DISTINCT Expression) (ALL. column_n. DISTINCT Expression) Description Return the average of value in a numeric expression Return the number of values in an expression Returns the no. of rows returned by the query Return the highest value in the expression Return the lowest value in the expression Return the total of value in a numeric expression The AVG. SELECT column1. . MAX. DISTINCT Expression) (*) (expression) (expression) (ALL. .These function are specially executed for the mathematical expression. column_n expressions describe the column name (s) or expressions on which the result set of the SELECT statement is to be grouped.

'avg'=AVG(advance) FROM titles WHERE title_id IN ('BU1032'. For Example: SELECT type. The ALL keyword is meaningful for those query that contain WHERE clause.pub_id Return the 'type' and 'pub Id' and 'avg' . which calculated from titles table.'pub Id'=pub_id.0000 mod_cook NULL popular_comp 7000.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'. For Example: SELECT type. Means this keyword used to display all groups.For Example: SELECT type. including those exclude from WHERE clause. 'avg'=AVG(advance) FROM titles WHERE type LIKE 'b%' GROUP BY ALL type Out Put type avg ----------------------------------------------business 5000.'PC1035') GROUP BY ALL type Out Put type avg ----------------------------------------------business 5000.0000 psychology NULL trad_cook NULL UNDECIDED NULL Using COMPUTE Clause . 'avg'=AVG (price) FROM titles GROUP BY type.

• COMPUTE BY clause can be used to calculate summary values of the result set on a group of data.column_name n For Example: SELECT type.• Used to generate summary rows using aggregate function in the query results... advance FROM titles ORDER BY type COMPUTE AVG (advance) BY type Out Put . SELECT column_name FROM table_name ORDER BY column_name COMPUTE aggregate_function (column_name) BY column_name 1. 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. • The main difference between GROUP BY and COMPUTE BY Clause is.

.

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. Function name ASCII Parameters (character_expression) Example Description CHAR (integer_expression) CHARINDEX ('pattern'. character_expression2) Return 65 the ASCII SELECT ASCII ('ADI') code of the leftmost character 'A' Return A the character SELECT CHAR (65) equivalent of the ASCII code value Returns 5. It used for implicit convert data to char to varchar.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. SELECT function_name (parameter) function_name is the name of the string function. parameter are required parameters for the string function. expression) SOUNDEX (character_expression) DIFFERENCE(character_expression1 . Mostly they are used with the char and varchar data types. the standing SELECT position of the specified CHARINDEX ('O'.'HELLO') pattern in the expression Return the four SELECT character code to SOUNDEX ('ADITYA') compare the string SELECT Difference function DIFFERENCE ('ADITYA'. Using String Functions This function use to format data that will meet specific requirements.'ADI') compare the SOUNDEX value of two string and return a value from 0 .

45'.6. the standing position of the first SELECT occurrence of the PATINDEX ('%TY%'. [length. the part RIGHT ('ADITYA'. which is the part of character SELECT string equal in size to LEFT ('ADITYA'. SELECT LTRIM ('ADITYA ') It removes leading blanks from the character expression Returns 'ADITYA TIWARI'. the no of SELECT LEN ('ADITYA') character in the (character_expression) Return 'aditya'.45. integer_expression) RTRIM (character_expression) SPACE (integer_expression) STR (float_expression. the sign. after the converting SELECT LOWER ('ADITYA') (character_expression) to the lower case Return 'ADITYA' without leading spaces. expression") REVERSE (character_expression) RIGHT (character_expression.'4') the integer_expression character from the left Return 6. Return 'ADITYA' without leading spaces. or zero if pattern is not found Return 'AYTIDA' .including the decimal point.'ADITYA') pattern in the specified expression. the digits.[decimal]]) .2) Return '123. the spaces and the decimal is the number of places to the right of the LEFT (character_expression. The value 4 is best match. It converts numeric data to character data where the length is the total length . Two space SELECT are inserted between 'ADITYA'+SPACE(2)+'TIWARI' the first and second word SELECT STR (123.to 4. the SELECT reverse of the REVERSE ('ADITYA') (character_expression) SELECT Return 'ITYA' .4) of the character string. Return 'ADIT'. SELECT LTRIM (' ADITYA') It removes leading blanks from the character expression Return 4. integer_expression) LEN (character_expression) LOWER (character_expression) LTRIM (character_expression) PATINDEX ("%pattern%.

which is part of a character string. as character DATENAME(datepart. ('Aditya'.3) UPPER (character_expression) SELECT UPPER ('aditya') Return 'Asya'.date Adds the number of dateparts to the date ) Calculates the number of dateparts between two DATEDIFF (datepart.date) value (for example: March) .2. length) SELECT SUBSTRING ('Aditya'.number.date1. It returns length character from the start position of the expression Return 'ADITYA'.2.date2) dates Return datepart from the listed date.'s') character_expression2) SUBSTRING (expression. SELECT STUFF start. after the converting (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 Name DATEADD Parameter Description (datepart.3. length. It delete length characters from character_expression1 from the start and then inserts character_expression2 into character_expression1 at the start position Returns 'dit'.decimal point STUFF (character_expression1 . start.

SELECT datepart (yy. The various mathematical functions are: Parameter Description (numeric_expression ABS Return an absolute value ) ACOS.date) GETDATE () For Example: SELECT getdate() Returns datepart from the listed date as an integer Returns current date and time The above statement display the current system date by using getdate() function. Using Mathematical Functions Mathematical function perform numerical operation on mathematical data.pubdate) FROM titles Return all Date from pubdate of titles table.sin Function Name .2.ASIN.DATEPART (datepart.pubdate) FROM titles Return the all pubdate from titles table with increment of 2 in each year of the table. ATN (float_expression) Returns the angle in radians whose cosin. SELECT 'getdate'= DATEADD(yy.

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. COS. negative or zero ) SQRT (float_expression) Return the square root of the specified value ROUND (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.TAN(float_expression) sin.452352.SIN.141592653589793 (numeric_expression.length) numeric_expression is the numeric expression to be round off SELECT 'value'= ROUND (123.and tangent is a floating point value Returns the angle in radians whose cosin. returns a numeric expression rounded off to ROUND length) the length specified as an integer expression (numeric_expression SIGN Returns positive. . 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.3) Out Put: Using System Functions System function provide a method of querying the system tables of SQL server.COT.

INNER. table_name specifies the name of the tables from which data to be retrieve. join_operator specifies the operator used to join the tables Function . OUTER] JOIN table_name ON [table_name. 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. column name 2.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.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 n FROM table name [CROSS.

table_name specifies the name of the tables that have to be combined in the query table_alias identifiers is the keyword used to refer to a table. it should be referred to either by prefixing it with the table name to which it belongs or by a table alias. A primary key is validated against the foreign key when a joined is used.ref_column_name] For Example: SELECT title.When two tables are joined. royalty FROM titleauthor JOIN titles titleauthor. Rows in both tables that do not satisfy the join condition are not displayed.title_id=titles.ref_column_name] join_operator [table_name. Syntax: FROM table_name table_alias Where. royaltyper. royalty from table in which these attributes are present . SELECT columnm_name FROM table_name JOIN table_name ON [table_name. data from multiple tables is displayed after comparing values present in a common column. Whenever a column is referred to in a join condition. Only rows with values satisfying the join condition column are displayed.title_id Return all title. they must share a common key that defines how the rows in the tables correspond to each other. 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. royaltyper. It must follow the rules of Types of JOIN Inner Join Outer Join Cross Join Equi Join Natural Join Self Join Inner Join In inner joining.

ref_column_name] join_operator [table_name.notes FROM pub_info p LEFT OUTER JOIN titles t ON p.price.pub_id=t.pub_id .. SELECT logo.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.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. columnm_name 2..columnm_name n FROM table_name [LEFT.RIGHT] OUTER JOIN table_name ON [table_name..

For Example: . column_name 2. where two or more tables are compared for equality.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.pub_id=t.. 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..column_name n FROM table_name CROSS JOIN table_name For example: SELECT * FROM sales CROSS JOIN publishers returns 168 rows. SELECT logo.Right Outer Join: Right outer join ensure the inclusion of rows the second table and the matching rows from the first table..notes FROM pub_info p RIGHT OUTER JOIN titles t ON p.price.

Self Join A join is said to self join when one row in a table correlates with the other rows in the same table.price=2.pub_id Returns the all title and pub_name from respective tables.title.pub_id=p. t1.title. Natural Join A join that restrict the redundant column from the result set is known as natural join SELECT t.pub_id=p.price=t2. t2.title_id JOIN publishers p ON t.price FROM titles t1 JOIN titles t2 ON t1. always returns data in terms of a TRUE or FALSE value.99 Using EXITS Clause A sub query used with the EXISTS clause.title. For Example: .price WHERE t1. For Example: SELECT t1.title_id=t. p.SELECT * FROM sales s JOIN titles t ON s.pub_name FROM titles t JOIN publishers p ON t. All join operators except the outer join operators can be used in a self join. An alias name can differentiate the two copy of the table. 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.pub_id Returns the above columns in the result set.

. Operator >ALL Description Means greater than the maximum value in the list. 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.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. 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.

column_name<>ALL (10.30) means 'equal to either 10 or 20 or 30' Means not equal to any in the list.20.30) means 'not equal to either 10 and 20 and 30' For Example: SELECT title_id .20.20. <>ANY column_name<>ANY (10.title FROM titles WHERE price>ANY(SELECT price FROM titles WHERE pub_id='0736') . It acts in the same way as the IN clause column_name=ANY (10.30) means 'greater than 30' Means greater than the minimum value in the list.title FROM titles WHERE price> ALL (SELECT price FROM titles WHERE pub_id='0736') Out Put: =ANY <>ALL 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 .20.30) means 'greater than 10' Means any of the values in the list.30) means 'not equal to either 10 or 20 or 30' Means not equal to all the values in the list.column_name>ALL (10. It acts in the same way as the NOT IN clause.20. >ANY column_name>ANY (10.

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..title INTO aditya .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. For Example: Create a new table from the title table. then the operation fails. condition is the conditions on which rows are to be included in the new table. The SELECT INTO statement creates a new table. table_name n WHERE condition 1. table_name 2. If the table is already exists. SELECT title_id . The command syntax is the.. SELECT columns_list INTO new_table_name FROM table_name 1. condition 2.

. 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].city. For Example: SELECT au_fname.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.state FROM authors WHERE state='UT' UNION .] [ORDER BY clause] [COMPUTE BY clause] UNION ALL is the operator used to combine two or more queries with duplicate rows from different queries.

n] LOG ON (NAME=logical_file_name. FILENAME='os_file_name'. NAME=logical_file_name specifies the logical name for the file.. FILENAME=os_file_name specifies the operating system file name. ON specifies the disk files used to store the data portion of the database. FILEGROWTH=growth_incremet specifies the growth increament of the file defined in the <filespace> list. SIZE=size.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.SELECT pub_name. data_base name is the name of new database. CREATE DATABASE database_name ON [<filespace>.. MAXSIZE=max_size specifies the maximum size to which the file defined in the <filespace> list can grow. . MAXSIZE=max_size..city. SIZE=size specifies the initial size f the file defined in the (<filespace>) list.n] [<filegroup>.. FILEGROWTH=growth_increment) where.

mdf Extension • When we create a database. Aditya named database created .00 MB on disk 'aditya_log'.ldf EXTENSIONS FILES . For Example: CREATE DATABASE aditya ON (NAME=aditya_dat.FILEGROUP filegroup_name name specifies the name of the filegroup. • It is a SQL Data files where all the data in the database objects are stored in .mdf is a primary file. FILEGROWTH=2 MB) Out Put: The CREATE DATABASE process is allocating 12.ndf and .ldf'. FILENAME='C:\Program Files\Microsoft SQL Server\MSSQL\DATA\aditya.00 MB on disk 'aditya_dat'. SIZE=12. the CREATE command create a data file with extension .mdf. FILENAME='C:\Program Files\Microsoft SQL Server\MSSQL\DATA\aditya. FILEGROWTH=2) LOG ON (NAME='aditya_log'. LOG ON specifies the disk files used to store the log files. SIZE=4 MB. . MAXSIZE=50 MB. MAXSIZE=100.mdf'. The CREATE DATABASE process is allocating 4.

Renaming and Deleting a Database Viewing a Database The information regarding database such as owner. and full being the most.• Like tables. size.ndf Extension • . Viewing. date of creation.mdf file of sql server • This is the reason whey we use . 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..ldf is the log file in the SQL server to see the data • Transaction log file with extension .ndf are secondary databse files • Same as mdf. there are a lot of things that can be done .ldf Extension • . All are stored in the .mdf we were able to see all the data exist in that respective database. and status can be viewed using the following: sp_helpdb database_name For Example: sp_helpdb aditya Renaming Database .ldf • The size of the log file (ldf) is determined my the logging level you have set up on the database • Simple. views. Once we attach the . triggers etc. stored procedures. and build logged are the options • Simple being the least. . full. 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.MDF file to attaché the database. but you can only have 1 Main database file • This file also could be stored on a separate physical drive • Advantage is that.

they can be identified using the unique code assigned to them. Deleting a Database A database is deleted when it is no longer required. The database should not be in use when it is being renamed. that contain various offices of a company and this table has another column city that store the cities where branch offices are located. 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. database_name is the name of the database DATA INTEGRITY There are three most important things when database is accessing: • • • Accurate Consistent Reliable . It can be enforced by restricting the type of data. means its very tuff to maintain data integrity. 'Chanai'. . sp_rename 'old_name'. the range of values. For example: there might be two candidates for interview with the same name 'alok'. By enforcing the integrity we ensure that only valid values can be entered in the city column of the BranchOffice table. 'Mumbai'. The primary key can not be NULL. and it should be set to the single-user mode. Assume that offices are located in 'Delhi'. For Example: Let assume that table BranchOffice. DROP DATABASE database_name where. Only the system administrator and database owner have permission to delete a database.The name of database can be changed. Data integrity ensures the consistency and correctness of data stored in a database. Domain Integrity Domain integrity ensures that only a valid range of values is allowed to be stored in a column. and the format of data.'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.

another table in university database is UniversityStudent which contain Enrollment number that make ensure registration of each student. CONSTRAITS constraints_name constraints_type] where. It can be created with the CREATE TABLE statement. which do not belong to the entity. 2. • • Column level Table level A constraints can be defined on a column at the time of creating a table. and referential integrity categories. For Example: In a CollegeStudent table each student has there enrollment number in the column. table_name is the name of the table that is to be altered for adding a constraints. domain. 1. ALTER TABLE statement: ALTER TABLE table_name [WITH CHECK or WITH NOCHECK] ADD CONSTRAINTS constraints_name constraints_type where. constraints_type is the type of constraints to be added. CREATE TABLE statement: CREATE TABLE table_name column_name CONSTRAINTS constraints_name constraints_type [. CREATING CONSTRAINTS Constraints can be be enforced at two levels. constraints_name is the name of the constraints to be created and must follow the rules for the identifier. column_name is the name of the column on which the constraints is to be defined.Referential Integrity Referential Integrity ensures that the values of the foreign key match with the value of the corresponding primary key. . User-defined Integrity User-defined integrity refers to a set by a user. For Example: If you want a candidate who is less than 18 years to apply for a post.

You can define a PRIMARY KEY constraints at the time of a table creation. If a name is not specified. table_name is the name of the table that constraints to be dropped. While defining a PRIMARY KEY constraints. SQL server automatically assigns a name to the constraints. All constraints defined in the table are dropped automatically when the table is dropped ALTER TABLE table_name DROP CONSTRAINTS constraints_name where. you need to specify a name for the constraints.. 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. For Example: . constraints_name is the name of the constraints to be dropped.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. DROPPING CONSTRAINTS A constraints dropped using the ALTER TABLE statement in the Query Analyzer. or you can add it later by altering the table. constraints_type specifies the type of constraints. These columns are referred to as the primary key columns.. CREATE TABLE table_name (column_name data_type CONSTRAINT constraints_name PRIMARY KEY). 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.

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