You are on page 1of 97

Basic DBMS Concept

A)DATABASE MANAGEMENT SYSTEM(DBMS) The software used for the management, maintenance and retrieval of the data stored in a database is called DBMS. Database management systems frees the programmer from the need to worry about the organization and location of data. The primary goal of a DBMS is to provide an environment which is both convenient and efficient to use in retrieving and storing information. B) A DATABASE STORAGE HIERARCHY 1) DATABASE A collection of data files integrated and organised into a simple comprehensive file system, which is arranged to minimize duplication of data and to provide conenient access to information within that system to satisfy a wide variety of user needs. 2) DATA FILES A file is a number of related records that are treated as a unit. eg:- A collection of all employee records for one company would be an employee file. 3) RECORDS A collection of related items of data that are treated as a unit. eg:- An employee record would be collection of all fields of one employee. ->Record is sometimes referred as tuple. 4) FIELD Individual element of data is called Field. eg:- Bank cheque consist of following field cheque no, date, payee, numeric amt, signature, bank,etc. ->Field is sometimes referred as Data item.

C) Basic DBMS TERMS 1) RELATION

A relationship is an association among several entities eg:- A cusst_Acct relationship associates a customer with each account that she or he has. 2) REDUNDANCY If same piece of information is stored in database for number of times the database is said to be redundant. We should check our database should not be redundant as it wastes make our disk space, reduced efficiency of database, require more processing time, and their are chances of Inconsistency due to it in our database. eg:-If we have to tables emp_details (contains details of employee) and Payroll(contains Payment details to employee), than if we include details of employee in payroll table, than it is said to be redundancy as same piece of information is repeated. 3) INCONSISTENCY Inconsistency is various copies of the same data may no longer agree. Inconsistency occurs due to redundancy, so redundancy should be reduced . Though we cannot elimnates the redundancy , but we can reduced it upto certain level. eg:- If we have details of employee stored in emp_details and payroll table than while updating information we should check that both tables are updated or not, if we update the address of one employee in emp_details and same details is not updated in payroll table, than database is said to be in inconsistent state.

4) PROPAGATING UPDATES Propagating updates ensures users that any change made to record of one files, automatically made to other files. This process is known as Propagating updates. Where the term "Updates" is used to cover all the operations of creation, deletion and modification. -we can avoid inconsistency by using propagating update technique. 5) INSTANCES The collection of information stored in the database at a particular moment

in time is called an instances of the database. 6) SCHEMES The overall design of the database is called the database schemes. Schemes are changed infrequently, if at all. 7) USERS There are four different types of database system users. - Application programmers:- A person who prepares application program are called application programmer. Application programs operates on the data in all the usual ways: retrieving information, creating new information, deleting or changing existing information. - SOPHISTICATED USERS:- Sophisticated users interact with the system without writing programs. Instead, they form their requests in a databasequery language. Each such query is submitted to a query processor whose function is to take a DML statement and break it down into instructions that the database manager understands. - SPECIALIZED USERS:-Some sophisticated users write specialized database application that do not fit into the traditional data processing framework. Among these application are computer-aided design systems, knowledge-base and expert systems, systems that store data with complex data types eg:-For Graphics and Audio data. - END USERS:-Unsophisticated users interact with the system by invoking one of the permanent application programs that have been written previously.Thus they are persons who uses the information generated by a computer based system. Retrival is the most common function for this class of user.

D) KEYS concept in DBMS A Key is a single attribute or combination of two or more attributes of an

entity set that is used to identify one or more instances of the set. 1) PRIMARY KEY:-A primary key is a field that uniquely identifies each record in a table. As it uniquely identify each entity, it cannot contain null value and duplicate value. eg:-Consider the customer table, which has field :customer_number, customer_socialsecurity_number, and customer_address.here customer_number of each entity in customer table is distinct so customernumber can be a primary key of customer-table. 2) SUPER KEY :- If we add additional attributes to a primary key, the resulting combination would still uniquely identify an instance of the entity set. Such augmented keys are called superkey. A primary key is therefore a minimum superkey. 3) CANDIDATE KEY:-A nominee's for primary key field are know as candidate key. eg:-From above example of customer table, customer_socialsecurity_number is candidate key as it has all characteristics of primary key. 4) ALTERNATE KEY:-A candidate key that is not the primary key is called an Alternate key. eg:- In above example, customer_socialsecurity_number is a candidate key but not a primary key so it can be considered as alternate key. 5) COMPOSITE KEY:- Creating more than one primary key are jointly known as composite key. eg:-In above example, if customer_number and customer_socialsecurity_number are made primary key than they will be jointly known as composite key. 6) FOREIGN KEY:- Foreign key is a primary key of master table, which is reference in the current table, so it is known as foreign key in the current table. A foreign key is one or more columns whose value must exist in the primary key of another table.

eg:-Consider two tables emp(contains employees description) and emp_edu(contains details of employee's education), so emp_id which is primary key in emp table will be referred as foreign key in emp_edu table.

E) NORMALIZATION It is important to understand the concept of normalization before switch on to the creation of table and its manipulation. - NORMALIZATION is the process of grouping data into logical related groups. - Normalization is the process of reducing the redundancy of data in a relational database. - A database that is not normalized may include data that is contained in one or more different tables for no apparent reason. This could be bad for security reasons, disks space usage, speed of queries, efficiency of database updates, and may be most importantly, data integrity. A database before normalization is one that has not been broken down logically into smaller, more manageable tables. BENEFITS OF NORMALIZATION Normalization provides numerous benefits to a database. some of the major benefits include

Wider the overall database organization. The reduction of redundant data. Data Inconsistency can be avoided. A much more flexible database design. A better handle on database security.

SQL Basics
SQL(STRUCTURED QUERY LANGUAGE)

SQL is a Non-procedural Language. SQL provides a fixed set of datatypes you cannot define new datatypes. Every SQL statement is terminated by a semicolon. An SQL statement can be entered on one line or split across several lines for clarity. SQL is not a case sensitive; you can mix uppercase and lowercase when referencing SQL keywords (such as select and Insert), table names and column names. SQL determines how to perform the request. SQL is the official and de facto standard language for interfacing with relational database. SQL is Fourth Generation Language (4GLs). SQL*Plus is one of the Front end tool of ORACLE. SQL is the interfacing language between the user and the ORACLE database. SQL as non-procedural, does not bother how to get data - Interested in what data to get. SQL HISTORY AND STANDARDS * Found in mid 1970's by IBM for system R. * ORACLE incorporated it in the year 1979. * SQL used by IBM/DBZ and DS database systems. * SQL adopted as a standard language for RDBMS by ANSI in 1986.

SQL statements can be broadly categorized into Three types:1)DATA DEFINITION LANGUAGE(DDL) Which defines the structure of the data. The statements are CREATE, ALTER,etc. 2)DATA MANIPULATION LANGUAGE(DML)

which retrives or modify data. The category of DML contains four basic statements: i>select - which retrieves rows from a table. ii>Insert - Which adds rows to a table. iii>Update - Which modifies existing rows in a table. iv>Delete - Which removes rows from a table. 3)TRANSACTION CONTROL LANGUAGE(TCL) Which defines the privileges granted to database users. TCL statements are used for securing the database.TCL statement such as COMMIT,SAVEPOINT and ROLLBACK affirm or and revoke database transactions. (commands will be explained later).

LOGIN PROCEDURE FOR SQL*PLUS FOR LINE MODE VERSION 1) C:\>SQLPLUS 2) C:\>PLUS80 FOR GRAPHICAL USER INTERFACE(GUI) MODE 1) C:\>PLUS80W 2) START -> PROGRAMS -> ORACLE -> SQL*PLUS. NOTE:-The above path are define considering most common path used, their can be other path for same procedure depending upon the way of installation of particular software.

CONNECTING TO AN ORACLE DATABASE Before you create a new user, you will have to know how to connect to an oracle database. The dialog window prompts you for three items: i) User Name :- The oracle database user you are using for connection.

ii) Password :- The User Password associated with username. iii) Host string :- A database or connect string is require while you are trying to connect to an Oracle database on server.

The starter database comes with some default user names and user password which are shown in the following table. Use these default values until you establish your own user_name and user_password.They are given as ROLES, USER_NAME AND PASSWORD respectively. 1)[DBA - INTERNAL - ORACLE] 2)[CONNECT RESOURCES - SCOTT - TIGER] 3)[DBA - SYSTEM - MANAGER] 4)[DBA/CONNECT RESOURCES - SYS - CHANGE_ON_INSTALL] 5)[CONNECT RESOURCES - DEMO - DEMO] 6)[DBA - PO8 - PO8] NOTE:-This are the commonly use user_name and password still there are many for longon purpose. TIPS FOR USER NAME AND PASSWORD A user name must be associated with a user password. The maximum length for the user_name is 30 characters. A user Password is a word or phrase (no space or commas allowed) associated with a user_name. Keep this password secret in order save your data from modified by other users. The maximum length is 30 Characters. To create user syntax:-create user identified by ; example:-create user vivek identified by vr1; where vivek is user and password is vr1. To Give Rights after creating users syntax:- grant to ; grant on to ;

example:- 1)grant DBA to vivek; where DBA is Right and vivek is user_name. 2)grant update,delete on library to nihar; To Remove the Grant given to users syntax :- revoke on from ; example :- revoke insert on library from tushar; where Right is insert table is library and user is tushar. To see Rights of users syntax :- show all user; To Connect to another user from current login syntax :- connect ;

To see the name of user in which you are currently been logged on syntax :- select user from dual; or show user; DUAL:- DUAL is usually a pseudocolumn which doesn't require any argument, It can be considered as built-in value that returns specified piece of information by quering a table. for example:-sysdate always returns the current date and time. similarly here it provides information about the current user who is connected to the oracle database.

Before Ending this topic let us learn common command which is require frequently that is Command To Clear Screan syntax cl scr;

ORACLE Datatypes Basics


