You are on page 1of 27

What is RDBMS? Ans: RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows.Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. What is View? Ans: A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views. What is SQL? Ans: SQL is a bassically standard language for accessing and manipulating databases. Its is defines as : > SQL stands for Structured Query Language > SQL lets you access and manipulate databases > SQL is an ANSI (American National Standards Institute) standard. SQL have a many properties, It can do : > SQL can execute queries against a database. > SQL can retrieve data from a database. > SQL can insert records in a database. > SQL can update records in a database. > SQL can delete records from a database. > SQL can create new databases. > SQL can create new tables in a database. > SQL can create stored procedures in a database. > SQL can create views in a database. > SQL can set permissions on tables, procedures, and views. What is schema? Ans: Schema bassically Pronounce skee-ma, It is the structure of a database system,It described in a formal language supported by the database management system (DBMS). In the RDBMS (Relational database System) , the schema defines the tables, the fields in each table, and the Schemas are generally stored in a data

dictionary . Even a schema is defined in text database language , the term is often used to refer to a graphical depiction of the database structure. What are the main components of Database management systems software. Ans: The database management system software includes many components are there, like : > for storage management, > concurrency control, > transaction processing, > database manipulation interface, > database definition interface, and > database control interface. What is query optimization? Ans: In the database many queries generate and executed or Query optimization is the part of the query process in which the database system compares different query strategies and chooses the one with the least expected cost.

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

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

OTHER DATABASE MODELS


Relational Database Model 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 relational calculus. E-R Model in Database E-R model stands for Entity-Relationship model. This data model 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 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, user only concentrate on logic

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 <table_name> ( <attribute_name 1> <data_type 1>, ... <attribute_name n> <data_type n>); 2. ALTER: Alters the structure of the database ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name> PRIMARY KEY (<attribute_list>); 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 <table_name> ADD CONSTRAINT <constraint_name> FOREIGN KEY (<attribute_list>) REFERENCES <parent_table_name> (<attribute_list>); 3. DROP: Delete objects from the database DROP TABLE <table_name>; ALTER TABLE <table_name> DROP CONSTRAINT <constraint name>; 4. TRUNCATE: Remove all records from a table, including all spaces allocated for the records are removed 5. COMMENT: Comments added to the data dictionary. 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, '201012-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 condition; 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 4. 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 (Data Control Language)

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

1. 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 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 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 Aggregate Functions


