Basic DBMS Concept

download Basic DBMS Concept

of 97

Transcript of Basic DBMS Concept

  • 7/31/2019 Basic DBMS Concept

    1/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 toworry about the organization and location of data. The primary goal of aDBMS is to provide an environment which is both convenient and efficient touse in retrieving and storing information.

    B) A DATABASE STORAGE HIERARCHY 1) DATABASEA collection of data files integrated and organised into a simplecomprehensive file system, which is arranged to minimize duplication of dataand to provide conenient access to information within that system to satisfya wide variety of user needs.

    2) DATA FILESA 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 anemployee file.

    3) RECORDSA 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) FIELDIndividual 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 TERMS1) RELATION

    http://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.html
  • 7/31/2019 Basic DBMS Concept

    2/97

    A relationship is an association among several entitieseg:- A cusst_Acct relationship associates a customer with each account thatshe or he has.

    2) REDUNDANCYIf same piece of information is stored in database for number of times thedatabase is said to be redundant. We should check our database should notbe 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) andPayroll(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) INCONSISTENCYInconsistency 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 uptocertain 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 areupdated or not, if we update the address of one employee in emp_detailsand same details is not updated in payroll table, than database is said to bein inconsistent state.

    4) PROPAGATING UPDATESPropagating updates ensures users that any change made to record of onefiles, automatically made to other files. This process is known as Propagatingupdates. 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) INSTANCESThe collection of information stored in the database at a particular moment

  • 7/31/2019 Basic DBMS Concept

    3/97

    in time is called an instances of the database.

    6) SCHEMESThe overall design of the database is called the database schemes. Schemes

    are changed infrequently, if at all.

    7) USERSThere are four different types of database system users.

    - Application programmers :- A person who prepares application programare called application programmer. Application programs operates on thedata in all the usual ways: retrieving information, creating new information,deleting or changing existing information.

    - SOPHISTICATED USERS :- Sophisticated users interact with the systemwithout writing programs. Instead, they form their requests in adatabase query language . Each such query is submitted to a query processorwhose function is to take a DML statement and break it down intoinstructions that the database manager understands.

    - SPECIALIZED USERS :-Some sophisticated users write specialized

    database application that do not fit into the traditional data processingframework. Among these application are computer-aided design systems,knowledge-base and expert systems, systems that store data with complexdata typeseg:-For Graphics and Audio data.

    - END USERS :-Unsophisticated users interact with the system by invokingone of the permanent application programs that have been writtenpreviously.Thus they are persons who uses the information generated by acomputer based system. Retrival is the most common function for this classof user.

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

    http://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.html
  • 7/31/2019 Basic DBMS Concept

    4/97

    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 eachrecord 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.herecustomer_number of each entity in customer table is distinct so customer-number can be a primary key of customer-table.

    2) SUPER KEY :- If we add additional attributes to a primary key, theresulting combination would still uniquely identify an instance of the entityset. 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 ascandidate key.eg:-From above example of customer table,customer_socialsecurity_number is candidate key as it has all characteristicsof primary key.

    4) ALTERNATE KEY :-A candidate key that is not the primary key is calledan Alternate key.eg:- In above example, customer_socialsecurity_number is a candidate keybut not a primary key so it can be considered as alternate key.

    5) COMPOSITE KEY: - Creating more than one primary key are jointlyknown as composite key.eg:-In above example, if customer_number andcustomer_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 isreference in the current table , so it is known as foreign key in the currenttable. A foreign key is one or more columns whose value must exist in theprimary key of another table.

    http://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.html
  • 7/31/2019 Basic DBMS Concept

    5/97

    eg:-Consider two tables emp(contains employees description) andemp_edu(contains details of employee's education), so emp_id which isprimary 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 onto the creation of table and its manipulation.

    - NORMALIZATION is the process of grouping data into logical relatedgroups.- Normalization is the process of reducing the redundancy of data in arelational database.- A database that is not normalized may include data that is contained in oneor more different tables for no apparent reason. This could be bad forsecurity reasons, disks space usage, speed of queries, efficiency of databaseupdates, and may be most importantly, data integrity. A database beforenormalization is one that has not been broken down logically into smaller,more manageable tables.

    BENEFITS OF NORMALIZATIONNormalization 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.

    http://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/06/basic-dbms-concept.html
  • 7/31/2019 Basic DBMS Concept

    6/97

    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)

    http://dotnetguts.blogspot.in/2007/06/sql-basics.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-basics.html
  • 7/31/2019 Basic DBMS Concept

    7/97

    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 areused for securing the database.TCL statement such as COMMIT,SAVEPOINTand ROLLBACK affirm or and revoke database transactions.(commands will be explained later).

    LOGIN PROCEDURE FOR SQL*PLUS

    FOR LINE MODE VERSION1) C:\>SQLPLUS2) C:\>PLUS80

    FOR GRAPHICAL USER INTERFACE(GUI) MODE1) C:\>PLUS80W

    2) START -> PROGRAMS -> ORACLE -> SQL*PLUS.

    NOTE:-The above path are define considering most common path used, theircan 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 anoracle database. The dialog window prompts you for three items:

    i) User Name :- The oracle database user you are using for connection.

  • 7/31/2019 Basic DBMS Concept

    8/97

    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 userpassword which are shown in the following table. Use these default valuesuntil you establish your own user_name and user_password.They are givenas 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 aremany for longon purpose.

    TIPS FOR USER NAME AND PASSWORDA user name must be associated with a user password. The maximum lengthfor 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 yourdata from modified by other users. The maximum length is 30 Characters.

    To create usersyntax:-create user identified by ;example:-create user vivek identified by vr1;where vivek is user and password is vr1.

    To Give Rights after creating userssyntax:- grant to ;grant on to ;

  • 7/31/2019 Basic DBMS Concept

    9/97

    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 userssyntax :- 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 userssyntax :- show all user;

    To Connect to another user from current loginsyntax :- connect ;

    To see the name of user in which you are currently been logged onsyntax :- select user from dual;orshow user;

    DUAL :- DUAL is usually a pseudocolumn which doesn't require anyargument, It can be considered as built-in value that returns specified pieceof information by quering a table.for example:-sysdate always returns the current date and time. similarlyhere it provides information about the current user who is connected to theoracle database.

    Before Ending this topic let us learn common command which is requirefrequently that isCommand To Clear Screansyntaxcl scr;

  • 7/31/2019 Basic DBMS Concept

    10/97

    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 bydefault.-> Char datatypes stores data in the Fixed-Length Format.-> Be aware, when using this data type, that spaces are padded to the rightof 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 fora 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. ToDecember 31, 4712 A.D.

    -> To view System Date and time we can use the SQL function calledSYSDATE.

    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 canstore or retrieve data but not manipulate it.Limitations of LONG data type are as underi> Only one column in a table can have LONG datatype, which should notcontain unique or primary key constraint.

    http://dotnetguts.blogspot.in/2007/06/oracle-datatypes-basics.htmlhttp://dotnetguts.blogspot.in/2007/06/oracle-datatypes-basics.html
  • 7/31/2019 Basic DBMS Concept

    11/97

    ii> Column cannot be indexed.iii> Procedures or stored procedures cannot accept LONG datatype asargument.

    4) NUMBER -> It can store Numeric data such as Zero, Positive or Negative, Fixed orFloating point data.-> It accepts Positive and negative integers and real number and has from 1to 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. 999992) 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 besupported 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 choicesare available to you.i> Store the BLOB in an operating system file(such as an MS-DOS file) andstores the directory and filename in the associated table.

  • 7/31/2019 Basic DBMS Concept

    12/97

    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-then-ELSE and LOOP statements. A Boolean value can hold true, false or NULLonly.

    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 aLONG 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 foraccuracy and store efficiency. This datatype is used to store signed integervalues, which range from TM2147483647 to +2147483647. It is stored in a2's complement binary format. Loop Counter are often of type BINARYINTEGER.

  • 7/31/2019 Basic DBMS Concept

    13/97

    DATA DEFINITION LANGUAGE (DDL)

    INTRODUCTION to DDL

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

    Let us now understand DDL statements and how it works on Oracledatabase.

    TABLE(A table consist of Rows and Columns. Table is a collection of related recordsthat 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; oracleis not case sensitive as long as table or column names are not enclosed indouble 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 mayuse the same column name in different tables.-> Like other database objects , a column name can be upto 30 characters

    http://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.html
  • 7/31/2019 Basic DBMS Concept

    14/97

    long.-> The column name must begin with an alphabetic character.-> The column name can contain the letters A through Z, the digits 0through 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 columnnames help users understand the definition of each column.-> An Oracle table may have upto 254 columns.

    Commands Related To Table

    1) Syntax to CREATE TableCREATE 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 avoidinvalid information to be entered in the database.NOTE:-you can assign default value for field by using the keyword defaultand specifying default value for that field.eg:-city varchar2(25) default 'AHMEDABAD'(Though SQL is not case sensitive, but contents of table are case sensitiveso it is good practise to write data always in uppercase).Tip - CHAR, VARCHAR AND DATE kind of data should be written in singlequota.

    example

  • 7/31/2019 Basic DBMS Concept

    15/97

    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 tablesql> desc ;orsql> describe ;examplesql> 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 definitionALTER TABLE[ADD MODIFY DROP]( ,::);

  • 7/31/2019 Basic DBMS Concept

    16/97

    examples

    -> To Add column in a table.sql> alter table emp

    add(emp_phno number(10));

    -> To Modify Tablesql> alter table empmodify(emp_city varchar2(35),emp_state varchar2(35));

    -> To Drop Table's Primary key and other constraints.general syntaxALTER TABLE[DROP ENABLE DISABLE]CONSTRAINT ;

    sql> alter table empdrop primary key;

    After successfully completion of above command you get the message tablealtered.

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

  • 7/31/2019 Basic DBMS Concept

    17/97

    examplesql> truncate table emp;-> It will delete all the rows of the emp table and only structure of the tableremains.

    5) Command to Delete TableDROP-> Drop command will delete the table contents and its structure.Syntax for Drop commandsql> DROP TABLE ;examplesql> 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 commandSql > RENAME TOexamplesql> Rename employee to emp;-> Now the table name is renamed and you can manipulate it using name

    emp.

    INTEGRITY CONSTRAINTSAn Integrity constraint is a trick used by oracle to prevent invalid data entryinto the table. It is only a rules applied to restrict user to enter particularvalue. It prevent this by defining it at column-level or table-level constraint.The main difference between both is that column-level constraint is definedat 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 anyof the table's columns.NOTE:-not null and check constraint cannot be defined as table-levelconstraint.Integrity constraint are categorized into three types they are as under1) Domain Integrity Constraints2) Entity Integrity Constraints

  • 7/31/2019 Basic DBMS Concept

    18/97

    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 restrictthe user to enter the value at any cost we should put not null constraint.->In other words, not null field should always contains value.examplecreate 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 theabove command while user want to enter the value, he must have to enterempno. ntnl is the constraint name.

    CHECK-> check constraint is used to match the enter data with predifined criteriaduring 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 reliableinformation.examplecreate 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

  • 7/31/2019 Basic DBMS Concept

    19/97

    try's to enter job for another category an error code for it will be generatedby sql.

    II) ENTITY INTEGRITY CONSTRAINTS

    -> Entity integrity constraint Prevent invalid data entry by enforcing ruleslike UNIQUE and PRIMARY KEY on the column.

    UNIQUE-> Unique constraint allowed null values, but it does not allowed duplicatevalues.-> It may be composite upto 16 columns.examplecreate 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 andconstraint 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.examplecreate 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 eachrecords in a table. pkno is a constraint name for column-level definition of

  • 7/31/2019 Basic DBMS Concept

    20/97

    constraint.

    III) REFRENTIAL INTEGRITY CONSTRAINTS

    -> Often, we wish to ensure that a value that appers in one relation for agiven set of attributes also appears for a certain set of attributes in anotherrealtion. This condition is called referential integrity.-> To implement this, we should define the column in the parent table as aprimary key and the same column in the child table as a foreign keyreferring to the corresponding parent entry.->foreign key is a column or combination of column which refers to primarykey of primary table.

    examplecreate 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 whileeducation_detail table consist of their achived degree's by their no. one-to-many relationship is formed here. As one employee have many degree's andeven few employee have no degree's.

    ON CASCADE DELETE -> It is special facilty through which we can ensure that the row deleted in

    http://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-definition-language-ddl.html
  • 7/31/2019 Basic DBMS Concept

    21/97

    the master table will automatically deletes the row in the reference table.for example if we have records of employee details than after deleting anyone of their record will automatically deletes the corresponding entry in thereference table.

    examplecreate 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 theappropriate data model .

    There are basically two types of DMLi>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 tounderstand 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.

    http://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.html
  • 7/31/2019 Basic DBMS Concept

    22/97

    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 getthe unique records by using keyword distinct with it.

    syntax:SELECT [DISTINCT ALL] FROMWHERE

    ->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 byselecting 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 anemployee.3)SQL>select * from empwhere

    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 itwill 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 onlystandard way to insert multiple rows.)

    syntax:-

    INSERT INTO(........)VALUES(......)->Where the Fieldname should be valid field for a table.->Field having datatype char,varchar2 and Date kind of data should be written in singlequota.

    http://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.html
  • 7/31/2019 Basic DBMS Concept

    23/97

    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, sowe have made use of single quota.2)SQL>Insert into emp(empno,job)values(&empno,'&job');->Here we have customize the insert command to take data for only two field that is empnoand job for multiple records.->When you don't want to type the command which is used last than simply press the slashto activate the command which is used by you last.3)SQL>Insert into empvalues(&empno,'&ename','&job');->Note in Above command we haven't declare the field in which data is to be entered, it isoptional 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 enameand leave the column job.->If we doesn't want to enter value for a particular field we can just type NULL in it placeduring 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 tableemp_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:UPDATESET =WHERE;->Where Clause is optional.

  • 7/31/2019 Basic DBMS Concept

    24/97

    ->Fieldname is name of column whose contents are to be manipulated.

    example:1)SQL>Update empset job = 'ACCOUNTANT'

    where job = 'MUNIM';->Above sql statement will Modify Job field for employee whose status is munim, it willupdate the status munim with accountant.2)SQL>Update empset 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 thisoperation.

    syntax:DELETE FROMWHERE;->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 empWhereempno = 4;->Above statement remove record of empno 4.->Only one record is deleted.2)SQL>Delete from empWhere

    job = 'OPERATOR';

    ->Above statement remove record/s of those employee whose status is operator in thecompany.

    http://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.htmlhttp://dotnetguts.blogspot.in/2007/06/data-manipulation-language-dml.html
  • 7/31/2019 Basic DBMS Concept

    25/97

    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 theinformation created by us. To kept such a kind of watch we must have toexecute 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 ourdatabase 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 ourdatabase, 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 ONTO

    Example1)SQL> grant select onemp 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 onemp to operators;- here user who logged on as operators are granted access, insertion anddeletion right on the database.111)SQL>grant insert (empno, ename, job) on

    http://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.htmlhttp://dotnetguts.blogspot.in/2007/06/data-control-language-dcl.html
  • 7/31/2019 Basic DBMS Concept

    26/97

    emp to endusers;- In some case, we require to hide the information to particular users, thiscan be achived by grant as in the above command we want to hide the detailof 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 wewant our database to stop sharing the information with other users, withcertain type of right revoked to him. Consider that if we want our operatorsto have only access privilege to our database, we can revoke it by executingcommand.- Revoke privilege is assigned not only on table object, but also views,synonyms, indexes, sequences,etc.

    SyntaxREVOKE PRIVILEGES ONFROM

    example

    1)SQL> revoke insert, delete onemp 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 inlogical 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 alreadydiscussed.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

    http://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.html
  • 7/31/2019 Basic DBMS Concept

    27/97

    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 savedto the database.

    TRANSACTIONAL CONTROLTransactional control is the ability to manage various transactions that mayoccur within a relational database management system . (Note keep in mindthat transaction is group of DML statements).When a transaction is executed and completes successfully, the target tableis not immediately changed, although it may appear so according to theoutput. When a transaction successfully completes, there are transactionalcontrol commands that are used to finalize the transaction.There are three commands used to control transactions : 1) COMMIT2) ROLLBACK3) SAVEPOINT

    When transaction has completed, it is not actually taken changes ondatabase, the changes reflects are temporary and are discarded or saved byissuing transaction control commands. Explanatory figure is drawn as under.

    http://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.htmlhttp://dotnetguts.blogspot.in/2007/06/transaction-control-language-tcl.html
  • 7/31/2019 Basic DBMS Concept

    28/97

    TRANSACTIONAL CONTROL COMMANDS

    1) COMMIT Command ->The commit command saves all transactions to the database since the lastCOMMIT or ROLLBACK command.Syntaxcommit [work];

    The keyword commit is the only mandatory part of the syntax. Keywordwork is optional; its only purpose is to make the command more user-friendly.

    exampleSQL>delete from empwhereemp_age > 75;

    ->The above command deletes the records of those employee whose age isabove 75 yrs. Though the changes are reflected on database they are notactually save as explained above they are stored in temporary area. To allowchanges permanently on database commit command is used.

    SQL> COMMIT WORK;

    http://1.bp.blogspot.com/_nuQwSyDoLk8/RmuBqYBeQ4I/AAAAAAAAAGg/YwqJKZGlU2U/s1600-h/sql+transaction.bmp
  • 7/31/2019 Basic DBMS Concept

    29/97

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

    2) ROLLBACK Command->The rollback command is the transactional control command used to undotransactions that have not already been saved to the database. The rollbackcommand can only be used to undo transactions since the last COMMIT orROLLBACK command was issued.

    SyntaxSQL>rollback [work];

    The keyword rollback is the only mandatory part of the syntax. Keywordwork is optional; its only purpose is to make the command more user-friendly.

    exampleSQL>delete from emp

    whereemp_age > 75;->The above command deletes the records of those employee whose age isabove 75 yrs. Though the changes are reflected on database they are notactually save as explained above they are stored in temporary area. Todiscards changes made on database rollback command is used.

    SQL> ROLLBACK WORK;->The above command will discards changes made on database,since lastcommit or rollback command was issued.note here work is totally optional, it is just to make command more userfriendly.

    3) SAVEPOINT Command

  • 7/31/2019 Basic DBMS Concept

    30/97

    ->A savepoint is a point in a transaction that you can roll the transactionback to without rolling back the entire transaction.->Practical exampleconsider 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, sobefore randomly selecting one track he make a signal flag, so that if thetrack was not the right one he can rollback to signal flag and select the righttrack. In this example the signal flag becomes the savepoint. Explanatoryfigure is as under.

    SyntaxSQL>SAVEPOINT->Savepoint name should be explanatory.

    example->Before deleting the records of employee whose age is above 75, we arenot sure that whether we are given work to actually delete the records of employee whose age is above 75yrs or 80yrs. So before proceding furtherwe should create savepoint here if we are been order later than it mightcreate loss of information.SQL>savepoint orignally;

    SQL>delete from empwhereemp_age > 75;->The above command deletes the records of those employee whose age isabove 75 yrs. Though the changes are reflected on database they are notactually save as explained above they are stored in temporary area.

    http://2.bp.blogspot.com/_nuQwSyDoLk8/RmuByoBeQ5I/AAAAAAAAAGo/k5wkrLW1_Cc/s1600-h/savepoint.bmp
  • 7/31/2019 Basic DBMS Concept

    31/97

    ->After some time we are given order to increase employee salary to 10%.We can increase by generating following command. But before that we willmake 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 cansimply pass rollback entry achieve present state.SQL>savepoint increm_sal;

    SQL>update empset salary=salary + (salary*10);->It will Increase salary of employee by 10%.

    ->After sometime top level management decided that salary of onlyprogrammer should be increased by 10% than only we have to do is just topass 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 salaryrecords for employee who is programmer. If we have dout than we can putsavepoint, otherwise savepoint is not compulsory.

    SQL>update empset salary=salary + (salary*10);whereemp_status='PROGRAMMER';->It will increase salary of only programmers.

    If all the changes have been taken place and now we have decided that nofurther changes require and we have to made changes to apply on databasepermanently than we can simply generate commit command to reflectchanges permanently on database.

    SQL>commit work;

  • 7/31/2019 Basic DBMS Concept

    32/97

    SQL OPERATORS

    The Operators Supported by SQL*Plus are as under1) Comparision Operators

    2) Logical Operators3) Arithmetic Operators4) Operators used to negate conditionsThey are discussed in brief as under.

    SQL COMPARISION OPERATORSComparision Operators as the name sujjests are used to test valuesin SQLstatement . The comparision operators are as under* Equality (=)* Non-Equality ()* Greater-than (>)* Less-than (=)* Less-than or equal to ( select * from empwhereemp_name='RAHUL';->It will select all details of employee whose name is rahul.

    2) SQL> select emp_name from empwhereemp_age > 50;

    -> It will list names of those employee whose age is above 50 yrs.

    3) SQL> select emp_name from empwhereemp_job = 'ACCOUNTANT' OR emp_job= 'MUNIM';->It will list names of those employee whose status is munim or accountant

    http://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.html
  • 7/31/2019 Basic DBMS Concept

    33/97

    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 makecomparision 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

    whereemp_age < emp_name="'SAJID';">The above eg shows rows for thoseemployee 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 empwhereemp_age < emp_name="'SAJID';">The above eg shows rows for thoseemployee 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

  • 7/31/2019 Basic DBMS Concept

    34/97

    exact character value . ->The LIKE operator used wildcard operators to compare a value to similarvalues.->There are two wildcards used in conjunction with LIKE operator.

    ( % ) The percent sign-The percent sign represents Zero, oneor multiple characters.( _ ) The Underscore-The underscore represents singlenumber or characters.->These symbols can be used in combinations.eg:1)SQL> select * from empwhereemp_name LIKE 'A%';->Finds any name that start with A and continues for any length.

    2) SQL>select * from empwhereemp_name LIKE '%A';->Finds any name that ends with A.

    3) SQL>select * from emp

    whereemp_name LIKE '%A%';->Finds any name that have A in any position.

    4) SQL>select * from empwhereemp_salary LIKE '3___5';->Finds any value in a five digit number that starts with 3 and end with 5.

    5) SQL>select * from empwhereemp_salary LIKE '_5%5';->Finds any values that have a 5 in the second position and ends with a 5.

    http://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.html
  • 7/31/2019 Basic DBMS Concept

    35/97

    BETWEEN->The BETWEEN operator is an extension of comparision operator as tomake 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 asa part of search.-> A Between operator can be used with both character andnumeric datatypes. However, one cannot mix the data types .eg:1)SQL>select * from empwhereemp_salary BETWEEN 5000 AND 10000;->It searches for those employee whose salary is lies between 5000 and10000, including the values 5000 and 10000.

    IN->The IN operator search the value from a predetermined list, if any of thevalue matches than row will be displayed.eg:1)SQL>select * from emp

    whereemp_jobIN ('ACCOUNTANT','PROGRAMMER','OPERATOR');->It will display all details of those employee whose status in company iseither accountant, programmer or operator.Note IN operator is basically useto remove multiple OR operators. The above statement using OR operatorwill beemp_job='ACCOUNTANT' OR emp_job='PROGRAMMER' ORemp_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 alsomake our statement more efficient.

    2)SQL>select * from empwhere

    http://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.html
  • 7/31/2019 Basic DBMS Concept

    36/97

    emp_depart_no IN ('5','10','15','20');->It will display details of those employee whose department number iseither 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-id1) SQL> select * fromempwhereemail_id IS NULL;->It will display records of those employee who haven't created their email-id.NOTE:- If you tried NULL operator to use with equality operator it will notgive proper result.consider above eg. if you modify above statement usingequality operator it will display improper result.email_id = NULL does not find a NULL value. You will be prompted with themessage no rows selected even though there are rows with a NULL values.

    2)SQL>select * from emp

    whereemp_salary IS NULL;->It will display records of those employee whose pay field is NULL. This isconsider as invalid's records and should be deleted immediately.

    ALL and ANYALL->The ALL operator compares a value to all values in another value set.eg:1)SQL>select * from empwhereemp_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

  • 7/31/2019 Basic DBMS Concept

    37/97

    of the employee whose status is operator.

    2)SQL>select * from empwhere

    emp_age Itwill compares age value to see whether it is less than or equal to allemployee'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 empwhereemp_salary > ANY(select emp_salary from emp where emp_job = 'PROGRAMMER');->It will compares salary value to see whether it is greater than ANY salariesof the employee whose status is programmer.

    2)SQL>select * from empwhereemp_age It

    will compares age value to see whether it is less than or equal to anyemployee's age who is staying in CA.

    SQL ARITHMETIC OPERATORS

    ->The arithmetic operators are mentioned as under1) 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 Itcontains field like rno, stname, std, div, totsub, totmarks.where rno is roll number, stname is student name , std is standard, div is

    http://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.htmlhttp://dotnetguts.blogspot.in/2007/06/sql-operators.html
  • 7/31/2019 Basic DBMS Concept

    38/97

    division, totsub is total subjects and totmarks is total marks.

    1) To find percentage of all studentSQL>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 atexecution of statement or field already there in a table.

    consider the above example, field is created at the execution of statementand 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 todisplay field title more user friendly.->Note aliases is not compulsory on a field it is used just to interface moreuser 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 Amountfrom productwhereprodname = 'SCREW';->Here query contains aliases Product_Name for prodname, Quantity forqty, Price_per_unit for price and Amount for (qty*price)->This query display product name, quantity, price and amount for recordswhose prodname is screw.->Here Amount is a field which will be created at the time of execution. Ituses the multiplication operator.

    Similarly we use arithmetic operators according to our requirement but the

  • 7/31/2019 Basic DBMS Concept

    39/97

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

    SQL NEGATE OPERATORS

    The Negate Operators reverses the meaning of the logical operators withwhich 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

    whereemp_job 'ACCOUNTANT';->Here all records are selected excluding those whose status is accountantin company.

    2)SQL>select * from empwhereemp_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

  • 7/31/2019 Basic DBMS Concept

    40/97

    whereemp_salary NOT BETWEEN 2000 and 3000.->It will select all records excluding those whose salary is between 2000 and3000, including 2000 and 3000.

    IS NOT NULL->It will check whether the selected field is not empty(null).eg:1)SQL>select * from empwhereemail_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 isnot similar.->It supports both wildcard character that are mentioned in like operators.eg:1)SQL> select * from empwhereemp_name NOT LIKE 'A%';

    ->Finds any name that do not start with A and continues for any length.

    2) SQL>select * from empwhereemp_name NOT LIKE '%A';->Finds any name that do not ends with A.

    3) SQL>select * from empwhereemp_salary NOT LIKE '1___0';->Finds any value in a five digit number that do not starts with 1 and endwith 0.

    NOT IN->The NOT IN operator search the value that is not mentioned in a

  • 7/31/2019 Basic DBMS Concept

    41/97

    predetermined list, if any of the value matches than row will be displayed.eg:1)SQL>select * from empwhere

    emp_jobNOT IN ('PROGRAMMER','OPERATOR');->It will display all details of employee excluding those whose status incompany is either programmer or operator.

    2)SQL>select * from empwhereemp_depart_no NOT IN ('5','10','15','20');->It will display details of employee excluding those whose departmentnumber 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 Administratorrights 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 createddatabase

    http://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.googlepages.com/MySamplePractise_Script.sqlhttp://dotnetguts.googlepages.com/MySamplePractise_Script.sqlhttp://dotnetguts.googlepages.com/MySamplePractise_Script.sqlhttp://dotnetguts.googlepages.com/MySamplePractise_Script.sqlhttp://dotnetguts.googlepages.com/MySamplePractise_Script.sqlhttp://dotnetguts.googlepages.com/MySamplePractise_Script.sqlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    42/97

    Now type your desired database name and choose appropriate settings foryour desired database. I have selected all default settings here and press OKbutton

    So our "MySampleDatabase" Is created.

    http://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://3.bp.blogspot.com/_nuQwSyDoLk8/Rwfo2JahXfI/AAAAAAAAAOg/473t7fNP1Sg/s1600-h/SQL-Server-2005-3.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwfoBJahXeI/AAAAAAAAAOY/4XiStIU_EFE/s1600-h/SQL-Server-2005-2.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/Rwfo2JahXfI/AAAAAAAAAOg/473t7fNP1Sg/s1600-h/SQL-Server-2005-3.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwfoBJahXeI/AAAAAAAAAOY/4XiStIU_EFE/s1600-h/SQL-Server-2005-2.jpghttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    43/97

    While working with Windows VistaNote: You may receive error "An exception occurred while executing aTransact - 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 asAdministrator as shown in figure

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

    http://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://4.bp.blogspot.com/_nuQwSyDoLk8/Rwfm5ZahXdI/AAAAAAAAAOQ/2t4cPvBcVRM/s1600-h/SQL-Server-2005-1.jpghttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    44/97

    Creating Tables in SQL Server 2005 database

    Now, right click the newly created MySamplePractise Database and add newtable

    http://3.bp.blogspot.com/_nuQwSyDoLk8/RwfpuJahXgI/AAAAAAAAAOo/dvDzX1j5P-0/s1600-h/SQL-Server-2005-4.jpg
  • 7/31/2019 Basic DBMS Concept

    45/97

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

    http://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://4.bp.blogspot.com/_nuQwSyDoLk8/RwfqWZahXhI/AAAAAAAAAOw/Ok6sipl7Ftw/s1600-h/SQL-Server-2005-5.jpghttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/10/datatypes-in-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    46/97

    Here, CustomerID is Identity field, that is Auto generated by system. It issimilar 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 generateautonumber from 1001

    ConstraintConstraint is a check which is made on table which must be followed by userentering data. It reduce the number of Invalid data feed-in into system byprechecking its validity.

    In this table 2 constraint are used that is "Allow Null" and "Primary Key"

    http://3.bp.blogspot.com/_nuQwSyDoLk8/RwfsbJahXiI/AAAAAAAAAO4/ACiOXNO2vBo/s1600-h/SQL-Server-2005-6.jpg
  • 7/31/2019 Basic DBMS Concept

    47/97

    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 thecolumn 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

    http://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://4.bp.blogspot.com/_nuQwSyDoLk8/RwfxdZahXnI/AAAAAAAAAPg/tLNXaIMdGO8/s1600-h/SQL-Server-2005-8.jpghttp://4.bp.blogspot.com/_nuQwSyDoLk8/RwfvnZahXjI/AAAAAAAAAPA/h7ERvxnTDMg/s1600-h/SQL-Server-2005-7.jpghttp://4.bp.blogspot.com/_nuQwSyDoLk8/RwfxdZahXnI/AAAAAAAAAPg/tLNXaIMdGO8/s1600-h/SQL-Server-2005-8.jpghttp://4.bp.blogspot.com/_nuQwSyDoLk8/RwfvnZahXjI/AAAAAAAAAPA/h7ERvxnTDMg/s1600-h/SQL-Server-2005-7.jpghttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.html
  • 7/31/2019 Basic DBMS Concept

    48/97

    Product Table

    ProductType Table

    so your object explorer looks as under

    http://4.bp.blogspot.com/_nuQwSyDoLk8/Rwfw2ZahXkI/AAAAAAAAAPI/z_flA5wYY8s/s1600-h/SQL-Server-2005-11.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/Rwfw7JahXlI/AAAAAAAAAPQ/aZEtSvhJZQE/s1600-h/SQL-Server-2005-10.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwfxLJahXmI/AAAAAAAAAPY/ZUqUnWpuFHs/s1600-h/SQL-Server-2005-9.jpghttp://4.bp.blogspot.com/_nuQwSyDoLk8/Rwfw2ZahXkI/AAAAAAAAAPI/z_flA5wYY8s/s1600-h/SQL-Server-2005-11.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/Rwfw7JahXlI/AAAAAAAAAPQ/aZEtSvhJZQE/s1600-h/SQL-Server-2005-10.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwfxLJahXmI/AAAAAAAAAPY/ZUqUnWpuFHs/s1600-h/SQL-Server-2005-9.jpghttp://4.bp.blogspot.com/_nuQwSyDoLk8/Rwfw2ZahXkI/AAAAAAAAAPI/z_flA5wYY8s/s1600-h/SQL-Server-2005-11.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/Rwfw7JahXlI/AAAAAAAAAPQ/aZEtSvhJZQE/s1600-h/SQL-Server-2005-10.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwfxLJahXmI/AAAAAAAAAPY/ZUqUnWpuFHs/s1600-h/SQL-Server-2005-9.jpg
  • 7/31/2019 Basic DBMS Concept

    49/97

    Creating Database Diagram in SQL Server 2005

    http://4.bp.blogspot.com/_nuQwSyDoLk8/RwfyFZahXoI/AAAAAAAAAPo/ZUe66_svMHI/s1600-h/SQL-Server-2005-12.jpg
  • 7/31/2019 Basic DBMS Concept

    50/97

    Next step select Table and press Add button

    http://3.bp.blogspot.com/_nuQwSyDoLk8/RwfzBJahXqI/AAAAAAAAAP4/HAmnPQFcOSs/s1600-h/SQL-Server-2005-14.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwfyrpahXpI/AAAAAAAAAPw/7FkiketjcXY/s1600-h/SQL-Server-2005-13.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwfzBJahXqI/AAAAAAAAAP4/HAmnPQFcOSs/s1600-h/SQL-Server-2005-14.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwfyrpahXpI/AAAAAAAAAPw/7FkiketjcXY/s1600-h/SQL-Server-2005-13.jpg
  • 7/31/2019 Basic DBMS Concept

    51/97

    Adding a releationship among tables

    Right click the "Many" Table as They don't allow to change foreign key tablein 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 youwill find details appear on right pane of dialog box.

    http://2.bp.blogspot.com/_nuQwSyDoLk8/RwjsmIrTfjI/AAAAAAAAAQA/PsF-xrpoMG4/s1600-h/SQL-Server-2005-15.jpg
  • 7/31/2019 Basic DBMS Concept

    52/97

    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" forForeign Key.

    And press ok button to create relationship between two table.

    Advantage of creating relationship

    http://1.bp.blogspot.com/_nuQwSyDoLk8/Rwjt-4rTflI/AAAAAAAAAQQ/N8pYbUQ6Dzs/s1600-h/SQL-Server-2005-17.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwjtG4rTfkI/AAAAAAAAAQI/1fr_tm7ZunU/s1600-h/SQL-Server-2005-16.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/Rwjt-4rTflI/AAAAAAAAAQQ/N8pYbUQ6Dzs/s1600-h/SQL-Server-2005-17.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwjtG4rTfkI/AAAAAAAAAQI/1fr_tm7ZunU/s1600-h/SQL-Server-2005-16.jpg
  • 7/31/2019 Basic DBMS Concept

    53/97

    It will not allow to enter orders details without customer information. Thatis it allow to enter orders details of valid customer.

    It will not allow to delete customer information, until all details associatedwith customer is delete.

    You may change setting as per your need by selecting No from dropdownof "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 canchange the view of table by selecting all table with "ctrl+A" and right clicking

    http://4.bp.blogspot.com/_nuQwSyDoLk8/RwjxXorTfmI/AAAAAAAAAQY/2tS1YQX-cEc/s1600-h/SQL-Server-2005-18.jpg
  • 7/31/2019 Basic DBMS Concept

    54/97

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

    A sample diagram will now look as under

    http://4.bp.blogspot.com/_nuQwSyDoLk8/RwjyPorTfnI/AAAAAAAAAQg/zYJF04vGNrM/s1600-h/SQL-Server-2005-19.jpg
  • 7/31/2019 Basic DBMS Concept

    55/97

    So now as Database Designing and Table creation is done, lets enter somesample data

    Inserting Record in Table for SQL Server 2005, right click the table andselect open table, it gives you MS Access type editor to enter data. Notethose who prefer inserting data through SQL Query or Script may open SQLEditor. Similarly making change in table design click modify.

    http://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.htmlhttp://1.bp.blogspot.com/_nuQwSyDoLk8/Rwjyq4rTfoI/AAAAAAAAAQo/_u9sa_V-TJA/s1600-h/SQL-Server-2005-20.jpghttp://dotnetguts.blogspot.in/2007/10/basics-of-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    56/97

    Now key-in the data in customer table, as shown in figure. Note: hereCustomerID 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 Identityfield wherein data is auto generated by system. As we have enforce

    http://3.bp.blogspot.com/_nuQwSyDoLk8/Rwj1qYrTfqI/AAAAAAAAAQ4/Nyit1xVSnY4/s1600-h/SQL-Server-2005-22.jpghttp://2.bp.blogspot.com/_nuQwSyDoLk8/Rwj0uIrTfpI/AAAAAAAAAQw/hDq2KgSZoOQ/s1600-h/SQL-Server-2005-21.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/Rwj1qYrTfqI/AAAAAAAAAQ4/Nyit1xVSnY4/s1600-h/SQL-Server-2005-22.jpghttp://2.bp.blogspot.com/_nuQwSyDoLk8/Rwj0uIrTfpI/AAAAAAAAAQw/hDq2KgSZoOQ/s1600-h/SQL-Server-2005-21.jpg
  • 7/31/2019 Basic DBMS Concept

    57/97

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

    http://3.bp.blogspot.com/_nuQwSyDoLk8/RwklTIrTftI/AAAAAAAAARQ/-QI3IGa1fI4/s1600-h/SQL-Server-2005-25.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/Rwkk5orTfsI/AAAAAAAAARI/SU0xlkDQ_Mo/s1600-h/SQL-Server-2005-24.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwkPVorTfrI/AAAAAAAAARA/9yD4wRkFnTc/s1600-h/SQL-Server-2005-23.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwklTIrTftI/AAAAAAAAARQ/-QI3IGa1fI4/s1600-h/SQL-Server-2005-25.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/Rwkk5orTfsI/AAAAAAAAARI/SU0xlkDQ_Mo/s1600-h/SQL-Server-2005-24.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwkPVorTfrI/AAAAAAAAARA/9yD4wRkFnTc/s1600-h/SQL-Server-2005-23.jpghttp://3.bp.blogspot.com/_nuQwSyDoLk8/RwklTIrTftI/AAAAAAAAARQ/-QI3IGa1fI4/s1600-h/SQL-Server-2005-25.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/Rwkk5orTfsI/AAAAAAAAARI/SU0xlkDQ_Mo/s1600-h/SQL-Server-2005-24.jpghttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwkPVorTfrI/AAAAAAAAARA/9yD4wRkFnTc/s1600-h/SQL-Server-2005-23.jpg
  • 7/31/2019 Basic DBMS Concept

    58/97

    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 inseconds 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 somepoint your system may become useless. Example use of smalldatetime (2bytes) datatype over datetime (4 bytes) datatype can make your systemuseless 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 spaceas same information can be stored in tinyint and serves the need. So herewe can save space and money by allocating tinyint (1 byte) over smallint(2 bytes).

    http://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.htmlhttp://1.bp.blogspot.com/_nuQwSyDoLk8/RwklnorTfuI/AAAAAAAAARY/lqSyTpzcjI4/s1600-h/SQL-Server-2005-26.jpghttp://dotnetguts.blogspot.com/2007/06/basic-dbms-concept.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    59/97

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

    Choosing between tinyint, smallint, int, bigint datatype inSQL Server2005

    You should use int datatype to store exact number. Now depends on chartshown below you and your maximum and minimum data rangeconsideration you can able to decide which is better to go with.

    Data type Range Storagebigint -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) 8 Bytes

    int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes

    smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes

    tinyint 0 to 255 1 Byte

    Choosing between datetime and smalldatetime datatype in SQLServer 2005 datetime datatype are used for storing date and time information.

    Comparision chartData type Range Storage/Accuracy

    datetime January 1, 1753, through December 31, 9999 4 Bytes/3.33 milliseconds

    smalldatetime January 1, 1900, through June 6, 2079 2 Bytes/1 minute

    Difference between datetime and smalldatetime datatype in SQL Server 2005 datetime is more accurate than smalldatetime datatype. datetime datatypestores milliseconds data while smalldatetime datatype doesn't storemillisecond 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

    http://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    60/97

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

    Choosing between char, varchar, varchar(MAX) and text datatype inSQL Server 2005 char, varchar, varchar(MAX) and text datatype are used for storingcharacter string . Note you cannot store multilingual data. i.e. You will notallowed 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 isrecommended to use Varchar(MAX) instead of Text datatype,

  • 7/31/2019 Basic DBMS Concept

    61/97

    as ntext , text , and image data types will be removed in a future versionof Microsoft 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-lengthcharacter data.

    Difference between varchar and varchar(MAX) datatype varchar stores variable-length character data whose range varies upto 8000bytes, 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 choosevarchar(MAX) over text datatype as text data types will be removed in afuture version of Microsoft SQL Server .

    Choosing between nchar, nvarchar, nvarchar(MAX) and ntextdatatype in SQL Server 2005 nchar, nvarchar, nvarchar(MAX) and ntext datatype are used for storingunicode character string . you can store multilingual data. i.e. You canstore 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

    http://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/datatypes-in-sql-server-2005.html
  • 7/31/2019 Basic DBMS Concept

    62/97

    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 exceeds4000 bytes and data can be multi-lingual.

    nText datatype

    nText datatype is used in previous versions of SQL Server, it isrecommended to use nVarchar(MAX) instead of Text datatype,as ntext , text , and image data types will be removed in a future versionof 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 bytesand data can be multi-lingual.

    Difference between nchar and nvarchar datatype n char stores fixed-length unicode character data while nvarchar storesvariable-length unicode character data.

    Difference between nvarchar and nvarchar(MAX) datatype varchar stores variable-length unicode character data whose range variesupto 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 choosevarchar(MAX) over text datatype as text data types will be removed in afuture version of Microsoft SQL Server.

  • 7/31/2019 Basic DBMS Concept

    63/97

    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 storesunicode character string.

    Former require less memory, while latter requires doubles as muchmemory as former. i.e. char can stores upto 8000 bytes while nchar canstores upto 4000 bytes, because regular data are of 8bits while unicodedata require 16bits storage space.

    Example: Former is used to store character data which doesn't suppormulti-language support, while latter can support character multi-languagecharacter 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 fixedprecision 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 Server2005

    http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1266201,00.htmlhttp://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1266201,00.htmlhttp://msdn2.microsoft.com/en-us/library/ms187746.aspxhttp://msdn2.microsoft.com/en-us/library/ms187746.aspxhttp://msdn2.microsoft.com/en-us/library/ms187746.aspxhttp://msdn2.microsoft.com/en-us/library/ms187746.aspxhttp://msdn2.microsoft.com/en-us/library/ms187746.aspxhttp://msdn2.microsoft.com/en-us/library/ms187746.aspxhttp://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1266201,00.html
  • 7/31/2019 Basic DBMS Concept

    64/97

    Money and smallmoney datatype are used for storing monetary data.

    Data type Range Storage

    money -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytessmallmoney - 214,748.3648 to 214,748.3647 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 indatatype can be represented exactly.

    Data type Range Storage

    float - 1.79E+308 to -2.23E-308, 0 and 2.23E-308 to1.79E+308Depends on the valueof n

    real - 3.40E + 38 to -1.18E - 38, 0 and 1.18E - 38 to 3.40E +38 4 Bytes

    syntax of float [ ( n ) ]

    SQL Server 2005 treats n as one of two possible values. If 1

  • 7/31/2019 Basic DBMS Concept

    65/97

    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 convertedto bit values: 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 aninternal format as large binary objects (BLOB), which enable the XML modelto support document order and recursive structures. Because of theseamless integration of the XML data type with SQL Server's storage andprogramming models, you can query and update XML documents and evenwrite joins between XML data and relational data in your database. SQLServer 2005 uses the same query engine and optimizer for querying XMLdata as it does for relational data, radically enhancing your ability to workwith

    Query execution in SQL Server 2005

    SQL Query execution

    In this article you will explore

    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 o Inner Join

    o Outer Join Left Outer Join Right Outer Join Full Join or Cross Join

    o Self Join

    http://msdn2.microsoft.com/en-us/library/ms188362.aspxhttp://msdn2.microsoft.com/en-us/library/ms188362.aspxhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://msdn2.microsoft.com/en-us/library/ms188362.aspx
  • 7/31/2019 Basic DBMS Concept

    66/97

    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 opperationuse MySamplePractise

    For mastering, Data Manipulation from beginner to expert, Study following Example with150+ Queries.

    Select Statement Execution in SQL Server 2005

    --Display each details of all Customersselect * from customer

    --Display FirstName, City and Country Details of Customersselect FirstName, City, Country from Customer

    http://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts.blogspot.in/2007/10/query-execution-in-sql-server-2005.htmlhttp://dotnetguts