1) CHAR -> Char contain alphanumeric data. -> Length of Char datatype is between 1 and 255 characters. -> If you don't specify a length, a char column stores a single character by default. -> Char datatypes stores data in the Fixed-Length Format. -> Be aware, when using this data type, that spaces are padded to the right of the value to supplement the total allocated length of the column. -> It can be declared as char(size) where size is the total length allowed for a value in a column defined as char. 2) DATE -> Date datatype is used to store all date and Time information. -> Oracle always allocates a Fixed - 7 bytes for a DATE column. -> Oracle uses the default format of DD-MON-YY for entering and displaying. -> Following Include as a Part of DATE are century, year, month, day, hour, minute and second. -> It enables you to store dates in range of January 1, 4712 B.C. To December 31, 4712 A.D. -> To view System Date and time we can use the SQL function called SYSDATE. 3) LONG -> It can store alphanumeric strings. -> It stores the data in Variable-Length Format. -> Length of Long rise upto 2 giga bytes. -> Long is used to store more than 2000 characters in a column. -> You cannot use any of Oracle's built-in functions or operator with LONG column. -> You can think of a LONG column as a large container into which you can store or retrieve data but not manipulate it. Limitations of LONG data type are as under i> Only one column in a table can have LONG datatype, which should not contain unique or primary key constraint.

ii> Column cannot be indexed. iii> Procedures or stored procedures cannot accept LONG datatype as argument. 4) NUMBER -> It can store Numeric data such as Zero, Positive or Negative, Fixed or Floating point data. -> It accepts Positive and negative integers and real number and has from 1 to 38 digits of precision. -> Scale which refers to number of digits to the right of the decimal point, which varies between (-84) to 127. -> Format of declaring NUMBER datatype is NUMBER( Precision, Scale) example:1) NUMBER(5) - It can store numeric data upto 5 digits i.e. 99999 2) NUMBER(8,2) - It can store numeric data of 6 Integers and 2 for decimal. i.e. 999999.99 5) -> -> -> -> -> VARCHAR2 It stores Alphanumeric data values. The field must be between 1 and 2000 characters long. VARCHAR2 supports Oracle built-in functions and operators. It supports a variable length character string. Format of declaring VARCHAR2 IS VARCHAR2( size ).

6) VARCHAR Same as Varchar2. Always use Varchar2 instead of varchar as it may not be supported in future. 7) BLOB (Binary Large OBjects) -> Blob include documents, graphics, sound, video, actually any type of binary file you can think of. -> A binary large object with a limit of 4GB in length. -> When you want to associate a BLOB with a 'NORMAL' row, two choices are available to you. i> Store the BLOB in an operating system file(such as an MS-DOS file) and stores the directory and filename in the associated table.

ii> Store the BLOB itself in the LONG RAW column. 8) CLOB (Character Large OBject) -> A character Large object with a limit of 4GB in length. 9) BOOLEAN -> Boolean variables are used in PL/SQL control structure such as IF-thenELSE and LOOP statements. A Boolean value can hold true, false or NULL only. 10) LONG RAW -> It can store binary data upto 2GB. -> LONG RAW datatype is designed for BLOB storage. You can't use any of the built-in functions with a LONG RAW column. 11) RAW -> It can store binary data upto 255 bytes. -> Because of this storing restriction, a RAW column is less useful than a LONG RAW column. 12) ROWID -> Hexadecimal string representing the address of a row in a table. 13) INTEGER -> Specifies size of an INTEGER(n) digits wide. 14) BINARY INTEGER -> The number type is stored in a decimal format which is optimized for accuracy and store efficiency. This datatype is used to store signed integer values, which range from TM2147483647 to +2147483647. It is stored in a 2's complement binary format. Loop Counter are often of type BINARY INTEGER.

DATA DEFINITION LANGUAGE (DDL)


INTRODUCTION to DDL A database scheme is specified by a set of definition which are expressed by a special language called a Data Definition Language. The result of compilation of DDL statement is a set of tables which are stored in a special file called Data Dictionary. -> DDL defines the structure of data. -> DDL statements in SQL language are responsible for creating or modifyingdatabase structures such as tables, views, and indexes.

Let us now understand DDL statements and how it works on Oracle database. TABLE (A table consist of Rows and Columns. Table is a collection of related records that are treated as a unit. ) Convention for Naming a Table in Oracle -> Each table owned by a Oracle account must have a unique name. -> A table name cannot exceed 30 characters in length. -> A table name must begin with an alphabetic character. -> A table name can contain the letters A through Z, the digits 0 through 9, and the characters $, #, and _(underscore). -> A table name cannot be an SQL reserved word. -> You can use uppercase and lowercase characters in naming tables; oracle is not case sensitive as long as table or column names are not enclosed in double quotes. -> A table name should be descriptive. Convention for Naming Column in Oracle. -> Within a single table, a column name must be unique. However, you may use the same column name in different tables. -> Like other database objects, a column name can be upto 30 characters

long. -> The column name must begin with an alphabetic character. -> The column name can contain the letters A through Z, the digits 0 through 9, and the characters $, #, and _(underscore). The name cannot include spaces. -> A column name cannot be an SQL reserved word. -> As with tables, be descriptive in naming a column. Descriptive column names help users understand the definition of each column. -> An Oracle table may have upto 254 columns. Commands Related To Table 1) Syntax to CREATE Table CREATE TABLE ( [column level constraint], : : , [Table level constraint] ); Here, -> Table_name is the name for the table. -> Column_name1 through Column_nameN are valid column names. -> Datatypes is a valid Oracle datatype specification. -> Constraint_name is a optional, but it should be used in order to avoid invalid information to be entered in the database. NOTE:-you can assign default value for field by using the keyword default and specifying default value for that field. eg:-city varchar2(25) default 'AHMEDABAD' (Though SQL is not case sensitive, but contents of table are case sensitive so it is good practise to write data always in uppercase). Tip - CHAR, VARCHAR AND DATE kind of data should be written in single quota. example

sql> create table emp ( emp_no number (6) primary key, emp_name varchar2(35), emp_address varchar2(45), emp_city varchar2(30), emp_state varchar2(30), emp_age number(2), emp_sex char, emp_department varchar2(30) ); Table created. 2) Describe Table -> This command will describe the table. Syntax for describing table sql> desc ; or sql> describe ; example sql> desc emp;

3) ALTER Table -> Alter command is used to make modification after table has created. -> Modification like to add column, to drop constraint like primary key,etc., However you cannot delete the column nor you can decrease the width of column. Syntax to ALTER Table definition ALTER TABLE [ADD MODIFY DROP] (, : : );

examples -> To Add column in a table. sql> alter table emp add (emp_phno number(10)); -> To Modify Table sql> alter table emp modify ( emp_city varchar2(35), emp_state varchar2(35) ); -> To Drop Table's Primary key and other constraints. general syntax ALTER TABLE [DROP ENABLE DISABLE] CONSTRAINT ; sql> alter table emp drop primary key; After successfully completion of above command you get the message table altered.

4) Command to Delete contents of Table TRUNCATE -> Truncate command will delete all the table contents by removing all the rows(records) from the table. -> After the implementation of this command, only the structure of the table remains. Syntax for Truncate command sql> TRUNCATE TABLE ;

example sql> truncate table emp; -> It will delete all the rows of the emp table and only structure of the table remains. 5) Command to Delete Table DROP -> Drop command will delete the table contents and its structure. Syntax for Drop command sql> DROP TABLE ; example sql> drop table emp; -> It will delete all the rows and the structure of emp table. 6) Command to Rename Table -> Rename command will rename the table name. Syntax for Rename command Sql > RENAME TO example sql> Rename employee to emp; -> Now the table name is renamed and you can manipulate it using name emp. INTEGRITY CONSTRAINTS An Integrity constraint is a trick used by oracle to prevent invalid data entry into the table. It is only a rules applied to restrict user to enter particular value. It prevent this by defining it at column-level or table-level constraint. The main difference between both is that column-level constraint is defined at the column level and cannot reference by any other columns in the table. A table-level constraint is defined at the table level and can reference to any of the table's columns. NOTE:-not null and check constraint cannot be defined as table-level constraint. Integrity constraint are categorized into three types they are as under 1) Domain Integrity Constraints 2) Entity Integrity Constraints

3) Referential Integrity Constraint. I) DOMAIN INTEGRITY CONSTRAINTS -> Domain integrity constraint Prevent invalid data entry by enforcing rules like NOT NULL and CHECK on the column. NOT NULL ->By default, every column can contain null value. But, If we want to restrict the user to enter the value at any cost we should put not null constraint. ->In other words, not null field should always contains value. example create table emp ( empno number(4) constraint ntnl not null, ename varchar2(25), job varchar2(25) ); ->here empno is column-level constraint and after implementation of the above command while user want to enter the value, he must have to enter empno. ntnl is the constraint name. CHECK -> check constraint is used to match the enter data with predifined criteria during designing of table. -> As it check for predifined criteria it stops the invalid user to do mischief with the database. -> Thus it helps in making database consistent by feeding reliable information. example create table emp ( empno number(4) constraint ntnl not null, ename varchar2(25), job varchar2(25) constraint check(job in('clerk','manager')) ); ->here check constraint will look for job in clerk or manager and if enduser

try's to enter job for another category an error code for it will be generated by sql. II) ENTITY INTEGRITY CONSTRAINTS -> Entity integrity constraint Prevent invalid data entry by enforcing rules like UNIQUE and PRIMARY KEY on the column. UNIQUE -> Unique constraint allowed null values, but it does not allowed duplicate values. -> It may be composite upto 16 columns. example create table emp ( empno number(4), ename varchar2(25), job varchar2(25), constraint unino unique(empno) ); ->here unino is constraint name for table-level constraint definition and constraint unique is applied to empno, so after execution of above command user can enter only unique value or may not enter the value. PRIMARY KEY -> A primary key is a field that uniquely identifies each records in a table. -> It should neither be duplicate nor null. -> It may be composite upto 16 columns. example create table emp ( empno number(4) constraint pkno primary key , ename varchar2(25), job varchar2(25) ); ->here Primary key is created for empno so it will alone identifies each records in a table. pkno is a constraint name for column-level definition of

constraint.

