rdbms quan book (debraj)
TRANSCRIPT
-
8/3/2019 Rdbms Quan Book (Debraj)
1/27
What is RDBMS?Ans:
RDBMS stands for Relational Database ManagementSystem. RDBMS is the basis for SQL, and for all
modern database systems like MS SQL Server, IBMDB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in
database objectscalled tables. A table is a collections ofrelated data entries and it consists of columns
and rows.Relational Data Base Management Systems
(RDBMS) are database management systems that maintain data records andindices in tables. Relationships may be created and maintained across and among
the data and tables. In a relational database, relationships between data items areexpressed by means of tables. Interdependencies among these tables are
expressed by data values rather than by pointers. This allows a high degree ofdata independence. An RDBMS has the capability to recombine the data items
from different files, providing powerful tools for data usage.What is View?
Ans:
A simple view can be thought of as a subset of a table. It can be used forretrieving data, as well as updating or deleting rows. Rows updated or deleted inthe view are updated or deleted in the table the view was created with. It should
also be noted that as data in the original table changes, so does data in the view,as views are the way to look at part of the original table. The results of using a
view are not permanently stored in the database. The data accessed through aview is actually constructed using standard T-SQL select command and can come
from one to many different base tables or even other views.What is SQL?
Ans:SQL is a bassically standard language for accessing and manipulating databases.
Its is defines as :
> SQL stands for Structured Query Language> SQL lets you access and manipulate databases
> SQL is an ANSI (American National Standards Institute) standard.SQL have a many properties, It can do :
> SQL can execute queries against a database.> SQL can retrieve data from a database.
> SQL can insert records in a database.
> SQL can update records in a database.> SQL can delete records from a database.
> SQL can create new databases.> SQL can create new tables in a database.
> SQL can create stored procedures in a database.> SQL can create views in a database.
> SQL can set permissions on tables, procedures,and views.
What is schema?Ans:
Schema bassically Pronounce skee-ma, It is the structure of a database system,Itdescribed in a formal language supported by the database management system
(DBMS). In the RDBMS (Relational database System) , the schema defines thetables, the fields in each table, and the Schemas are generally stored in a data
-
8/3/2019 Rdbms Quan Book (Debraj)
2/27
dictionary . Even a schema is defined in text database language , the term is oftenused to refer to a graphical depiction of the database structure.
What are the main components of Database management systemssoftware.
Ans:The database management system software includes
many components are there, like :> for storage management,> concurrency control,
> transaction processing,
> database manipulation interface,> database definition interface, and
> database control interface.What is query optimization?
Ans:In the database many queries generate and executed or Query optimization is the
part of the query process in which the database system compares different querystrategies and chooses the one with the least expected cost.
KEYS
A database key is a attribute utilized to sort and identify data in some manner.There are many keys:
1. Primary key:The primary key is a attribute of a relational table uniquelyidentifies the each tuple of a table or each record in the table. It can either be a
normal attribute that is guaranteed to be unique. Such as Social Security Number
in a table with no more than one record per person. Examples: Imagine we have aemployees table that contains a record for each employee at a organization. The
employee's unique employee ID number would be a good choice for a primary key
in the employees table. The employee's first and last name would not be a goodchoice, as there is always the chance that more than one employee might have the
same name.
2. Foreign Key:These keys are used to create relationships between tables.
Natural relationships exist between tables in most database structures. Example:
Lets assume that the Departments table uses the Department Name column asthe primary key. To create a relationship between the two tables, we add a newcolumn to the Employees table called Department. We then fill in the name of the
department to which each employee belongs. We also inform the databasemanagement system that the Department column in the Employees table is a
foreign key that references the Departments table. The database will then enforcereferential integrity by ensuring that all of the values in the Departments column
of the Employees table have corresponding entries in the Departments table.
-
8/3/2019 Rdbms Quan Book (Debraj)
3/27
3. Candidate key, Alternate key and Composite key: Any number of attributesthat are uniquely identifying a row in a table is candidate key for the table. We
select one of the candidate key as Primary key. All candidate keys which are notchosen as "primary key" are Alternate keys. The key which uniquely identify the
rows of the table and which is made up of more than one attribute is calledcomposite key.
For Example: In a class we have to select Class Representative. So A, B, C and Dstand for that post. So A, B, C and D are candidate for Class Representative sothese are candidate key. We select B as Class Representative so B is primary key
and A, C and D can be Class Representative but not selected as a Class
Representative so they are alternative choice. So A, C and D are alternate key.When two students of class work together in a project then they are composite key
for the class.
LEVELS OF ABSTRACTION
Physical Level:Physical level is the lower level of abstraction. Its define how datais stored in database.
Logical Level:The next higher level of abstraction, its describe what data bestore and each logical operation done at this level, links and concept apply here.
View Level: This is the higher level describe only part of entire database for a
particular user.
NORMALIZATION
Some rules that should followed to achieve a good database design are:
1. Each table should have an identifier.
2. Each table should store data for a single type entity3. Columns that should store data for a single type of entity.
4. The repetition of values or columns should be avoided.
-
8/3/2019 Rdbms Quan Book (Debraj)
4/27
To remove the redundancy of a table as called Normalization. In other wordsduplicity or repetitions of data never occur in database. Normalization is mainly
minimizing redundancy, insertion, deletion and update anomalies. Normalizationachieve through functional dependency. Normalization is much type.
Functional Dependency: Functional dependencies (FDs) are used to specify
formal measures of the "goodness" of relational designs and used to define normalforms for relations. FDs are constraints that are derived from the meaning andinterrelationships of the data attributes. FDs are derived from the real-world
constraints on the attributesFor example: A set of attributes X functionally determines a set of attributes Y if
the value of X determines a unique value for YX-->Y holds if whenever two tuples have the same value for X, they must have the
same value for Y If t1[X] =t2[X], then t1[Y] =t2[Y] in any relation instance r(R)X-->Y in R specifies a constraint on all relation instances r(R)
Fully Functional dependency: A functional dependency X --> Y is full functionaldependency if any attribute A removed from X. It means that the dependency does
not hold any more then it is not Fully Functional dependence. Means each attributeis functionally dependent.
All categories are in sequential order:
1.1NF: There is no repetition of values and data in table known as 1NF. In other
words the 1NF disallows composite attributes, multivalued attributes, and nestedrelations, attributes whose values for an individual tuple are non-atomic.
2.2NF:A relation schema R is in 2NF when it is in 1NF and every non-primeattribute A in R is fully functionally dependent on primary key.
3.3NF:A relation schema R is in 3NF ,It is in 2NF and no non-prime attribute A inR is transitively dependent on the primary key. Transitive dependent means if
there a set of attribute Z that are neither a primary or candidate key and both X-->Z and Y-->Z holds.
4.BCNF:3NF inadequate in some situation then it was not satisfactory for the
table:
1. That had multiple candidate keys.2. Where the multiple candidate keys were composite.
3. Where the multiple candidate keys were overlapped.
A relation schema R is in BCNF, It is in 3NF and additional constraints that for
every FD X -> A, X must be a candidate key. "A relation is in the Boyce-Coddnormal form (BCNF) if and only if every determinant is a candidate key "
5.4NF:A relation schema R is said to be in 4NF, it is in BCNF and for everyMultivalued dependency X --> Y that holds over R, Either X is subset or equal to
(or) XY = R. or X is a super key.
-
8/3/2019 Rdbms Quan Book (Debraj)
5/27
6.5NF: A relation schema R is said to be in 5 NF, it is in 4NF and relation schemaR is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one
the following is true Ri = R for some i. and The join dependency is implied by theset of FD, over R in which the left side is key of R.
Demoralization
The intentional introduction of redundancy in a table in order to improveperformance is called demoralization. The decision to demoralize results in a trade-
off performance and data integrity. Demoralization increases disk utilization.
OTHER DATABASE MODELS
Relational Database Model
Data represent in form of column and row, column means attribute and row meanstouples present instance of data. This Database model came into existence with
help of mathematical concepts. Its using some other concepts like normalization,touple relational calculus.
E-R Model in Database
E-R model stands for Entity-Relationship model. This data model is based on real
world that consists of basic objects called entities and of relationship among theseobjects. Entity in database, which existence in real world with number of
attributes. In a table attribute know as column. Relationship is a logical thingwhich relates entities. The E-R diagram shows structure of E-R model.
Object Oriented Database Model
-
8/3/2019 Rdbms Quan Book (Debraj)
6/27
This model is based on collection of objects. An object is instance variables whichstore value and bodies of code, that codes are called method. These codes have
written to operate the objects. Objects that contain same types of values and thesame methods are grouped together into classes. In other words classes are a
group of object. This model also follows the some concept related to the OOPs
Hierarchical model of Database
The word hierarchy means tree form relationship, like a tree with branches. MeansRelationship formed like tree structure in a database called hierarchical model.
With this database you form relationship among many tables with certain concept.It has a downward link to describe the nesting and they are arranged in a
particular order down the same level of the list.
Network model
This model provides greater flexibility and easy access to data. This model providelogical relationship among many parent database. But implementing this model is
more difficult due to time consuming and cost. Its flexible because through linkeasily accessing of information.
XML Database
XML databases came into existence in 2000. This database lets you organize data
irrespective of whether it is organized or not. This data can exported and serializedinto the desired format. Two major classes of XML database exist:
1. XML-enabled2. Native XML
SQL
Language to access data object from the SQL server
Stands for Structured Query Language
SQL addresses data in sets of rows and column rather than addressingindividual component or a single data
SQL support automatic navigation to target the data means user find
data without knowing how to get this data and how to store the data
Using this user never waste the time on representation of data, useronly concentrate on logic
DDL (Data Definition Language)
Data Definition Language (DDL) statements are used to define the databasestructure or schema. DDL statements are used to build and modify the structure of
your tables and other objects in the database. When you execute a DDLstatement, it takes effect immediately.
1. CREATE: To create objects in the database
-
8/3/2019 Rdbms Quan Book (Debraj)
7/27
CREATE TABLE ( ,...
);
2. ALTER: Alters the structure of the database
ALTER TABLE ADD CONSTRAINT PRIMARY KEY ();
The foreign key constraint is a bit more complicated, since we have to specify boththe Foreign Key attributes in this (child) table, and the Primary Key attributes that
they link to in the parent table.
ALTER TABLE
ADD CONSTRAINT FOREIGN KEY ()REFERENCES ();
3. DROP: Delete objects from the database
DROP TABLE ;
ALTER TABLE
DROP CONSTRAINT ;
4. TRUNCATE:Remove all records from a table, including all spaces allocated for
the records are removed
5. COMMENT: Comments added to the data dictionary.
6. RENAME: Rename an object of the Database.
DML (Data manipulation language)
.DML statements are used to work with the data in tables. SELECT, INSERT,UPDATE, DELETE statements are consider as a DML statement.
1. SELECT:SQL server provide the SELECT statement to retrieve data fromdatabase. The keywords SELECT, FROM and WHERE makeup the basic SELECT
statement . SELECT statement promote the server to querying single table ormultiple tables in Database and prepare a result and return to the client
application.
Selecting Columns
The column name from a table specified in the SELECT statement separated by a
comma (,) and there is no need to insert a comma after the last column name.
SELECT column_name 1,column_name 2....column_name nFROM table_name
http://r4r.co.in/SQL/01/tutorial/basics/DML.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/DML.shtml -
8/3/2019 Rdbms Quan Book (Debraj)
8/27
The above query retrieve the column data which you pass in the query from tablewhich you pass after From keyword.
Selecting All Columns
The SELECT statement used with an asterisk (*) symbol to display all column of
the table
SELECT *
FROM table_name
2. INSERT: The insert statement is used to add new rows to a table. There will
need a separate INSERT statement for every row. The statement of Insert will be:
INSERT INTO table_nameVALUES (value 1, ... value n);
The number of attributes and the data type of each attribute
Character type values are always enclosed in single quotes Number values are never in quotes
Date values are often in the format 'yyyy-mm-dd' (for example, '2010-
12-24')
3. UPDATE:The update statement is used to change values that are already in a
table.
UPDATE table_nameSET attribute_name 1 = value 1, attribute_name 2 = value 2....attribute_name n
= value n
WHERE condition;
If the WHERE clause is omitted, then the specified attribute is set to
the same value in every row of the table
Set multiple attribute values at the same time with a comma-delimited
list of attribute_name=value pair
4. DELETE:The delete statement does just that, for rows in a table.
DELETE FROM table_nameWHERE condition;
If the WHERE clause is omitted, then every row of the table is deleted
5. CALL: Call a PL/SQL
6. EXPLAIN PLAN: Explain access path to data
7. LOCK TABLE: Control concurrency
DCL (Data Control Language)
-
8/3/2019 Rdbms Quan Book (Debraj)
9/27
DCL stands for Data Control Language
Used to create roles
Used to create permissions
1. GRANT: Gives user to access database means user privilege to database.
2. REVOKE: Withdraw access privileges given with the GRANT command
TCL (Transactional Control Language)
TCL is stands for Transactional Control Language
It is used to manage different transactions occurring within a database
1. COMMIT: This Statement used to save work done by the user.
2. SAVEPOINT: Identify the point which you can later roll back in a transaction.
3. ROLLBACK: Restore database to original.
4. SET TRANSACTION: Change transaction options like isolation level and what
rollback segment to use
Using Logical Operator
Multiple search condition done by using logical operator. They are:
1. OR:Any of the specified search condition is true.
SELECTcolumn_listFROMtable_nameWHERE condition_expression OR condition_expression
Return all rows specific to the conditions, even if any one of the condition is true.
2. AND:When all specified search conditions are true.
SELECTcolumn_listFROMtable_name
WHERE condition_expression AND condition_expression
Return all rows specific to the conditions, when both conditions are true.
3. NOT:Neutralizes the expression that follow it.
SELECTcolumn_list
FROMtable_name
WHERE condition_expression {OR/AND} NOT condition_expression
-
8/3/2019 Rdbms Quan Book (Debraj)
10/27
Return all rows specific to the conditions, except the rows that match the conditionspecified after the NOT operatoor.
Using Comparison Operators
Comparison operator allow row retrieval from a table based on the conditionspecified in the WHERE clause.
SELECTcolumn_list
FROMtable_nameWHEREexpression1 comparison_operator expression2
Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
Not greater than
!< Not less than
() Controls precedenceFor Example:
SELECT pub_idFROM publishers
WHERE city='Boston'
Using Range Operators
The range operator is used to retrieve data between range . The range operator
are:
1. BETWEEN: Specified an inclusive range to search.
SELECTcolumn_list
FROM table_nameWHEREexpression1BETWEENexpression1 AND expression1
For Example: Below query return the attribute list value between 2000 and 5000
SELECT *
FROM titles
WHERE advance BETWEEN 2000 AND 5000
-
8/3/2019 Rdbms Quan Book (Debraj)
11/27
2. NOT BETWEEN: This key word used to exclude the rows from thespecified range in the result set.
SELECTcolumn_listFROM table_name
WHEREexpression1NOT BETWEENexpression1 AND expression1
For Example: Below query return the attribute list value which not between 2000
and 5000
SELECT *
FROM titlesWHERE advance NOT BETWEEN 2000 AND 5000
Using IS NULL & IS NOT NULL
In SQL server, NULL is a unknown value means the data is not available. The NULLcan be retrieve from the table using IS NULL keyword in the WHERE clause.
Note: NO two NULL values are equal. You can not compare one NULL value toother.
SELECTcolumn_listFROMtable_name
WHEREcolumn_name unknown_value_operator
Where unknown_value_operatoris either the keyword IS NULL or IS NOT NULL.
Example:
SELECT *
FROM publishersWHERE state IS NULL
Returns the all attributes of publisher table where state attribute contain NULL
SELECT *
FROM publishersWHERE state IS NOT NULL
Returns the all attributes of publisher table where state attribute does not containNULL
Using ORDER BY Clause
It retrieve and display the data in specific order. ASC is the default sort order.
SELECTcolumn_listFROMtable_name
ORDER BY column_name ASC/DESC
-
8/3/2019 Rdbms Quan Book (Debraj)
12/27
For Example:
SELECT *FROM publishers
ORDER BY pub_name DESC
Return all attributes of publishers able in order to descending alphabetically orderwith respect to pub_name attribute
Using Aggregate Functions
These function are specially executed for the mathematical expression.
Function
NameParameters Description
AVG(ALL, DISTINCT
Expression)
Return the average of value in a numeric
expression
COUNT (ALL, DISTINCTExpression)
Return the number of values in anexpression
COUNT (*)Returns the no. of rows returned by the
query
MAX (expression) Return the highest value in the expression
MIN (expression) Return the lowest value in the expression
SUM(ALL, DISTINCT
Expression)
Return the total of value in a numeric
expression
The AVG, COUNT, MAX, MIN and SUM function ignore NULL values, whereas the
COUNT (*) function counts the NULL values.
Examples Description
SELECT 'avg'=AVG (discount)FROM discounts
Returns the average value of the discount
SELECT 'sum'=SUM (discount)
FROM discountsReturns the sum value of the discount
SELECT 'min'=MIN (discount)FROM discounts
Returns the minimum value of the discount indiscounts table
SELECT 'max'=MAX (discount)FROM discounts
Returns the maximum value of the discount indiscounts table
SELECT 'count'=COUNT(discount)
FROM discounts
Using GROUP BY Clause
Group clause summarize the result set in to a groups defined in the query using
aggregate function.
-
8/3/2019 Rdbms Quan Book (Debraj)
13/27
SELECTcolumn1, column2, ... column_n, aggregate_function (expression)FROM table_name
WHEREconditionsGROUP BYALL column1, column2, ... column_n
expressions describe the column name (s) or expressions on which the result set
of the SELECT statement is to be grouped.
ALL is a keyword used to include those groups that do not meet the searchcondition.
For Example:
SELECT type, 'avg'=AVG(advance)
FROM titlesWHERE type LIKE 'b%'
GROUP BY ALL type
Out Put
type avg-----------------------------------------------
business 5000.0000mod_cook NULL
popular_comp NULLpsychology NULL
trad_cook NULLUNDECIDED NULL
Return all type from table but the 'avg' display only those type which started with '
b'. Means this keyword used to display all groups, including those exclude fromWHERE clause. The ALL keyword is meaningful for those query that containWHERE clause.
For Example:
SELECT type,'pub Id'=pub_id, 'avg'=AVG (price)
FROM titlesGROUP BY type,pub_id
Return the 'type' and 'pub Id' and 'avg' , which calculated from titles table.
For Example:
SELECT type, 'avg'=AVG(advance)FROM titles
WHERE title_id IN ('BU1032','PC1035')GROUP BY ALL type
Out Put
-
8/3/2019 Rdbms Quan Book (Debraj)
14/27
type avg-----------------------------------------------
business 5000.0000mod_cook NULL
popular_comp 7000.0000psychology NULL
trad_cook NULLUNDECIDED NULL
JOINS
SQL server provide:
A method to retrieving a data from more than one table using join at atime
Implemented using SELECT statement, in which the SELECT statementcontain the name of columns to be retrieve from the tables
The FROM clause contains the name of the tables from which
combined data is to be retrieved The WHERE specifies the rows to be included in the result set with thehelp of the join operator
Syntax:
SELECT column name 1, column name 2....column_name n
FROM table name [CROSS, INNER, OUTER] JOIN table_nameON [table_name.ref_column_name] join_operator
[table_name.ref_column_name]WHERE search_condition
column_name specifies the name of the columns from one or more than one tablethat has to be displayed.
table_name specifies the name of the tables from which data to be retrieve.
ref_column_name specifies the name of the columns that are used to combined
the two tables using the common keys from the respective tables.
join_operatorspecifies the operator used to join the tables
When two tables are joined, they must share a common key that defines how the
rows in the tables correspond to each other. A primary key is validated against the
foreign key when a joined is used.
Whenever a column is referred to in a join condition, it should be referred to either
by prefixing it with the table name to which it belongs or by a table alias.
Table Alias: A table alias is required whenever an ambiguity is possible due
to duplicate column names in a multiple tables A tables alias is a keyword definedin the FROM clause of the SELECT statement to uniquely identify the table.
http://r4r.co.in/SQL/01/tutorial/basics/join.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/join.shtml -
8/3/2019 Rdbms Quan Book (Debraj)
15/27
Syntax:
FROMtable_name table_alias
Where,
table_name specifiesthe name of the tables that have to be combined in the query
table_alias is the keyword used to refer to a table. It must follow the rules ofidentifiers
Types of JOIN
Inner JoinOuter JoinCross Join
Equi Join
Natural Join
Self Join
CREATING CONSTRAINTS
Constraints can be be enforced at two levels.
Column level
Table level
A constraints can be defined on a column at the time of creating a table. It can becreated with the CREATE TABLE statement.
1. CREATE TABLE statement:
CREATE TABLEtable_namecolumn_name CONSTRAINTS constraints_name constraints_type [, CONSTRAITS
constraints_name constraints_type]
where, column_name is the name of the column on which the constraints is to be
defined.
constraints_name is the name of the constraints to be created and must follow therules for the identifier.
constraints_type is the type of constraints to be added.
2. ALTER TABLE statement:
ALTER TABLE table_name
[WITH CHECK or WITH NOCHECK]ADD CONSTRAINTS constraints_name constraints_type
http://r4r.co.in/SQL/01/tutorial/basics/inner.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/outer.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/cross.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/equi.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/equi.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/equi.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/inner.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/outer.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/cross.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/cross.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/equi.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/equi.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/equi.shtml -
8/3/2019 Rdbms Quan Book (Debraj)
16/27
where, table_name is the name of the table that is to be altered for adding aconstraints.
WITH CHECK and WITH NOCHECK specifies whether the existing data is to be
checked or not checked for a newly added constraints or a re-enabled constraints
constraints_name specifies the name of the constraints to be created and mustfollow the rule for identifier.
constraints_type specifies the type of constraints.
DROPPING CONSTRAINTS
A constraints dropped using the ALTER TABLE statement in the Query Analyzer.
All constraints defined in the table are dropped automatically when the table is
dropped.
ALTER TABLE table_name
DROP CONSTRAINTS constraints_name
where, table_name is the name of the table that constraints to be dropped.
constraints_name is the name of the constraints to be dropped.
TYPES OF CONSTRAINTS
[1] PRIMARY KEY constraints
[2] UNIQUE constraints
[3] FOREIGN KEY constraints
[4] CHECK constraints
[5] DEFAULT constraints
The UNIQUE Constraints
To enforce uniqueness on non-primary columns used the UNIQUE constraints. A
primary key constraints column automatically includes a restriction for uniqueness.
The unique constraint is similar to the primary key constraint except that it allowsNULL values, but there can be only one row in the table with a NULL value.
Multiple Unique constraints can be created on a table.
CREATE TABLE table_name(coloumn_name data_type CONSTRAINT constraint_name UNIQUE)
The Rules regarding to the UNIQUE constraints are:
http://r4r.co.in/SQL/01/tutorial/basics/primary_key.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/unique_cons.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/foreign_key.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/check_con.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/default_cons.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/primary_key.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/unique_cons.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/foreign_key.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/check_con.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/default_cons.shtml -
8/3/2019 Rdbms Quan Book (Debraj)
17/27
It can be created at the column level as well as table level
It does not allow two rows to have the same non-null value in a table
Multiple UNIQUE constraints can be placed on a table
The FOREIGN KEY Constraint
FOREIGN KEY constraint to remove the inconsistency in two tables
when data in one table depends on data in another table.
A FOREIGN KEY constraint associates one or more columns of a table(the foreign key) with an identical set of columns on which a PRIMARY KEY
constraint has been defined (a primary key column in another table).
CREATE TABLE table_name
(column_name data_type REFERENCES table_name (emp_id))
Syntax:
CONSTRAINT constraint_name FOREIGN KEY (column_name,..)REFERENCE table_name (column_name,..)
For Example:
CREATE TABLE employee
(emp_name char(4), emp_id varchar (16) REFERENCES engineer(emp_id))
The above command creates a FOREIGN KEY on the attribute emp_id of theemployee table that reference the primary key emp_id of the engineer table. This
will ensure that the employeeID code that is inserted into the employee table is
checked against the engineer table for the validity.
-
8/3/2019 Rdbms Quan Book (Debraj)
18/27
If the employee table is exist and does not have foreign key defined, then tablealso modified using ALTER TABLE command.
ALTER TABLE employeeADD CONSTRAINT fkemp_id FOREIGN KEY (emp_id) REFERENCES engineer
(emp_id)
-
8/3/2019 Rdbms Quan Book (Debraj)
19/27
The CHECK Constraint
A check constraint:
Enforces the domain integrity by restricting the values to be inserted
in a column
Constraints are evaluated in the order in which they are defined
There is a possible to define multiple CHECK constraints on a single
column
If check constraints defined at the table level it can be applied for themultiple columns
Syntax:
[CONSTRAINTconstraint_name ] CHECK (expression)
where, constraint_name specifies the name of the constraint to be created.
expression specifies the conditions that define the check to be made on the
column. It can be any expression arithmetic operation, relational operation orkeywords :
1. The IN keyword.
2. The LIKE keyword.
3. The BETWEEN keyword.
The rules regarding the creation of the CHECK constraint are as follows:
It can be created at the column level
It can be contain user-specified search condition
It cannot contain sub queries
It does not check the existing data in the table if created with the
WITH NOCHECK option
It can reference other columns of the same table
CREATE TABLE Persons(P_Id int NOT NULL CHECK (P_Id>0),LastName varchar(255) NOT NULL,FirstName varchar(255),
Address varchar(255),City varchar(255))
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiplecolumns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
http://r4r.co.in/SQL/01/tutorial/basics/logical_operator.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/string.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/comparison.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/logical_operator.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/string.shtmlhttp://r4r.co.in/SQL/01/tutorial/basics/comparison.shtml -
8/3/2019 Rdbms Quan Book (Debraj)
20/27
CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes'))
The DEFAULT Constraint
A default constraint can be used to assign a constant value to a column, and the
user need not insert values for such a column . Only one DEFAULT constraintvalues can be created for a column , but the column cannot be an IDENTITY
column. The system-supplied values like USER, CURRENT_USER, and user definedvalues can be assigned as defaults.
CREATE TABLE table_name
(column_name data_type DEFAULT [constant_expression])
where, constraint_name specifies the name of the constraint to be created.
constant_expression specifies an expression that contains only constant values
and can contain NULL.
For Example:
CREATE TABLE employee(cCitychar (14) DEFAULT 'New Delhi', emp_id varchar(15))
The above command use to create a DEFAULT constraint on the cCityattribute. Ifa city is not specified, then the cCityattribute would contain 'New Delhi' bydefault.
-
8/3/2019 Rdbms Quan Book (Debraj)
21/27
If table already created then using ALTER command we specified theDEFAULT constraint
ALTER TABLE employee
ADD CONSTRAINT defcCity DEFAULT 'New Delhi' FOR cCity
INDEXES
An Indexes is:
SQL server used an internal table structure that provide quick accessto rows of a table
It is totally based on the values of one or more columns
-
8/3/2019 Rdbms Quan Book (Debraj)
22/27
SQL Server indexes are like the indexes at the back of a book, which
help in locating content
Advantage Of Using Indexes
The primary purpose of an index is to provide faster access to data
pages When server searched anything, it searching the index at the place ofsearching the whole page
Server scan the index and get the address of data storage location and
directly access the information
Indexes are also used as a mechanism of enforcing data uniqueness
An index speeds up the processing of queries that use joins or otherclauses like ORDER BY or GROUP BY, by allowing to faster access of data
Improve the speed of the execution of queries
Enforce uniqueness of data
Speed up joins between table
Disadvantage Of Using Indexes
Indexes does not indexing every column of the table
It takes time to create index
Each index create requires space to store data along with the original
data source-the table
An index gets updated each time the data is modified
The IF...ELSE Statement and BEGIN...END Statement
IF...ELSE Statement
Syntax:
IF boolean_expression{sql_statement}
ELSE boolean_expression
{sql_statement}
where, boolean_expression is the condition that evaluates to either TRUE orFALSE.
sql_statement is any T-SQL statement.
statement_block is a collection of T-SQL statements.
BEGIN...END Statement
Syntax:
-
8/3/2019 Rdbms Quan Book (Debraj)
23/27
BEGIN{sql_statement}
END
where, sql_statement is one or more SQL statements
The BEGIN...END block is nested and is most often used with the IF...ELSEstatement and the WHILE looops.
Example:
IF EXISTS (SELECT * FROM employee WHERE emp_name='anchal')
BEGIN PRINT 'The Details of employee are Available'
SELECT * FROMemployee WHERE emp_name='anchal'END
ELSE PRINT 'Employee details not Available'
Out Put: anchal related information viewed
IF EXISTS (SELECT * FROM employee WHERE emp_name='anchal')
BEGIN PRINT 'The Details of employee are Available'
SELECT * FROMemployee WHERE emp_name='Ram'END
ELSE PRINT 'Employee details not Available'
Out Put:
There is no information shown related to Ram
For Example: There are number of employee in the employee table and theresalary different according to there experience, the administrator want to increase
there salary then this code be written.
SELECT * FROMemployee
-
8/3/2019 Rdbms Quan Book (Debraj)
24/27
IF (SELECTMAX (emp_sal) FROM employee )
-
8/3/2019 Rdbms Quan Book (Debraj)
25/27
Better security mechanism: Users can be granted permission to
execute a stored procedure even if they do not own the procedure
Types Of Procedures
User Defined Stored procedure: The user defined stored procedures
are created by users and stored in the current database
System Stored Procedure: The system stored procedure havenames prefixed with sp_. Its manage SQL Server through administrative
tasks. Which databases store system stored procedures are master andmsdb database
Temporary Stored procedures: The temporary stored procedures
have names prefixed with the # symbol. Temporary stored proceduresstored in the tempdb databases. These procedures are automatically
dropped when the connection terminates between client and server
Remote Stored Procedures: The remote stored procedures areprocedures that are created and stored in databases on remote servers.
These remote procedures can be accessed from various servers, provided
the users have the appropriate permission Extended Stored Procedures: These are Dynamic-link libraries
(DLL's) that are executed outside the SQL Server environment. They areidentified by the prefix xp_
How To Create Stored Procedure
The CREATE PROCEDURE statement
Guideline
Identify the database in which the stored procedure has to be created
Determine the type of stored procedure Determine the name for the stored procedure
Write the batch statement
Syntax
CREATE PROCEDUREproc_nameAS
BEGINsql-statement 1
sql-statement 1
END
where, proc_name specifies the name of the stored procedure.
For Example
CREATE PROCEDURE empNameList
ASBEGIN
SELECT 'Employee'=emp_name, 'Salary'=emp_sal
-
8/3/2019 Rdbms Quan Book (Debraj)
26/27
FROM employeeEND
Stored Procedure Created.
Check the existence of the procedure in the database
Syntax
sp_helptextproc_name
sp_helptext empNameList
Out Put
Execute the procedure
Syntax
EXECUTEproc_name
EXECUTE empNameList
Out Put
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields fromone or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as ifthe data were coming from one single table.
-
8/3/2019 Rdbms Quan Book (Debraj)
27/27
SQL CREATE VIEW Syntax
CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, usingthe view's SQL statement, every time a user queries a view.
SQL CREATE VIEW Examples
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not discontinued)from the "Products" table. The view is created with the following SQL:
CREATE VIEW [Current Product List] ASSELECT ProductID,ProductNameFROM ProductsWHERE Discontinued=No
AutoincrementCREATE TABLE Persons(P_Id PRIMARY KEY AUTOINCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))
SqlserverCREATE TABLE Persons(P_Id int PRIMARY KEY IDENTITY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))