These function are specially executed for the mathematical expression. Function Name AVG COUNT COUNT MAX MIN SUM Parameters (ALL, DISTINCT Expression) (ALL, DISTINCT Expression) (*) (expression) (expression) (ALL, 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, COUNT, MAX, MIN and SUM function ignore NULL values, 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

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 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 alias. 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 identifiers is the keyword used to refer to a table. It must follow the rules of

Types of JOIN Inner Join Outer Join Cross Join Equi Join Natural Join Self Join

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

The UNIQUE Constraints


To enforce uniqueness on non-primary columns used the UNIQUE constraints. A primary key constraints column automatically includes a restriction for uniqueness. The unique constraint is similar to the primary key constraint except that it allows NULL values, but there can be only one row in the table with a NULL value. Multiple Unique constraints can be created on a table. CREATE TABLE table_name (coloumn_name data_type CONSTRAINT constraint_name UNIQUE) The Rules regarding to the UNIQUE constraints are:

It can be created at the column level as well as table level It does not allow two rows to have the same non-null value in a table Multiple UNIQUE constraints can be placed on a table

The FOREIGN KEY Constraint


FOREIGN KEY constraint to remove the inconsistency in two tables when data in one table depends on data in another table. A FOREIGN KEY constraint associates one or more columns of a table (the foreign key) with an identical set of columns on which a PRIMARY KEY constraint has been defined (a primary key column in another table). CREATE TABLE table_name (column_name data_type REFERENCES table_name (emp_id)) Syntax: CONSTRAINT constraint_name FOREIGN KEY (column_name,..) REFERENCE table_name (column_name,..) For Example: CREATE TABLE employee (emp_name char(4), emp_id varchar (16) REFERENCES engineer (emp_id)) The above command creates a FOREIGN KEY on the attribute emp_id of the employee table that reference the primary key emp_id of the engineer table. This will ensure that the employeeID code that is inserted into the employee table is checked against the engineer table for the validity.

If the employee table is exist and does not have foreign key defined, then table also modified using ALTER TABLE command. ALTER TABLE employee ADD CONSTRAINT fkemp_id FOREIGN KEY (emp_id) REFERENCES engineer (emp_id)

The CHECK Constraint


A check constraint: Enforces the domain integrity by restricting the values to be inserted in a column Constraints are evaluated in the order in which they are defined There is a possible to define multiple CHECK constraints on a single column If check constraints defined at the table level it can be applied for the multiple columns Syntax: [CONSTRAINT constraint_name ] CHECK (expression) where, constraint_name specifies the name of the constraint to be created. expression specifies the conditions that define the check to be made on the column. It can be any expression arithmetic operation, relational operation or keywords : 1. The IN keyword. 2. The LIKE keyword. 3. The BETWEEN keyword. The rules regarding the creation of the CHECK constraint are as follows: It can be created at the column level It can be contain user-specified search condition It cannot contain sub queries It does not check the existing data in the table if created with the WITH NOCHECK option It can reference other columns of the same table
CREATE TABLE Persons ( P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') )

The DEFAULT Constraint


A default constraint can be used to assign a constant value to a column, and the user need not insert values for such a column . Only one DEFAULT constraint values can be created for a column , but the column cannot be an IDENTITY column. The system-supplied values like USER, CURRENT_USER, and user defined values can be assigned as defaults. CREATE TABLE table_name (column_name data_type DEFAULT [constant_expression]) where, constraint_name specifies the name of the constraint to be created. constant_expression specifies an expression that contains only constant values and can contain NULL. For Example: CREATE TABLE employee (cCity char (14) DEFAULT 'New Delhi', emp_id varchar(15)) The above command use to create a DEFAULT constraint on the cCity attribute. If a city is not specified, then the cCity attribute would contain 'New Delhi' by default.

If table already created then using ALTER command we specified the DEFAULT constraint ALTER TABLE employee ADD CONSTRAINT defcCity DEFAULT 'New Delhi' FOR cCity

INDEXES
An Indexes is: SQL server used an internal table structure that provide quick access to rows of a table It is totally based on the values of one or more columns

SQL Server indexes are like the indexes at the back of a book, which help in locating content Advantage Of Using Indexes The primary purpose of an index is to provide faster access to data pages When server searched anything, it searching the index at the place of searching the whole page Server scan the index and get the address of data storage location and directly access the information Indexes are also used as a mechanism of enforcing data uniqueness An index speeds up the processing of queries that use joins or other clauses like ORDER BY or GROUP BY, by allowing to faster access of data Improve the speed of the execution of queries Enforce uniqueness of data Speed up joins between table Disadvantage Of Using Indexes Indexes does not indexing every column of the table It takes time to create index Each index create requires space to store data along with the original data source-the table An index gets updated each time the data is modified

The IF...ELSE Statement and BEGIN...END Statement


IF...ELSE Statement Syntax: IF boolean_expression {sql_statement} ELSE boolean_expression {sql_statement} where, boolean_expression is the condition that evaluates to either TRUE or FALSE. sql_statement is any T-SQL statement. statement_block is a collection of T-SQL statements. BEGIN...END Statement Syntax:

BEGIN {sql_statement} END where, sql_statement is one or more SQL statements The BEGIN...END block is nested and is most often used with the IF...ELSE statement and the WHILE looops. Example: IF EXISTS (SELECT * FROM employee WHERE emp_name='anchal') BEGIN PRINT 'The Details of employee are Available' SELECT * FROM employee WHERE emp_name='anchal' END ELSE PRINT 'Employee details not Available' Out Put: anchal related information viewed

IF EXISTS (SELECT * FROM employee WHERE emp_name='anchal') BEGIN PRINT 'The Details of employee are Available' SELECT * FROM employee WHERE emp_name='Ram' END ELSE PRINT 'Employee details not Available' Out Put: There is no information shown related to Ram For Example: There are number of employee in the employee table and there salary different according to there experience, the administrator want to increase there salary then this code be written. SELECT * FROM employee

IF (SELECT MAX (emp_sal) FROM employee )<45000 BEGIN UPDATE employee SET emp_sal=emp_sal+25000 END ELSE BEGIN UPDATE employee SET emp_sal=emp_sal+10000 END SELECT * FROM employee

STORED PROCEDURES
SQL server is based on Client/Server technology. A number of clients send queries to the central server. After receiving the query, the server parses the query and check the syntaxes errors. After this processes the request. The query passes through the network , its add the network congestion and increased the traffic. A stored procedure is a solution to these problems. It can be created through the Enterprise Manager or using the Query Analyzer window with the CREATE PROCEDURE statement. "A Stored Procedure is a precompiled object stored in the database." Benefits Of Stored Procedure Improved performance: SQL server does not have to compile the procedure repeatedly Reduction in network congestion: Application need not submit multiple T-SQL statement to the server for the purpose of processing Better Consistency: The coding logic and T-SQL statements defined in the procedure are uniformly implemented across all applications as the procedure serves as a single point of control

Better security mechanism: Users can be granted permission to execute a stored procedure even if they do not own the procedure Types Of Procedures User Defined Stored procedure: The user defined stored procedures are created by users and stored in the current database System Stored Procedure: The system stored procedure have names prefixed with sp_. Its manage SQL Server through administrative tasks. Which databases store system stored procedures are master and msdb database Temporary Stored procedures: The temporary stored procedures have names prefixed with the # symbol. Temporary stored procedures stored in the tempdb databases. These procedures are automatically dropped when the connection terminates between client and server Remote Stored Procedures: The remote stored procedures are procedures that are created and stored in databases on remote servers. These remote procedures can be accessed from various servers, provided the users have the appropriate permission Extended Stored Procedures: These are Dynamic-link libraries (DLL's) that are executed outside the SQL Server environment. They are identified by the prefix xp_

How To Create Stored Procedure


The CREATE PROCEDURE statement Guideline Syntax CREATE PROCEDURE proc_name AS BEGIN sql-statement 1 sql-statement 1 END where, proc_name specifies the name of the stored procedure. For Example CREATE PROCEDURE empNameList AS BEGIN SELECT 'Employee'=emp_name, 'Salary'=emp_sal Identify the database in which the stored procedure has to be created Determine the type of stored procedure Determine the name for the stored procedure Write the batch statement

END

FROM employee

Stored Procedure Created. Check the existence of the procedure in the database Syntax sp_helptext proc_name sp_helptext empNameList Out Put

Execute the procedure Syntax EXECUTE proc_name EXECUTE empNameList Out Put

In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.

SQL CREATE VIEW Syntax


CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples


If you have the Northwind database you can see that it has several views installed by default. The view "Current Product List" lists all active products (products that are not discontinued) from the "Products" table. The view is created with the following SQL: CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No

Autoincrement
CREATE TABLE Persons ( P_Id PRIMARY KEY AUTOINCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) Sqlserver CREATE TABLE Persons ( P_Id int PRIMARY KEY IDENTITY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

You might also like