III) REFRENTIAL INTEGRITY CONSTRAINTS -> Often, we wish to ensure that a value that appers in one relation for a given set of attributes also appears for a certain set of attributes in another realtion. This condition is called referential integrity. -> To implement this, we should define the column in the parent table as a primary key and the same column in the child table as a foreign key referring to the corresponding parent entry. ->foreign key is a column or combination of column which refers to primary key of primary table. example create table emp ( empno number(4) constraint pkno primary key , ename varchar2(25), job varchar2(25) );

create table education_detail ( empno number(4) , degree varchar2(30), foreign key (empno) references emp(empno) ); -> here emp table contains the details of the employee while education_detail table consist of their achived degree's by their no. one-tomany relationship is formed here. As one employee have many degree's and even few employee have no degree's. ON CASCADE DELETE -> It is special facilty through which we can ensure that the row deleted in

the master table will automatically deletes the row in the reference table. for example if we have records of employee details than after deleting any one of their record will automatically deletes the corresponding entry in the reference table. example create table education_detail ( empno number(4) references emp(empno) on-delete-cascade, degree varchar2(30) );

DATA MANIPULATION LANGUAGE (DML)


INTRODUCTION to DML By data manipulation language we mean: ->The retrieval of information stored in the database. ->The insetion of new information into the database. ->The deletion of information from the database. ->The modification of data stored in the database. Thus, it is a language that enables users to access or manipulate data as organised by the appropriate data model. There are basically two types of DML i>Procedural DMLs ->It requires a user to specify what data is needed and how to get it. ii>Non-Procedural DMLs ->It requires a user to specify what data is needed without specifying how to get it. As SQL is Non-Procedural language we will switch on to Non-Procedural DMLs as it is easy to understand and became very efficient for new users to begin with it.

The category of DML contains four basic statements: i>select - which retrieves rows from a table. ii>Insert - Which adds rows to a table. iii>Update - Which modifies existing rows in a table. iv>Delete - Which removes rows from a table.

SELECT Statement ->To view all rows or some of the rows from a table or more than one table depending upon a userdefined criteria,this command is used. ->By default, select statement display all rows which matches the criteria but we can get the unique records by using keyword distinct with it. syntax: SELECT [DISTINCT ALL] FROM WHERE ->keyword ALL is optional by default it consider ALL rows in table. example: 1)SQL>select * from emp; ->It will display all rows of emp table including all feilds.we can customize the output by selecting the columns which are needed to us. 2)SQL>select empno,ename from emp; ->It will display all rows of emp table including empno and employee_name detail for an employee. 3)SQL>select * from emp where job = 'clerk'; ->It will display all details of employee whose status is clerk. 4)SQL>select distinct ename from emp; ->It will display all unique name of employee if employee_name is repeated twice than it will display only ones.Thus it discards the duplicate records.

INSERT Statement ->INSERT command is used to insert one or more rows in a table. (There are many of syntax for insert command but one mentioned as under is the only standard way to insert multiple rows.) syntax:INSERT INTO (........) VALUES (<&Fieldname1>......<&FieldnameN>) ->Where the Fieldname should be valid field for a table. ->Field having datatype char,varchar2 and Date kind of data should be written in single quota.

examples: 1)SQL>Insert into emp (empno,ename,job) values ('1','SHREY','MANAGER'); ->Above command will insert data for one record, here as data are mentioned directly, so we have made use of single quota. 2)SQL>Insert into emp (empno,job) values (&empno,'&amp;amp;job'); ->Here we have customize the insert command to take data for only two field that is empno and job for multiple records. ->When you don't want to type the command which is used last than simply press the slash to activate the command which is used by you last. 3)SQL>Insert into emp values (&empno,'&amp;amp;ename','&job'); ->Note in Above command we haven't declare the field in which data is to be entered, it is optional when we have to enter data for all fields in column. 4)SQL>Insert into emp (empno,ename,job) values ('5','VRAJ',NULL); ->The above command will create a row and assign value 5 for empno and vraj for ename and leave the column job. ->If we doesn't want to enter value for a particular field we can just type NULL in it place during defining the INSERT command. And just press enter while entering the value. 5)SQL>Insert into emp_bkup (select * from emp); ->The above command will copies all the rows from table emp and insert it into the table emp_bkup, provided that the structure of emp and emp_bkup is same. ->The above command is efficient to run when we want to create backup copy of our data.

UPDATE Statement ->Update command is used to modify content of table, that to under satisfaction of particular criteria. syntax: UPDATE SET = WHERE ; ->Where Clause is optional.

->Fieldname is name of column whose contents are to be manipulated. example: 1)SQL>Update emp set job = 'ACCOUNTANT' where job = 'MUNIM'; ->Above sql statement will Modify Job field for employee whose status is munim, it will update the status munim with accountant. 2)SQL>Update emp set salary = salary + (salary * 10) where job = 'PROGRAMMER'; ->Above statement will increase salary of employee by 10% whose status is programmer.

DELETE Statement ->DELETE command is used to delete one or more rows from the table. Note:-No warnings are given before deleting rows so be careful while performing this operation. syntax: DELETE FROM WHERE ; ->Table_name is name of table from which you want to delete record/s. ->Criteria is condition under which you want to delete record/s. example: 1)SQL>Delete from emp Where empno = 4; ->Above statement remove record of empno 4. ->Only one record is deleted. 2)SQL>Delete from emp Where job = 'OPERATOR'; ->Above statement remove record/s of those employee whose status is operator in the company.

DATA CONTROL LANGUAGE (DCL)


INTRODUCTION to DCL

DATA CONTROL LANGUAGE is known as DCL. DCL Statement is used for securing the database. DCL Statement control access to database. As data is important part of whole database system we must take proper steps to check that no invalid user access the data and invalidate the information created by us. To kept such a kind of watch we must have to execute certain DCL statement. Two main DCL statement are Grant and Revoke. GRANT Statement - Grant privilege(Rights which are to be allocated) is used when we want our database to share with other users, with certain type of right granted to him. Consider that if we want our enduser to have only access privilege to our database, we can grant it by executing command. - Grant privilege is assigned not only on table object, but also views, synonyms, indexes, sequences,etc. Syntax: GRANT PRIVILEGES ON TO Example 1)SQL> grant select on emp to endusers; - here emp is the table_name whose access right is being allocated to the user who logged on as endusers. 11)SQL>grant insert,select,delete on emp to operators; - here user who logged on as operators are granted access, insertion and deletion right on the database. 111)SQL>grant insert (empno, ename, job) on

emp to endusers; - In some case, we require to hide the information to particular users, this can be achived by grant as in the above command we want to hide the detail of employee salary to endusers, so by executing above command we can hide the information regarding empsalary to the endusers.

REVOKE Statement - Revoke privilege(Rights which are to be de-allocated) is used when we want our database to stop sharing the information with other users, with certain type of right revoked to him. Consider that if we want our operators to have only access privilege to our database, we can revoke it by executing command. - Revoke privilege is assigned not only on table object, but also views, synonyms, indexes, sequences,etc. Syntax REVOKE PRIVILEGES ON FROM example 1)SQL> revoke insert, delete on emp from operators;

TRANSACTION CONTROL LANGUAGE (TCL)


TRANSACTION:-Collection of operation that forms a single logical unit of work are called Transactions. In other words, Transactions are units or sequences of work accomplished in logical order, whether in a manual fashion by a user or automatically by some sort of a database program. In a relational database using SQL, transactions are accomplished using the DML commands, which are already discussed. A transaction can either be one DML statement or a group of statements. When managing groups of transactions, each designated group of transactions must be successful as one entity or none of them will be

successful. The Following list describes the nature of transactions: ->All transactions have a begining and an end. ->A transaction can be saved or undone. ->If a transaction fails in the middle, no part of the transaction can be saved to the database.

TRANSACTIONAL CONTROL Transactional control is the ability to manage various transactions that may occur within a relational database management system. (Note keep in mind that transaction is group of DML statements). When a transaction is executed and completes successfully, the target table is not immediately changed, although it may appear so according to the output. When a transaction successfully completes, there are transactional control commands that are used to finalize the transaction. There are three commands used to control transactions: 1) COMMIT 2) ROLLBACK 3) SAVEPOINT When transaction has completed, it is not actually taken changes on database, the changes reflects are temporary and are discarded or saved by issuing transaction control commands. Explanatory figure is drawn as under.

TRANSACTIONAL CONTROL COMMANDS 1) COMMIT Command ->The commit command saves all transactions to the database since the last COMMIT or ROLLBACK command. Syntax commit [work]; The keyword commit is the only mandatory part of the syntax. Keyword work is optional; its only purpose is to make the command more userfriendly. example SQL>delete from emp where emp_age > 75; ->The above command deletes the records of those employee whose age is above 75 yrs. Though the changes are reflected on database they are not actually save as explained above they are stored in temporary area. To allow changes permanently on database commit command is used. SQL> COMMIT WORK;

->The above command will made changes permanently on database, since last commit or rollback command was issued. note here work is totally optional, it is just to make command more user friendly.

2) ROLLBACK Command ->The rollback command is the transactional control command used to undo transactions that have not already been saved to the database. The rollback command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued. Syntax SQL>rollback [work]; The keyword rollback is the only mandatory part of the syntax. Keyword work is optional; its only purpose is to make the command more userfriendly. example SQL>delete from emp where emp_age > 75; ->The above command deletes the records of those employee whose age is above 75 yrs. Though the changes are reflected on database they are not actually save as explained above they are stored in temporary area. To discards changes made on database rollback command is used. SQL> ROLLBACK WORK; ->The above command will discards changes made on database,since last commit or rollback command was issued. note here work is totally optional, it is just to make command more user friendly.

3) SAVEPOINT Command

->A savepoint is a point in a transaction that you can roll the transaction back to without rolling back the entire transaction. ->Practical example consider that a person walking and after passing some distance the road is split into two tracks. The person were not sure to choose which track, so before randomly selecting one track he make a signal flag, so that if the track was not the right one he can rollback to signal flag and select the right track. In this example the signal flag becomes the savepoint. Explanatory figure is as under.

Syntax SQL>SAVEPOINT ->Savepoint name should be explanatory. example ->Before deleting the records of employee whose age is above 75, we are not sure that whether we are given work to actually delete the records of employee whose age is above 75yrs or 80yrs. So before proceding further we should create savepoint here if we are been order later than it might create loss of information. SQL>savepoint orignally; SQL>delete from emp where emp_age > 75; ->The above command deletes the records of those employee whose age is above 75 yrs. Though the changes are reflected on database they are not actually save as explained above they are stored in temporary area.

->After some time we are given order to increase employee salary to 10%. We can increase by generating following command. But before that we will make savepoint to our data so incase if the top level management change their mind and order's no increment should be given than we have can simply pass rollback entry achieve present state. SQL>savepoint increm_sal; SQL>update emp set salary=salary + (salary*10); ->It will Increase salary of employee by 10%. ->After sometime top level management decided that salary of only programmer should be increased by 10% than only we have to do is just to pass entry of rollback before salary is updated. SQL>rollback to increm_sal; ->It will rollback the changes made to emp_salary now we can update salary records for employee who is programmer. If we have dout than we can put savepoint, otherwise savepoint is not compulsory. SQL>update emp set salary=salary + (salary*10); where emp_status='PROGRAMMER'; ->It will increase salary of only programmers. If all the changes have been taken place and now we have decided that no further changes require and we have to made changes to apply on database permanently than we can simply generate commit command to reflect changes permanently on database. SQL>commit work;

SQL OPERATORS
The Operators Supported by SQL*Plus are as under 1) Comparision Operators 2) Logical Operators 3) Arithmetic Operators 4) Operators used to negate conditions They are discussed in brief as under. SQL COMPARISION OPERATORS Comparision Operators as the name sujjests are used to test values in SQLstatement. The comparision operators are as under * Equality (=) * Non-Equality (<>) * Greater-than (>) * Less-than (<) * Greater-than or equal to (>=) * Less-than or equal to (<=) All Operators Works according to their names. For example:1)SQL> select * from emp where emp_name='RAHUL'; ->It will select all details of employee whose name is rahul. 2) SQL> select emp_name from emp where emp_age > 50; -> It will list names of those employee whose age is above 50 yrs. 3) SQL> select emp_name from emp where emp_job = 'ACCOUNTANT' OR emp_job= 'MUNIM'; ->It will list names of those employee whose status is munim or accountant

in the company. ->Note, if any of condition satisfies than the record will display as they are joint using or operator(discussed later).

SQL LOGICAL OPERATORS -> Logical operators are those operators that are use SQL keywords to make comparision instead of symbols. ->A Logical operator is used to combine the results of two conditions. The Logical Operators are AND, OR and NOT. They also covers * LIKE * BETWEEN * IN * IS NULL * ALL and ANY

AND- AND operator display records only when both conditions are satisfied. eg: SQL>select * from emp where emp_age < emp_name="'SAJID';">The above eg shows rows for those employee whose age is less than 50 yrs and name is sajid OR- OR operator display records on matching of any condition. eg: SQL>select * from emp where emp_age < emp_name="'SAJID';">The above eg shows rows for those employee whose age is less than 50 yrs or name is sajid. NOT- explained under negate operators. LIKE ->LIKE operator is used to search a character pattern, without knowing

exact character value. ->The LIKE operator used wildcard operators to compare a value to similar values. ->There are two wildcards used in conjunction with LIKE operator. ( % ) The percent sign-The percent sign represents Zero, one or multiple characters. ( _ ) The Underscore-The underscore represents single number or characters. ->These symbols can be used in combinations. eg: 1)SQL> select * from emp where emp_name LIKE 'A%'; ->Finds any name that start with A and continues for any length. 2) SQL>select * from emp where emp_name LIKE '%A'; ->Finds any name that ends with A. 3) SQL>select * from emp where emp_name LIKE '%A%'; ->Finds any name that have A in any position. 4) SQL>select * from emp where emp_salary LIKE '3___5'; ->Finds any value in a five digit number that starts with 3 and end with 5. 5) SQL>select * from emp where emp_salary LIKE '_5%5'; ->Finds any values that have a 5 in the second position and ends with a 5.

BETWEEN ->The BETWEEN operator is an extension of comparision operator as to make more user friendly. ->The BETWEEN operator is used to search for values whose minimum and maximum values are given. Maximum and minimum values are included as a part of search. -> A Between operator can be used with both character and numeric datatypes. However, one cannot mix the data types. eg: 1)SQL>select * from emp where emp_salary BETWEEN 5000 AND 10000; ->It searches for those employee whose salary is lies between 5000 and 10000, including the values 5000 and 10000.

IN ->The IN operator search the value from a predetermined list, if any of the value matches than row will be displayed. eg: 1)SQL>select * from emp where emp_job IN ('ACCOUNTANT','PROGRAMMER','OPERATOR'); ->It will display all details of those employee whose status in company is either accountant, programmer or operator.Note IN operator is basically use to remove multiple OR operators. The above statement using OR operator will be emp_job='ACCOUNTANT' OR emp_job='PROGRAMMER' OR emp_job='OPERATOR'; Note here emp_job is repeated three times which is not efficient way of generating query, so using IN operator we can reduce our burden and also make our statement more efficient. 2)SQL>select * from emp where

emp_depart_no IN ('5','10','15','20'); ->It will display details of those employee whose department number is either 5,10,15 or 20.

IS NULL ->IS NULL operator is used to compare a value with a NULL value. eg: ->Let search for the employee who haven't have their email-id 1) SQL> select * fromemp where email_id IS NULL; ->It will display records of those employee who haven't created their emailid. NOTE:- If you tried NULL operator to use with equality operator it will not give proper result.consider above eg. if you modify above statement using equality operator it will display improper result. email_id = NULL does not find a NULL value. You will be prompted with the message no rows selected even though there are rows with a NULL values. 2)SQL>select * from emp where emp_salary IS NULL; ->It will display records of those employee whose pay field is NULL. This is consider as invalid's records and should be deleted immediately.

ALL and ANY ALL ->The ALL operator compares a value to all values in another value set. eg: 1)SQL>select * from emp where emp_salary > ALL (select emp_salary from emp where emp_job = 'OPERATOR'); ->It will compares salary value to see whether it is greater than all salaries

of the employee whose status is operator. 2)SQL>select * from emp where emp_age <= ALL (select emp_age from emp where emp_state='CA'); ->It will compares age value to see whether it is less than or equal to all employee's age who is staying in CA. ANY ->The ANY operator compares a value to any values in another value set. eg: 1)SQL>select * from emp where emp_salary > ANY (select emp_salary from emp where emp_job = 'PROGRAMMER'); ->It will compares salary value to see whether it is greater than ANY salaries of the employee whose status is programmer. 2)SQL>select * from emp where emp_age <= ANY (select emp_age from emp where emp_state='CA'); ->It will compares age value to see whether it is less than or equal to any employee's age who is staying in CA.

SQL ARITHMETIC OPERATORS ->The arithmetic operators are mentioned as under 1) Addition ( + ) 2) Subtraction ( - ) 3) Multiplication ( * ) 4) Division ( / ) They work same as we have been taught so far. ->Let consider usage of arithmetic operator by following result table It contains field like rno, stname, std, div, totsub, totmarks. where rno is roll number, stname is student name, std is standard, div is

division, totsub is total subjects and totmarks is total marks. 1) To find percentage of all student SQL>select rno,stname,(totmarks / totsub) as percentage from result; ->Here help of division operator is taken to get percentage. CONCEPT OF ALIASES Aliases - Aliases is a temporary name assign to the field created at execution of statement or field already there in a table. consider the above example, field is created at the execution of statement and the name percentage is aliases for it. eg: 1)SQL>select ename as employee_name from emp; ->here field is already there in a table and temporary name is created to display field title more user friendly. ->Note aliases is not compulsory on a field it is used just to interface more user friendly with sql statements. Now back to the discussion of arithmetic operators, continue with the examples 2)SQL>select prodname as Product_Name,qty as Quantity, price as Price_per _unit,(qty*price) as Amount from product where prodname = 'SCREW'; ->Here query contains aliases Product_Name for prodname, Quantity for qty, Price_per_unit for price and Amount for (qty*price) ->This query display product name, quantity, price and amount for records whose prodname is screw. ->Here Amount is a field which will be created at the time of execution. It uses the multiplication operator. Similarly we use arithmetic operators according to our requirement but the

only point to note is that while using multiple operators operators works according to the precedence. * and / have higher priority than + and - operator, but we can make priority of + and - higher than * and / by adding parenthesis to the statement.

SQL NEGATE OPERATORS The Negate Operators reverses the meaning of the logical operators with which it is used. We have explained some NOT operators which are mentioned as under. * NOT EQUAL ( <> ) or ( != ). * NOT BETWEEN * IS NOT NULL * NOT LIKE * NOT IN NOT EQUAL ->Not equal works exactly oposite to the equal operator. eg: 1)SQL>select * from emp where emp_job <> 'ACCOUNTANT'; ->Here all records are selected excluding those whose status is accountant in company. 2)SQL>select * from emp where emp_salary != 5000; ->Selects all records excluding those whose salary is 5000. NOTE:- Operator ( <> ) and ( != ) works same. NOT BETWEEN -> This operator is used negate the between operator. eg: 1)SQL>select * from emp

where emp_salary NOT BETWEEN 2000 and 3000. ->It will select all records excluding those whose salary is between 2000 and 3000, including 2000 and 3000. IS NOT NULL ->It will check whether the selected field is not empty(null). eg: 1)SQL>select * from emp where email_id IS NOT NULL; ->Selects records of those employee who have their email-id. NOT LIKE ->The NOT LIKE operator used wildcard operators to compare a value that is not similar. ->It supports both wildcard character that are mentioned in like operators. eg: 1)SQL> select * from emp where emp_name NOT LIKE 'A%'; ->Finds any name that do not start with A and continues for any length. 2) SQL>select * from emp where emp_name NOT LIKE '%A'; ->Finds any name that do not ends with A. 3) SQL>select * from emp where emp_salary NOT LIKE '1___0'; ->Finds any value in a five digit number that do not starts with 1 and end with 0. NOT IN ->The NOT IN operator search the value that is not mentioned in a

predetermined list, if any of the value matches than row will be displayed. eg: 1)SQL>select * from emp where emp_job NOT IN ('PROGRAMMER','OPERATOR'); ->It will display all details of employee excluding those whose status in company is either programmer or operator. 2)SQL>select * from emp where emp_depart_no NOT IN ('5','10','15','20'); ->It will display details of employee excluding those whose department number is either 5,10,15 or 20.

Basics of SQL Server 2005


Lets begin with basics of SQL Server 2005 In this article you will learn

How to Create Database in SQL Server 2005 How to Create Table in SQL Server 2005 How to Create Database Diagram in SQL Server 2005 How to Create Relationship among Tables in SQL Server 2005 How to Insert Data in SQL Server 2005 First of all logged in to SQL Server 2005 Database with Administrator rights as most of the stuff we gona do require admin rights. Creating Database in SQL Server 2005 Right click Database Folder and click Database as shown in Figure. Note: You can also download the script file and run in newly created database

Now type your desired database name and choose appropriate settings for your desired database. I have selected all default settings here and press OK button

So our "MySampleDatabase" Is created.

While working with Windows Vista Note: You may receive error "An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)"CREATE DATABASE permission denied in database 'master'. (Microsoft SQL Server, Error: 262) To overcome this error in Windows Vista you need explicitly logon as Administrator as shown in figure

So after creation of Database it consist of various database object as shown in figure.

Creating Tables in SQL Server 2005 database Now, right click the newly created MySamplePractise Database and add new table

This open the table in design mode, Lets create customer table and choose appropriate datatype, if you are not sure about choosing the correct datatype in sql server 2005 refer this article

Here, CustomerID is Identity field, that is Auto generated by system. It is similar to AutoNumber field in MS Access and Sequence in Oracle. Understanding Identity Specification Attribute.

(Is Identity) - Yes : will generate autonumber Identity Increment - It is number of increment you want from the previously generated ID, here i have taken 1. Identity Seed - It commands SQL Server 2005 from where to start generating autonumber. Here, I have taken value 1000, so it will generate autonumber from 1001 Constraint Constraint is a check which is made on table which must be followed by user entering data. It reduce the number of Invalid data feed-in into system by prechecking its validity. In this table 2 constraint are used that is "Allow Null" and "Primary Key"

Allow Null Constraint - If checked than will Allow Null values in field, else it will not allow you to bypass the column without entering data. Primary Key Constraint - It checks that each record in table is unique and not null. To refer more on Keys Creating Primary Key on Column of SQL Server 2005 Right click the column field and set the field as Primary Key

Now in similar fashion create Order Table, OrderDetails Table, Product Table, ProductType Table. Order Table

OrderDetails Table

Product Table

ProductType Table

so your object explorer looks as under

Creating Database Diagram in SQL Server 2005

Next step select Table and press Add button

Adding a releationship among tables Right click the "Many" Table as They don't allow to change foreign key table in Releationship dialog. Example: Click on Orders Table, as 1 Customer can place Many Orders

Foreign Key Relationship dialog box will appear, press add button and you will find details appear on right pane of dialog box.

Now click the open dialog button on right of "Table And Columns Specification" from right pane of dialog box. For creating relationship between Orders and Customer, CustomerID is used. Select Table "Customer" for Primary Key Table and table "Orders" for Foreign Key.

And press ok button to create relationship between two table. Advantage of creating relationship

It will not allow to enter orders details without customer information. That is it allow to enter orders details of valid customer. It will not allow to delete customer information, until all details associated with customer is delete. You may change setting as per your need by selecting No from dropdown of "Enforce for Replication" and "Enforce foreign key constraint" Similarly you need to create relationship between remaining tables.

1 Customer can place Many Orders 1 Order can have Many OrderDetails 1 Product can be in Many OrderDetails 1 ProductType consist of Many Product At the end Relationship diagram looks as under

When you are dealing with large database with 100's of table, you can change the view of table by selecting all table with "ctrl+A" and right clicking

any of selected table and change its views so that it is convinent to view.

A sample diagram will now look as under

So now as Database Designing and Table creation is done, lets enter some sample data Inserting Record in Table for SQL Server 2005, right click the table and select open table, it gives you MS Access type editor to enter data. Note those who prefer inserting data through SQL Query or Script may open SQL Editor. Similarly making change in table design click modify.

Now key-in the data in customer table, as shown in figure. Note: here CustomerID is generated automatically and its value is starting from 1001 as we have set Increment Seed to 1000. Insert Record into Customer Table.

Similarly enter data for other tables. Remember, you don't need to enter data into CustomerID, as it is Identity field wherein data is auto generated by system. As we have enforce

Referential Integrity by creating relationship, so you are not allowed to add record in orders table with anonymous customerId.

Datatypes in SQL Server 2005


Lets begin with easy series of understanding SQL Server 2005. If you are begineer and want to gain Database and RDBMS knowledge in seconds this SQL Tutorial

Why choosing datatype is important or what the disadvantage of choosing wrong datatype?

Choosing too small datatype cannot meet the system need and at some point your system may become useless. Example use of smalldatetime (2 bytes) datatype over datetime (4 bytes) datatype can make your system useless when you need to provide information based on millisecond data.

Choosing too large datatype can waste space and increase expense. Example: let say choosing of smallint to store age data is wastage of space as same information can be stored in tinyint and serves the need. So here we can save space and money by allocating tinyint (1 byte) over smallint (2 bytes).

Choosing incorect datatype can degrades performance, because of conversion of data. Example choosing a char datatype to store datetime information will degrades performance as it requires frequent boxing and unboxing of type.

Choosing between tinyint, smallint, int, bigint datatype in SQL Server2005 You should use int datatype to store exact number. Now depends on chart shown below you and your maximum and minimum data range consideration you can able to decide which is better to go with. Data type bigint int smallint tinyint Range Storage -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) 8 Bytes -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) -2^15 (-32,768) to 2^15-1 (32,767) 0 to 255 4 Bytes 2 Bytes 1 Byte

Choosing between datetime and smalldatetime datatype in SQL Server 2005 datetime datatype are used for storing date and time information. Comparision chart Data type Range January 1, 1753, through December 31, 9999 datetime smalldatetime January 1, 1900, through June 6, 2079

Storage/Accuracy 4 Bytes/3.33 milliseconds 2 Bytes/1 minute

Difference between datetime and smalldatetime datatype in SQL Server 2005 datetime is more accurate than smalldatetime datatype. datetime datatype stores milliseconds data while smalldatetime datatype doesn't store millisecond data and thus it is less accurate. But in most cases we don't require such a accurate information, so in this case you can storing datetime

in smalldatetime datatype and saves the extra 2 bytes storage space. Example: DOJ details of employee doesn't require such a accuracy level so you can use smalldatetime datatype.

Choosing between char, varchar, varchar(MAX) and text datatype in SQL Server 2005 char, varchar, varchar(MAX) and text datatype are used for storing character string. Note you cannot store multilingual data. i.e. You will not allowed to store japanes or hindi characters. Char datatype

Stores character (non-unicode) data. Stores data in fixed-length format. Choose char datatype when size of data is consistent. Varchar datatype

Stores Character (non-unicode) data. Stores data in variable-length format. Choose varchar datatype when size of data varies between 8000 bytes Varchar(MAX) datatype

Stores Character (non-unicode) data. Stores data in variable-length format. Choose varchar datatype when size of data varies and it may exceeds 8000 bytes. Text datatype

Text datatype is used in previous versions of SQL Server, it is recommended to use Varchar(MAX) instead of Text datatype,

as ntext,text, and image data types will be removed in a future version ofMicrosoft SQL Server Stores large amount of character string Stores data in variable-length format. Choose text datatype when size of data varies may exceeds 8000 bytes. Difference between char and varchar datatype char stores fixed-length character data while varchar stores variable-length character data. Difference between varchar and varchar(MAX) datatype varchar stores variable-length character data whose range varies upto 8000 bytes, varchar(MAX) stores variable-length character data whose range may varies beyond 8000 bytes. Should i choose varchar(MAX) or text datatype They both provides same functionality, but it is better to choose varchar(MAX) over text datatype as text data types will be removed in a future version of Microsoft SQL Server.

Choosing between nchar, nvarchar, nvarchar(MAX) and ntext datatype in SQL Server 2005 nchar, nvarchar, nvarchar(MAX) and ntext datatype are used for storing unicode character string. you can store multilingual data. i.e. You can store japanes or hindi characters. nChar datatype

Stores unicode character data. Stores data in fixed-length format. Choose nchar datatype when size of data is consistent and you want to store multi-lingual data. nVarchar datatype

Stores unicode Character data. Stores data in variable-length format. Choose nvarchar datatype when size of data varies upto 4000 bytes and data can be multi-lingual. nVarchar(MAX) datatype

Stores unicode Character data. Stores data in variable-length format. Choose nvarchar datatype when size of data varies and it may exceeds 4000 bytes and data can be multi-lingual. nText datatype

nText datatype is used in previous versions of SQL Server, it is recommended to use nVarchar(MAX) instead of Text datatype, as ntext,text, and image data types will be removed in a future version of Microsoft SQL Server Stores large amount of character string Stores data in variable-length format. Choose ntext datatype when size of data varies may exceeds 4000 bytes and data can be multi-lingual. Difference between nchar and nvarchar datatype nchar stores fixed-length unicode character data while nvarchar stores variable-length unicode character data. Difference between nvarchar and nvarchar(MAX) datatype varchar stores variable-length unicode character data whose range varies upto 4000 bytes, varchar(MAX) stores variable-length unicode character data whose range may varies beyond 4000 bytes. Should i choose varchar(MAX) or text datatype They both provides same functionality, but it is better to choose varchar(MAX) over text datatype as text data types will be removed in a future version of Microsoft SQL Server.

Difference between

char and nchar varchar and nvarchar varchar(MAX) and nvarchar(MAX) and text and ntext datatype Former can stores non-unicode character strings while latter can stores unicode character string. Former require less memory, while latter requires doubles as much memory as former. i.e. char can stores upto 8000 bytes while nchar can stores upto 4000 bytes, because regular data are of 8bits while unicode data require 16bits storage space. Example: Former is used to store character data which doesn't suppor multi-language support, while latter can support character multi-language character support. For more detail

Choosing between numeric and decimal datatype in SQL Server 2005 Numeric and decimal datatype both are used when the data have fixed precision and scale. Precision - Maximum total digit that can be stored on both left and right of decimal point. Scale - Mamimum total digit that can be stored on right of decimal point. There is no functional difference between numeric and decimal datatype. For more detail

Choosing between money and smallmoney datatype in SQL Server 2005

Money and smallmoney datatype are used for storing monetary data. Data type money smallmoney Range -922,337,203,685,477.5808 to 922,337,203,685,477.5807 - 214,748.3648 to 214,748.3647 Storage 8 bytes 4 bytes

Choosing between float and real datatype in SQL Server 2005 Both float and real datatype are approximate datatype. i.e. Not all values in datatype can be represented exactly. Data type float real Range - 1.79E+308 to -2.23E-308, 0 and 2.23E-308 to 1.79E+308 - 3.40E + 38 to -1.18E - 38, 0 and 1.18E - 38 to 3.40E + 38 Storage Depends on the value of n 4 Bytes

syntax of float [ ( n ) ] SQL Server 2005 treats n as one of two possible values. If 1<=n<=24, n is treated as 24. If 25<=n<=53, n is treated as 53. n value 1-24 25-53 7 digits 15 digits Precision 4 bytes 8 bytes Storage size

Choosing between binary, varbinary and varbinary(MAX) datatype in SQL Server 2005

Use binary when the sizes of the column data entries are consistent. Use varbinary when the sizes of the column data entries vary considerably. Use varbinary(max) when the column data entries exceed 8,000 bytes.

For more details

bit datatype - bit datatype can take a value of 1, 0, or NULL. It consumes 1 byte. Note: The string values TRUE and FALSE can be converted to bitvalues: TRUE is converted to 1 and FALSE is converted to 0.

xml datatype - SQL Server 2005 introduces a native data type called XML. By using this feature, you can create a table with one or more columns of type XML besides relational columns. These XML values are stored in an internal format as large binary objects (BLOB), which enable the XML model to support document order and recursive structures. Because of the seamless integration of the XML data type with SQL Server's storage and programming models, you can query and update XML documents and even write joins between XML data and relational data in your database. SQL Server 2005 uses the same query engine and optimizer for querying XML data as it does for relational data, radically enhancing your ability to work with

Query execution in SQL Server 2005


SQL Query execution In this article you will explore o o o How to execute query within sql server 2005 environment How to filter records with where clause How to arrange records with order by clause How to group records by group clause How to filter grouped records with having clause Concept of Joins, explanation and example of Inner Join Outer Join Left Outer Join Right Outer Join Full Join or Cross Join Self Join

Concept of sub queries, with explanation and example. Concept of correlated sub queries, with explanation and example. Ok, so lets begin... For execution of Query, Open New Query Editor as shown in figure.

Now lets execute different data manipulation statement. Select Database to perform Database Operation using "use" Statement --Select Database for Data Manipulation opperation use MySamplePractise For mastering, Data Manipulation from beginner to expert, Study following Example with 150+ Queries. Select Statement Execution in SQL Server 2005 --Display each details of all Customers select * from customer --Display FirstName, City and Country Details of Customers select FirstName, City, Country from Customer

--Using Alias to display details, Display "Customer Name" by concating FirstName and LastName of Customer select FirstName + ' ' + LastName as 'Customer Name' from Customer

Filtering Records with "Where Clause" --Display Customers from country USA select * from Customer where Country = 'USA' --Display Customers from All countries except USA select * from Customer where Country <> 'USA' --Display details of Customers whose CustomerID in a range from 1003 to 1008 select * from Customer where CustomerID >= 1003 and CustomerID <= 1008 --You can replace above statement by using Between statement. --Between will show customer with customerID 1003 to 1008. select * from Customer where CustomerID between 1003 and 1008 --Display Customers whose LastName starts from P select * from Customer where LastName like 'P%' --Display Customers whose country name ends with A select * from Customer where Country like '%A' --Display Customers whose FirstName or LastName consist of word khan select * from Customer where FirstName like '%Khan%' or LastName like '%Khan%' --Display Customers whose FirstName second character is A select * from Customer where FirstName like '_A%'

Ordering Records with "Order by" Caluse --Note: by default when neither ASC (for Ascending) or DESC (for descending) is specify, it is ordered in Ascending order. --Display Customers of USA country ordered by state select * from Customer where Country='USA' order by State --Display Customers of USA country ordered by state in descending order. select * from Customer where Country='USA' order by State DESC --Order Customer by LastName in descending order and FirstName in Ascending order. select * from Customer order by LastName DESC, FirstName ASC Grouping Records by "Group by" Caluse --Display Count of Customers in each country select Country,Count(CustomerID) from Customer group by country --Display Count of Customers group the data by Country and State select Country, state, Count(CustomerID) from Customer group by country, state Filtering Grouped data by "Having" Caluse --Display Count of Customers country wise and display those countries only where more than 2 customers are available. select Country,Count(CustomerID) from Customer group by country having Count(CustomerID) > 2

Using both Where and Having Clause to Filter data. --Display Count of Customers from country "USA", state wise where in display details of those state only which have atleast 2 Customer --It will display only Customer Count from "NJ" state of "USA" country. select State,Count(CustomerID) from Customer where state='NJ' and country='USA'

group by state having count(CustomerID) > 2

Using Order by to arrange Grouped data --Display Count of Customers from country "USA", state wise and it should display details in descending order of state of those state where Customers are atleast 2. select State,Count(CustomerID) from Customer where country='USA' group by state having count(CustomerID) > 2 Order by state desc Now, lets display data from multiple table. For that we need to understand Joins so lets begin what is Join and how many different ways to display data.

Joins in SQL Server Joins in SQL are used to combine the data from two or more tables on a common column between the two tables. Different types of Joins in SQL Server and its explanation

o o o

Inner Join Outer Join Left Outer Join Right Outer Join Full Outer Join or Cross Join Self Join Lets go through the concept quickly.

Inner Join Inner Join return those rows which are common in both the tables. In other words, Inner Join displays only the rows that have matching rows in both the tables. Note: Nulls are excluded. Another thing you may even write just "Join" instead of "Inner Join" as default join is "Inner Join" Example of Inner Join We can use two types of syntax to write Join Query, that is

Join Query with ANSI Join Syntax Join Query with Microsoft Join Syntax well i will go through both example, but we will follow ANSI Join Syntax as it is widely used, but according to me Microsoft Join Syntax is easy... Use Northwind Method 1: ANSI JOIN Syntax select * from orders inner join [order details] on orders.orderid = [order details].orderid Method 2: Former Microsoft JOIN Syntax select * from orders, [order details] where orders.orderid = [order details].orderid Both query will be generate the same result. Now, lets turn to example from our SamplePractise Database --Display Details of Customer who have placed order. select LastName, FirstName, Country, OrderId, OrderDate from Customer inner Join Orders on Customer.CustomerID = Orders.CustomerID --or-- Note: Inner join is default join and so you can write just join instead of inner join. select LastName, FirstName, Country, OrderId, OrderDate from Customer Join Orders on Customer.CustomerID = Orders.CustomerID --Display Details of Customer living in "USA" who have placed order and arrange data by latest order placed. select LastName, FirstName, Country, OrderId, OrderDate from Customer inner Join Orders on Customer.CustomerID = Orders.CustomerID where Country = 'USA' order by OrderDate DESC

Outer Join Outer Join, return all the rows from at least one of the table mentioned in the Join clause.

Lets understand 3 types of outer join

Left Outer Join Left outer join returns all the records from left table and only matching records from right table. Example of Left Outer Join: --Display details of all Customers and order details for those customer who have place any order select LastName, FirstName, Country, OrderID, OrderDate from Customer Left Outer Join Orders on Customer.CustomerId = Orders.CustomerID

Right Outer Join Right outer join returns all the records from right table and only matching records from left table. Example of Right Outer Join: --Display all product type and product available in it select producttype, productname from producttype right outer join product on producttype.producttypeid = product.producttypeid order by producttype

Full Join or Cross Join A cross join returns the sets of records from the two joined tables. If A and B are two sets then cross join = A X B. Example of Full Join or Cross Join --Display all orders and all its details select * from orders cross join orderdetails -orselect * from orders, orderdetails

Self Join A table is join to itself in a self join. Example for Self Join: --Display details of customer living in same state

select distinct a.* from customer a, customer b where a.customerid <> b.customerid and a.state = b.state order by state --Consider an Example of Employee Table, wherein you want to find details of all the employee drawing same salary select distinct a.* from employee a, employee b where a.empid <> b.empid and a.salary = b.salary

Joining three or more table In joining three or more tables, join applies to only one relationship, and each relationship represents an association between only two tables. FROM table1 join table2 ON table1.primarykey = table2.foreignkey join table3 ON table2.primarykey = table3.foreignkey The first join applies to table1 and table2, the second join applies to table2and table3. Example of Joining three or more tables --Sample syntax select * from table1 left outer join table2 on (table1.field1 = table2.field1), join table3 on (table2.field2 = table3.field2) --Display details from customer, order and orderdetails table. select c.lastname, c.firstname, o.orderid, o.orderdate, od.orderdetailsid, p.productname from customer c Inner Join orders o on (c.customerid = o.customerid) inner join orderdetails od on (o.orderid = od.orderid) inner join product p on (od.productid = p.productid) order by o.orderid, od.orderdetailsid, p.productname

Sub Queries A query within another query is called sub query. Example of Sub Query --Display details of customer who haven't placed any order select * from customer where customerid not in (select customerid from orders)

--Display details of customer belonging to "NJ" state of "USA" country has placed order. select * from customer where state = 'NJ' and customerid in (select customerid from orders)

Correlated Sub Queries A correlated subquery is a SELECT statement nested inside another T-SQLstatement, which contains a reference to one or more columns in the outer query. Therefore, the correlated subquery can be said to be dependent on the outer query. This is the main difference between a correlated subquery and just a plain subquery. A plain subquery is not dependent on the outer query, can be run independently of the outer query, and will return a result set. A correlated subquery, since it is dependent on the outer query will return a syntax errors if it is run by itself. Source of Information Example of Correlated Sub Queries --Display order information along with amount of order. select o.orderid, o.orderdate, (select sum(od.amount) from orderdetails od where o.orderid = od.orderid) as "Amount" from orders o --Display orderdetails along with product details. select od.orderdetailsid, (select p.productname from product p where od.productid = p.productid) as "ProductName", (select p.productprice from product p where od.productid = p.productid) as "ProductPrice", od.quantity as "Quantity", od.quantity * (select p.productprice from product p where od.productid = p.productid) as "Amount" from orderdetails od Note: you can also use ANY - To display any matching record within sub query ALL - To display details of those records who match all the criteria of sub query

SQL FUNCTION: Function in a database can be defined as the code segment consisting of a logical group of SQL statements which takes some input arguments (if required), run in a sequential order and returns the output either in the form of a single value or in the form of a table.Through this article, I am trying to give the overview of the System defined functions,User defined functions, their advantages, their disadvantages and their differences with the Stored procedures. Types of Functions: In SQL, Functions can be categorized into two categories:1. 2. System Defined Function User Defined Function (UDF)

In this article, I am going to use the following tables for the examples:CREATE TABLE [dbo]. [Employee]( [Empid] [Int] IDENTITY (1, 1) NOT NULL Primary key, [EmpNumber] [nvarchar](50) NOT NULL, [EmpFirstName] [nvarchar](150) NOT NULL, [EmpLAStName] [nvarchar](150) NULL, [EmpEmail] [nvarchar](150) NULL, [Managerid] [int] NULL ) CREATE TABLE [dbo].[Department]( [Departmentid] [int] IDENTITY (1, 1) NOT NULL primary key, [DepartmentName] [nvarchar](255) NOT NULL ) CREATE TABLE [dbo].[EmpdepartmentInfo]

( Empdepartmentid int identity(1,1) primary key, Empid int not null, departmentid int not null ) SQL scripts for entering the data into the table Employee:Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A001','Samir','Singh','samir@abc.com',2) Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A002','Amit','Kumar','amit@abc.com',1) Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A003','Neha','Sharma','neha@abc.com',1) Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A004','Vivek','Kumar','vivek@abc.com',1) Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A005',' AvinASh', 'Dubey','avinASh@abc.com',2)

Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A006',' Sanjay','Kumar',' sanjay@abc.com',5) Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A007','Rajiv','Kumar','rajiv@abc.com',5) Insert Into Employee (EmpNumber,EmpFirstName,EmpLAStName,EmpEmail,Managerid ) Values('A008','Manish','Kumar','manish@abc.com',6) SQL scripts for entering the data into the table Department:Insert Into Department(DepartmentName) Values('Testing') Insert Into Department(DepartmentName) Values('Admin') Insert Into Department(DepartmentName) Values('HR') Insert Into Department(DepartmentName) Values('Technology') SQL scripts for entering the data into the table EmpdepartmentInfo:Insert Into [EmpdepartmentInfo](empid, departmentid)

Values(1,1) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(2,2) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(3,3) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(4,4) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(4,5) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(5,1) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(6,2) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(7,3) Insert Into [EmpdepartmentInfo](empid, departmentid) Values(8,4) System defined function can again be further divided into further subsections which are given below:1. Aggregate function. Example: - Avg (), Min (), Max () 2. Configuration function.

Example:-@@servername (), @@version() 3. Cursor function. Example: -@@Fetch_status 4. Date and Time function. Example: - Getdate (), Month (), Day (), Year () 5. Mathematical function. Example: - Floor (), Abs () 6. Metadata function. Example: - Db_Name (), File_Name () 7. Other functions. Example: - cast (), convert () 8. Rowset function. Example: - Openxml (), Openrowset () 9. Security function. Example:-user(), User_Id (), User_Name () 10. String function. Example: - Char (), Left (), Len () 11. System Statistical function. Example:-@@connections

12. Text and Image function Example: - Textvalid () Types of UDF:Similarly, UDF can be divided Into 3 categories:1. 2. Scalar UDF Inline Table UDF

3. Multi statements UDF Scalar UDF:The UDFs which only returns only single values comes into this category. Syntax for creating Scalar UDFs:CREATE FUNCTION (FUNCTION name) ( (Input Variable name) (data type) ) Returns (returning variable data type) AS BEGIN (FUNCTION body) Return (returning variable name) End Example CREATE FUNCTION fn_getempname

( @empid Int ) RETURNS nvarchar(100) AS BEGIN DECLARE @empname AS Nvarchar(100) SELECT @empname=empfirstname + ' ' + emplAStname FROM employee WHERE empid=@empid RETURN @empname END Syntax for executing the Scalar UDF SELECT dbo. (FUNCTION name) (input variable name) For example, to execute the above UDF we use the following syntax:SELECT DBO.[fn_getempname](1) /* Here 1 is the empid*/ or SELECT DBO.[fn_getempname](1) AS EmployeeName/*To get the output under the column EmployeeName */

If we want to store the value of this FUNCTION in an variable the we have to use the following syntax:DECLARE @name AS nvarchar(100) SELECT @name =dbo.[fn_getempname](1) SELECT @name Here we first needs to define a variable (@name) which will be going to store the value return by the function and then used this variable in the SELECT statement to store the value. Result EmployeeName Samir Singh Explanation This function will return the name of the employee whose empid we passed in the function as the Input parameter. Inline Table UDF:The UDF which contains a single inline SQL statement and returns the data in the form of table is called Inline Table UDF. Syntax for creating Inline Table UDF:CREATE FUNCTION (FUNCTION name) (

(Input Variable name) (data type) ) Returns Table AS Return (SELECT statement) Example:Create Function fn_getempinfo ( @empid Int ) Returns Table As Return Select empid,empnumber,empfirstname,emplastname,empemail From employee Where empid=@empid Syntax for executing the Inline Table UDFs Select (columns names) from dbo. (Function name) (Input Parameter)

SELECT empid,empnumber,empfirstname,emplastname,empemail FROM dbo.[fn_getempinfo](1) Result Empid Empnumber Empfirstname Emplastname

Empemail 1 A001 samir@abc.com Explanation This FUNCTION will return the columns empid, empnumber, empfirstname, emplAStname, empemail of the employee AS a table variable whose employeeid is given AS the input parameter to the FUNCTION. Multi statements UDF: The UDFs which contain multiple SQL statements to returns the data in the form of table is called Multi Statements UDFs. Syntax for creating Multi Statements UDFs: Create Function ( (Input Variable name) (data type) ) Returns (table variable) Table (table columns) As Begin (Function body) Return End Example Samir Singh

CREATE FUNCTION fn_GetEmpdepartmentinfo ( @empid Int ) Returns @Empproject Table ( Employeename Nvarchar(100),Empemail Nvarchar(50),Departmentname Nvarchar(100) ) AS BEGIN Insert Into @Empproject(Employeename,Empemail,Departmentname) SELECT empfirstname + ' '+ emplAStname ,empemail,departmentname FROM employee Inner Join EmpdepartmentInfo On employee.empid=EmpdepartmentInfo.empid Inner join Department On EmpdepartmentInfo.departmentid=Department.departmentid WHERE employee.empid=@empid RETURN END Syntax for executing the Multi Statements UDF Select (columns names) from dbo. (Function name) (Input Parameter) SELECT Employeename,Empemail,Departmentname

FROM dbo.[fn_GetEmpdepartmentinfo](1) Result Employeename Samir Singh Explanation This function will returns the Employeename,Empemail,Departmentname of the employee whose empid we pass as the input parameter to the function. Empemail samir@abc.com Departmentname Accounts

Difference between UDFs and Stored Procedures:1. A stored procedure can return a value or it may not return any value but in case of function, a function has to return a value. 2. Stored procedure in SQL Server cannot we executed within the DML statement. It has to be executed with the help of EXEC or EXECUTE keyword but a function can be executed within the DML statement. 3. A function can be called from within the Stored Procedure but a stored procedure cannot be called from within a function. 4. We can use result set return by the function as a table in Join statements but we can't use ResultSet return from stored procedure as table in Join statements. 5. Transaction management is not possible in function but it is possible in Stored procedures.

6. Print function cannot be called within the function but it can be called within the stored procedure. Advantages of UDF:1. SQL Functions can be used in a DML statement. It means we can use execute the FUNCTION within the SELECT statement. 2. We can use the recursive FUNCTION to get the hierarchical information. For example, if we want to get the all the employee which are directly or indirectly have the manager whose empid is given AS the input parameter(@managerid), then we can use the following FUNCTION which calls itself. CREATE FUNCTION fn_recuursivesample ( @managerid int, @mode int ) Returns @temporder table(employeeid int , managerid int) AS BEGIN DECLARE DECLARE DECLARE DECLARE @count AS int @empid AS int @next_empid AS int @next_orderid AS int

IF @mode=0 BEGIN

INSERT Into @temporder SELECT @managerid,(SELECT managerid FROM employee WHERE empid=@managerid) END SELECT @count=count(empid)FROM employee WHERE managerid=@managerid IF @count=1 BEGIN SELECT @empid=empid FROM employee WHERE managerid=@managerid INSERT Into @temporder Values(@empid,@managerid) INSERT Into @temporder SELECT * FROM dbo.fn_recuursivesample(@empid,1) END ELSE IF @count>1 BEGIN SELECT @empid=min(empid)FROM employee WHERE managerid=@managerid WHILE @empid>0 BEGIN Insert Into @temporder Values(@empid,@managerid) Insert Into @temporder SELECT * FROM dbo.fn_recuursivesample(@empid,1) SELECT @next_empid=isnull(min(empid),0) FROM employee WHERE empid >@empid and managerid=@managerid SET @empid=@next_empid END END RETURN END

Syntax to execute the above function SELECT employeeid, managerid FROM dbo. fn_recuursivesample(1,0) Result:Employeeid Managerid 1 0 2 1 5 2 6 5 8 6 7 5 3 1 4 4 3. We can use the Function in the Join queries. 4. We can used UDFs as the parametrized view(a view which take input parameters). 5. UDFs also reduce the compilation cost of SQL codes by caching the plans and reusing them for repeated executions which mean it does not need to be re-parsed and recompiled with each use and it result in better execution time. 6. We can use the WHERE clause to filter the rows as per our needs FROM the result set return by the Function. For example, in the above function fn_recuursivesample, if we want to get the empid of only those employee which are directly under the employee whose empid is given AS the input parameter, the we

can use the "WHERE" clause to filter the dataset return by the function. SELECT employeeid, managerid FROM dbo. fn_recuursivesample(1,0) WHERE managerid=1 It will give the following result:Employeeid 2 3 4 Managerid 1 1 1

7. UDFs can be used to divide the complex code into shorter and simple blocks of code which helps in maintenance of the code. Disadvantages of the UDF 1. 2. We cannot use temporary tables inside the UDF. We cannot use Print command inside the UDF.

3. We can't use the Insert, update and delete command inside the function. We can only use these commands on the table variable defined inside the function. 4. We cannot use the try catch statement inside the function for the debugging purpose which makes it difficult to debug. 5. We can't use transaction inside the function. 6. We can't call the stored procedure from inside the function. 7. We can't return multiple record sets from a function as we can do in case of Stored Procedure.

8. We can't use Getdate() function within a UDF. Conclusions Functions are the feature which is given by the SQL Server to make our complex code shorter and less complex. We can either use the Functions which are already provided by the SQL Server known as the System defined Function such as Avg (), Min (), Max () or we can write our own UDF. If we want to get only a scalar value as result, we can create Scalar UDFs or if we want to get a ResultSet, then we can create Inline Table UDFs or Multi statements UDFs. We can also used Functions in the SELECT statement and in join statements. But while creating the UDFs we should also keeps in our mind that no DML(Insert, Update, Delete) statement can be performed inside the UDF. Also we can't use temporary table inside the Function. Also we can't use transaction management inside the UDF.

Function Execution in SQL Server 2005


In this article you will learn, everything about using Function Execution inSQL Server 2005

String Functions Date and Time Functions Mathematical Functions String Functions String Functions are used for manipulating string expression. Note: string expression should be passed within single quote.

Len('') - Returns length of string.

o o o o o o o

Example: select Len("Shri Ganesh") will return 11 Lower('') - Convert all characters to lowercase characters. Example: select Lower('Shri Ganesh') will return shri ganesh Upper('') - Convert all characters to uppercase characters. Example: select Upper('Shri Ganesh') will return SHRI GANESH LTrim('') - Removes spaces from given character strings on left. Example: select LTrim(' Shri Ganesh') will return Shri Ganesh Note: It doesn't removes tab or line feed character. RTrim('') - Removes space from given character strings on right. Example: select LTrim('Shri Ganesh ') will return Shri Ganesh Note: It doesn't removes tab or line feed character. Trim('') - Removes spaces from given character strings from both left and right.

o o o o o o o

Example: select LTrim(' Shri Ganesh ') will return Shri Ganesh Note: It doesn't removes tab or line feed character. SubString('') - Returns a part of string from original string. SubString(character_expression, position, length) position - specifies where the substring begins. length - specifies the length of the substring as number of characters. Example: select SubString('Shri Ganesh',6,7) where in 6 - Starting position of sub string from given string. 6 - It is no. of characters to be extract from given string, starting from 6. That is it will return "Ganesh" As ganesh start from 6th character upto 6 characters. Replace('') - Replace the desired string within the original string. Replace(character_expression, searchstring, replacementstring)

SearchString - string which you want to replace. ReplaceString - new string which you want to replace with Example: select replace('Think High To Achieve High','High','Low') here, function search for every occurrence of High and replace it with Low. Original - Think High To Achieve High

o o

Result - Think Low To Achieve Low Right('') - extract particular characters from right part of given string expression.

Example: select right('Think High To Achieve High',15) will return "To Achieve High" This function will be helpful when you want particular characters from right part. Example: Let say i have social security nos. and i want to extract last 4 digit of it.

select select select select

right('111-11-1111',4) right('222-22-2222',4) right('333-33-3333',4) right('444-44-4444',4)

will will will will

return return return return

1111 2222 3333 4444

Date and Time Functions Date and Time Functions are used for manipulating Date and Time expression.

GetDate() - Returns current date and time of a system. Example: select GetDate() will return something like "2007-10-10 15:34:37.287" GetUTCDate() - Returns current date and time information as per UTC (Universal Time Coordinate or Greenwich Mean Time)
o

Example: select GetDate() will return something like "2007-10-10 15:34:37.287"

DatePart and Abbrevation, which we will be using with DatePart, DateADD, DateDIFF function. Datepart Year Quarter Month Dayofyear Day Week yy, yyyy qq, q mm, m dy, y dd, d wk, ww Abbreviations

Weekday Hour Minute Second Millisecond

dw, w Hh mi, n ss, s Ms

DatePart() - Returns an integer representing a datepart of a date. Note: Example are based on considering "2007-10-10 15:34:37.287" as GetDate() Example:

select DatePart("day",GetDate()) will return 10. select DatePart("hour",GetDate()) will return 16. select DatePart("dayofyear",GetDate()) will return 283. And so on... Syntax: DateADD(Abbrevation, number to be added, date) Example:

o o

DateADD() - Returns adds a date or time interval to a specified date.

select DateAdd("day",7,GetDate()) will return 2007-10-17 16:09:18.280 select DateAdd("month",20,GetDate()) will return 2009-06-10 16:10:02.643 And so on... Syntax: DateDIFF(Abbrevation, startdate, enddate) Note: If the end date is earlier than the start date, the function returnsa negative number. If the start and end dates are equal or fall within the same interval, the function returns zero. Example:

o o

DateDIFF() - Returns difference between two specified dates.

select DATEDIFF("mm", Getdate()-500,GETDATE()) will return 17 You must pass valid start and end date otherwise you will receive error.

Mathematical Functions

Mathematical Functions are used for manipulating Mathematical expression.

ABS() - Returns positive value of numeric expression. Example: In following example both statement will return 3.14

select ABS(3.14) select ABS(-3.14)

Ceiling() - Returns the smallest integer that is greater than or equal to a numeric expression.
o

Example: select Ceiling(3.14) will return 4 select Ceiling(-3.14) will return 3.

Floor() -Returns the largest integer that is less than or equal to a numeric expression.
o

Example: select Floor(3.14) will return 3 select Floor(-3.14) will return 4

Round() - Returns a numeric expression that is rounded to the specified length or precision.
o

Example: select Round(3.14, 1) will return 3.10 select Round(-3.17, 1) will return -3.20 select Round(3.12345, 4) will return 3.12350 select Round(3.12345, 3) will return 3.12300 Example: select power(2,3) will return 8

Power() - POWER(numeric_expression, power)

SQL Optimization Tips Use views and stored procedures instead of heavy-duty queries. This can reduce network traffic, because your client will send to

server only stored procedure or view name (perhaps with some parameters) instead of large heavy-duty queries text. This can be used to facilitate permission management also, because you can restrict user access to table columns they should not see. Try to use constraints instead of triggers, whenever possible. Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers, whenever possible. Use table variables instead of temporary tables. Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible. The table variables are available in SQL Server 2000 only. Try to use UNION ALL statement instead of UNION, whenever possible. The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist. Try to avoid using the DISTINCT clause, whenever possible. Because using the DISTINCT clause will result in some performance degradation, you should use this clause only when it is necessary. Try to avoid using SQL Server cursors, whenever possible. SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated sub-query or derived tables, if you need to perform row-by-row operations. Try to avoid the HAVING clause, whenever possible. The HAVING clause is used to restrict the result set returned by the GROUP BY clause. When you use GROUP BY with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows and aggregates their values, and then the HAVING clause eliminates undesired aggregated groups. In many cases, you can write your select statement so, that it will contain only WHERE and GROUP BY clauses without HAVING clause. This can improve the performance of your query. If you need to return the total table's row count, you can use alternative way instead of SELECT COUNT(*) statement. Because SELECT COUNT(*) statement make a full table scan to return the total table's row count, it can take very many time for the large

table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of SELECT COUNT(*): SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So, you can improve the speed of such queries in several times. Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement. This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement. Try to restrict the queries result set by using the WHERE clause. This can results in good performance benefits, because SQL Server will return to client only particular rows, not all rows from the table(s). This can reduce network traffic and boost the overall performance of the query. Use the select statements with TOP keyword or the SET ROWCOUNT statement, if you need to return only the first n rows. This can improve performance of your queries, because the smaller result set will be returned. This can also reduce the traffic between the server and the clients. Try to restrict the queries result set by returning only the particular columns from the table, not all table's columns. This can results in good performance benefits, because SQL Server will return to client only particular columns, not all table's columns. This can reduce network traffic and boost the overall performance of the query. 1.Indexes 2.avoid more number of triggers on the table 3.unnecessary complicated joins 4.correct use of Group by clause with the select list 5 In worst cases Denormalization

Index Optimization tips Every index increases the time in takes to perform INSERTS, UPDATES and DELETES, so the number of indexes should not be very much. Try to

use maximum 4-5 indexes on one table, not more. If you have read-only table, then the number of indexes may be increased. Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index. Try to create indexes on columns that have integer values rather than character values. If you create a composite (multi-column) index, the order of the columns in the key are very important. Try to order the columns in the key as to enhance selectivity, with the most selective columns to the leftmost of the key. If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns. Create surrogate integer primary key (identity for example) if your table will not have many insert operations. Clustered indexes are more preferable than nonclustered, if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY. If your application will be performing the same query over and over on the same table, consider creating a covering index on the table. You can use the SQL Server Profiler Create Trace Wizard with "Identify Scans of Large Tables" trace to determine which tables in your database may need indexes. This trace will show which tables are being scanned by queries instead of using an index. You can use sp_MSforeachtable undocumented stored procedure to rebuild all indexes in your database. Try to schedule it to execute during CPU idle time and slow production periods. sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"

You might also like