Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
25 views62 pages

Unit2 Dbms

The document provides an overview of relational databases, including key concepts such as tables, tuples, attributes, and keys (primary, foreign, candidate, and alternate). It explains the importance of integrity constraints like entity and referential integrity in maintaining data accuracy and consistency. Additionally, the document introduces SQL as the standard language for managing relational databases, detailing its commands and data types.

Uploaded by

libnaansu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
25 views62 pages

Unit2 Dbms

The document provides an overview of relational databases, including key concepts such as tables, tuples, attributes, and keys (primary, foreign, candidate, and alternate). It explains the importance of integrity constraints like entity and referential integrity in maintaining data accuracy and consistency. Additionally, the document introduces SQL as the standard language for managing relational databases, detailing its commands and data types.

Uploaded by

libnaansu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 62
Database Design and Management 2-3 Relational Model and SQL Part I : Relational Model Introduction to Relational Databases * Relation database is a collection of tables having unique names * For example — Consider the example of Student table in which the information about the student is stored. Fig. 2.1.1 Student table The above table consists of three column headers RolINo, Name and Phone. Each row of the table indicates the information of each student by means of his Roll Number, Name and Phone number. Similarly consider another table named Course as follows — Fig. 2.1.2 Course table Clearly, in above table the columns are CourseID, CourseName and Credits. The CourselD 101 is associated with the course named Mechanical and associated with the course of mechanical there are 4 credit points. Thus the relation is represented by the table in the relation model. Similarly we can establish the relationship amon, tables by defining the third table. For example ~ Consider the table Admission as 3 the two , eo TECHNICAL PUBLICATIONS - an up-thrust for knowledge “ en Dotabese Desig Fig. 2.1.3 Admission the RollNc From this third table we can easily find out that the course to which io 00 admitted is computer Science. Doma domain. | Relational Model Concepts >dermittec There are some commonly used terms in Relational Model and those are - rames of data items arranged; That Table or relation : In relational model, table is a collection of 5 Below is an example; Ato rows and columns. The table cannot have duplicate data or rows. at student table NU ither alary Tuple or record or row : The single entry in the table is called tuple. The tup. represents a set of related data. In above Student table there are four tuples. One of t tuple can be represented as nt Attribute or columns : It is a part of table that contains several records. Each rect! can be broken down into several small parts of data known as attributes. For example! above table consists of four attributes such as RolINo,Name Marks and Phone. Relation schema : A relation schema describes the structure of the relation, witht name of the relation (i.e. name of table), its attributes and their names and type. Relation Instance : It refers to specific instance of relation i.e. containing a speci of rows. For example - the following is a relation instance - which contains the reco! with marks above 80. : wi 2222222222 3993333333, Domain : For each attribute of rel . lation, there is a set of permitted values called domain. For example ~ in above table, the domain of attribute Marks is set of all possible permitted marks of the students. Similarly the domain of Name attribute is all possible names of students. That means Domain of Marks attribute is (88,83,98) ___Atomic : The domain is atomic if elements of the domain are considered to be indivisible units. For example in above Student table, the attribute Phone is non-atomic. NULL attribute : A null is a special symbol, independent of data type, which means either unknown or inapplicable. It does not mean zero or blank. For example - Consider a salary table that contains NULL. Degree : It is nothing but total number of columns present in the relational database. In given Student table - The degree is 4.” Cardinality : It is total number of tuples present in the relational database. In above given table the cardinality is 3. . - TECHNICAL PUBLICATIONS ~ an up-thrust for knowledge Relational Mode) ~ iDetabees Design end Menegeriort imme ureitua2 = 0) asmanneemee meee Find out following for given Staff table i) No of Columns 1) No of tuples iti) Different attributes iv) Degree v) Cardinality — StafflD Name Sex |_ Designation Salary bed | soo John M Manager 50000 1 Oct. 2082 ‘S002 Ram M Executive | 20000 omnes {sms vee | F Supervisor 40000 He he ai Solution : i) No of Columns = 6 ii) No of Tuples = 3 iii) Different attributes are StafflD, Name,Sex, Designation, Salary, DOJ iv) Degree = Total number of columns = 6 v) Cardinality = Total number of rows = 3 Keys EES e) Keys are used to specify the tuples distinctly in the given relation. Various types of keys used in relational model are ~ Superkey, Candidate Ker Primary keys, foreign keys, Let us discuss them with suitable example 1) Super Key(SK): It is a set of one or more attributes within a table that ca uniquely identify each record within a table. For example — Consider the Stude: table as follows -— Fig. 2.3.1 Student ® TECHNICAL PUBLICATIONS = an up-thrust for. Databe: ise Design and Management 2-7 Relational Model and SQL The : © Superkey can be represented as follows (RotNe, Phone, Neme) (iam, Mais) key Superkey cele * eeN) and (RollNo,Phone,Name) we can identify the records : me, Marks) of two students can be same, hence this combination not necessarily help in identifying the record uniquely. 2) Candidate Key(CK) : The candidate key is a subset of superset. In other words candidate key is a single attribute or least or minimal combination of attributes that uniquely identify each record in the table. For example - in above given Student table, the candidate key is RegNo, (RollNo,Phone). The candidate key can : Candidate: key Candidate ——— snttititt 2202222222 3333333333 | Thus every candidate key is a superkey but every superkey is not a candidate key. 3) Primary Key(PK): The primary key is a candidate key chosen by the database designer to identify the tuple in the relation uniquely. For example — Consider the following representation of primary key in the student table © TECHNICAL PUBLICATIONS - an up-thrust for knowledge Database Desig” and Manager — Database DOS primary key, en 2222222222 | 3333333333 various possible primary keys than the above mentioned primary key, ame), (RollINo, Phone) candidate key and primary ¢ Other (RolINo), (RolINo,N The relation among super key, an be denoted by Candidate Key = Super Key - Primary Key Rules for Primary Key (i) The primary key may (ii) There is only one primary key in the relation. The value of primary key attribute can not be NULL. y have one or more attributes. (iii) (iv) The value of primary key attribute does not get changed. 4) Alternate key : The alternate key is a candidate key which i: database designer to uniquely identify the tuples. For example — is not chosen b Altemate key . 5) Foreign key : Forei; is a si : Foreign key is a single attrib te i i table that refers to the primary key of other table section of abut * Thus foreign keys refer to primary key. , * The table containing the prim: y key le 8 the primary key is called parent table and ent le TECHNICAL PUBLICA ra Database Desig co *B Phone aainnittt 2222222222 3333333333 ssible primary keys c mentioned primary key, various Po Other than the above (RollNo), (RollNo,Name), (RollNo, Phone) iat The relation among super key, candidate key and primary can be denoted by From easily find Candidate Key = Super Key — Primary Key Rules for Primary Key (j) The primary key may have one or more attributes. Gi) There is only one primary key in the relation. (ii The value of primary key attribute can not be NULL. (iv) The value of primary key attribute does not get changed. 4) Alternate key : The alternate key is a candidate key which is not chosen aa database designer to uniquely identify the tuples. For example — “ . 1 RollNo \ Name Marks ecc 98 1 oD0 67 Primar key " Altemate ke applica data. 5) Foreign key : Forei is i Ne ign key : Foreign key is a single attribute or collection of attributes i" the use table that refé efers to the primary key of other table. that tal primar * Thus foreign keys refer to primary key ¢ The table tainii i containing the primary key is called parent table and tt’ TECHNICAL PUBLICA’ ions” = AN Un thrieh fant me — Database Design and Management —_ 2-9 Relational Model and SQL containing foreign key is called child table. * Example - Student _ - + \ RollNo Phone Name Marks courseid [Coursename|/ Rago | | oor [san | ana cin | compawrsa|t ros | i i ' oa | zzazz2200 | one 3 ci | ewan [| ior |t ' 003 | a3933538 | coc °° cua | Mechanica [1 ica | tL S ' coe | aeeasaaaaa} p00 = cm | oa | mm |} Parent Table ciate Primary kay Foren hry From above example, we can see that two tables are linked. For instance we could easily find out that the ‘Student CCC has opted for ComputerSci course’ Review Question 1. Explain distinction among the terms primary key, with suitable example. Integrity Constraints Database integrity means correctness or accuracy of data in the database.A database may have number of integrity constraints. For example ~ (i) The Employee ID and Department ID must consists of two digits. (ii) Every Employee ID must start with letter. The integrity constraints are classified based on the concept of primary key and foreign key. Let us discuss the classification of constraints based on primary key and foreign key as follows — Entity Integrity Rule This rule states that ” In the relations , the value of attribute of primary key can not be null’. The NULL represents a value for an attribute that is currently unknown or is not applicable for this tuple. The Nulls are always to deal with incomplete or exceptional data. The primary key value helps in uniquely identifying every row in the table. Thus if the users of the database want to retrieve any row from the table or perform any action on that table, they must know the value of the key for that row. Hence it is necessary that the primary key should not have the NULL value. o TECHNICAL PUBLICATIONS - an up-thrust for knowledge Database Design and Management 2-10 ot ny tial Integrity Ri ERM Roferon ee acy and consistency of d « Referential integrity refers to the accur relationship Dotaboe ata with, » tables, This is ach or more tables. Achieves « In relationships, data is linked between (We 4 » reference a primary key value having the foreign key (in the assoc jated table) refe Pp in (this, we need to ensure that data on 5 2 of this, primary - or parent - table), Because sides of the relationship remain intact. . svar» foreign Key vahs en * The referential integrity rule states that whenes rn . must reference a valid, existing primary key in vee eles + Employes saa the Emploe a ee key attribute entitled Manage, ers, The Employees table has ' veetecins to the oie for each employee’s manager 1n the Managers table. Referential integrity enforces the following three rules: i) You cannot add a record to the Employees table unless Gs ManagedBy abs points to a valid record in the Managers table. Referential integrity p1 ; t insertion of incorrect details into a table. Any operation that doesn't satis I referential integrity rule fails. ii) If the primary key for a record in the Managers table changes, all correspondiz records in the Employees table are modified. iii) If a record in the Managers table is deleted, all corresponding records in t Employees table are deleted. Advantages of Referential Integrity Referential integrity offers following advantages : i) Prevents the entry of duplicate data. i) Prevents one table from pointing to a nonexistent field in another table. iii) Guaranteed consistency between "partnered" tables. iv) Prevents the deletion of a record that contains a value referred to by a foreif key in another table, ¥) Prevents the addition of a record to a table that contains a foreign key unlé there is a primary key in the linked table. iscuss the entity Integrity and refer Explain them with suitable examples, rential integrity constraints, a are = “eats 10 Design and Management neues rea Rotational Modol and SOL. art I: SQL | Introduction to SQL - + SQL stands for Structured Query ra, -anguage, « Itis the language of databases ts Bi bases and almost all companies use databases to store their © SQL makes use of query, ; management syste - Y: A Query is a set of instruction given to the database anags system. It tells any database what information we would like to get from the database. * SQL is case- insensitive. However it is become standard in SQL. to all capital letters for SQL keywords, saan 18 SON commun ws SQL is a standard language for Relational Database Management System (RDBMS). + There are various RDBMS software that are popularly used. It includes MySQL, Oracle, MS ACCESS, Microsoft SQL Server, Sybase and so on. Characteristics and Advantages 1) SQL is a standard computer language for creating and manipulating databases. 2) SQL is very simple and easy to learn. 3) SQL allows the users to create,update,delete and retrieve data from the database. 4) SQL is used to create view, stored procedures and functions ina database. 5) SQL allows the users to set the permissions on the tables, procedures and views in the database. SQL Data Types Various data types used in SQL are - 1) Numeric data types * Integer numbers : INT, INTEGER, SMALLINT, BIGINT * Floating-point (real) numbers : REAL, DOUBLE , FLOAT * Fixed-point numbers : DECIMAL(n,m), DEC(n,m), NUMERIC(n.m), NUM(n.m) 2) Character-string data types * Fixed length : CHAR(n), CHARACTER(n) © Varying length : VARCHAR(n), CHAR VARYING(n), CHARACTER VARYING(n), LONG VARCHAR o TECHNICAL PUBLICATIONS. - an up-thrust for knowledge ygement _ 2-12 Relational ny | Database Design a7 Mere Tn pject data types 3) cman | CLOB, CHAR LARGE OBJECT , CHARACTER LARGE OBjkey 7 pits : BLOB, BINARY LARGE OBJECT 4) Boolean data type Values of TRUE or FALSE or NULL 5) DATE data type «Ten positions © Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD 6) Additional Data type a) TIMESTAMP data type Itincludes the DATE and TIME fields. b) INTERVAL data type It specifies a relative value that can be used to increment or decrement an abs value of a date, time, or timestamp. DDL, DML, DCL, Structure There are four types of SQL commands - Fig. 2.6.1 Classification of SQL commands Data Definition Language © TECHNICAL PUBLICATIONS - an up-thrust for knowledge and Mane | Database Desipn SniNnepement 2-9 Relational Modo! and SOL pata Manipulation Language oo oe is used to retrieve either all or desired records one or more tables, : INSERT F ing the recorde int sed | E ‘oF inserting the records in the table, this command is used. Pati bone or more fields of the table, this command is used, This command is used for deleting the desired record. Transaction Control Language(TCL) ROLLBACK Difference between DDL and DML . DMLstands for Data Manipulation Language. DML commands are used for managing, data within the database. Tt works on one or more rows. a It can be classified as - procedural and non-procedural language. o TECHNICAL PUBLICATIONS - an up-thrust for knowledge relation tuple and attribuy rminology : In relational model we use the terms « Tel same terms are used in SQL as follows | Creation and Alteration Creating Table A database can be considered as a container for tables and a table is a gridy rows and columns to hold data. «Individual statements in SQL are called queries. © We can execute SQL queries for various tasks su data into the tables, deletion of record from table, and so on. ch as creation of tables, insertic In this section we will discuss how to create a table. step 1: We normally create a database using following SQL statement ee Be The blank table will be created wi with followin, g, structure Person_details Baa Insertion of Data into the Table « We can insert data into the table using INSERT statement. ‘Syntax eaaroe Lee Salers The above query will result into ~ [ AadharNo FirstName | MiddleName | LastName ‘Address City fea AAA BBB |__cce MG. Road Pune Modifying the Record from the Table + For modifying the existing record of a table, update query is used. The WHERE command is used to specify some condition. Based on this condition the ‘ed or can be updated or deleted. data present in the table can be display’ Example Consider following table cc ™ Database Design and Management Deleting Record from the Table «We can delete one or more records based on follows — Syntax Se some condition. The synta, The result will be - We can delete all the records from table. But in this deletion, all the records get without deleting table. For that purpose the SQL statement will be oe TECHNICAL PUBLICATIONS - an up-thrust for knowledge ‘petabase Design and Management 97 _—lational Mole and SOL 97 PR] SELECT olatione! Mode! end SOX The Select statement is The result veturne . used to fetch the data from the database tabl . s the data i latabase table. resultsets. in the form of table. These result tables are called « We can use the keyword DI i answer should not ener It is an optional keyword indicating that the DISTINCT pareien poeta Normal yy i i operator then it does not eliminate rs Hoe the SOK ions ‘Syntax [SBLECT coll, col2,..coln FROM table_name; 2S OR Example [SELECT AadhatNo, FirstName, Address, City FROM person_ The result of above query will be ple The above query will result into — = © Use of DISTINCT’ Keyword: The keyword DISTINCT is used along with the SELECT statements. « It is used to obtain duplication of element. unique values from the table. This query does not allow Databawe Poswign aint Maniagenient cee jannidter following dalabace table btadent Name Ankita Mohit Vrajkta Sunil Sharda This will result into. Where Command ‘The WHERE command is used to specify some condition. Based on this condi: data present in the table can be displayed or can be updated or deleted. Syntax Example Consider following table © TECHNICAL PUBLICATIONS» an up-thrust for knmucieciae — 2-49 : If we execute the following query Rotational Model and SOt The result will be If we want records of all those Se Person who liv query using WHERE clause as Person who live in city Pune then we we can write the Creating Synonym We can create a synonym (similar schema) by using create_synonym. db) procedure This procedure creates a synonym schema containing views that refer to all the tables and views in the original schema. For example - E— enka Database Design and Management ieee & “mysql> SHOW DATABASES; + | info Logical Operators «Using WHERE clause we can use the ope’ * AND operator displays the records if all AND operator are true. ¢ OR operator displays the records if any operator is true. © NOT op Consider following table Example of AND If we execute following query — ators such as AND, OR and NOT. | the conditions that are separated us, one of the condition separated using” erator displays a record if the condition is NOT TRUE. patabase Design and Management 2-21 Relational Model and SQL The result will be — syntax of OR Example of OR The result will be — Syntax of NOT Example of NOT The result will be The BETWEEN Operator * The between operator can be used to simplify the where clause which is used to denote the value be less than or equal to some value and greater than or equal to some other value. * For example - of we want the names of the students whose marks are between 80 and 90 then SQL statement will be ® TECHNICAL PUBLICATIONS - an up-thrust for knowledge yment Database Desig” a A Ta Database Desig?” ‘SELECT name FROM Su? BETWEEN 80 and 90; WHE) use of Group by, Having, ii )L, statements are Order by, Gri Most commonly used clauses in SQL stat 1, Group by any . Let us discuss them along with syntax and examples. jo Order by Clauses (1) Order By Many times we need the records in the table to be in sorted order. « If the records are arranged in increasing order of some column then it is, ascending order. : « If the records are arranged in decreasing order of some column then it is descending order. For getting the sorted records in the table we use ORDER BY command. * The ORDER BY keyword sorts the records in ascending order by default. Database Design and Management The above query will result in LastName GGG bop (2) Group By * The GROUP BY clause is a SQL command that is used to group rows that have the same values. «The GROUP BY clause is used in the SELECT statement. © Optionally it is used in conjunction with aggregate functions. © The queries that contain the GROUP BY clause are called grouped queries «This query returns a single row for every grouped item. © Syntax: ah table as follows - fis Query : Find the total marks of each student in each city —o TECHNICAL PUBLICATIONS - an up-thrust for knowledge geuscT suM(marks), city FROM student GrouP BY city The result will be as follows — (3) Having * HAVING filters records that work on summari: « HAVING applies to summarized group records, individual records. © Only the groups that meet the HAVING criteria will be returned. + HAVING requires that a GROUP BY clause is present. «WHERE and HAVING can be in the same query. Syntax : zed GROUP BY results. whereas WHERE app = Query : Find the total marks of i = each student in the city named ‘Pune’ and ‘Mu —=—” ECT SUM(marks), city ara FROM Student ' (Group BY city , HAVING city IN(Pung: » ) «The result will be ag follows — SUMimarks) city 150 Pune 125 Mumbai Defining Constraints + We can specify rules for data ina table. When the ti is table is created at that time we can define the constraints. The constraint Al t can be column level ie. we can impose constraint on the column and table level i.e we can impose constraint on the entire table. * There are various types of constraints that can be defined are as follows - (1) Primary key : The primary key constraint is defined to uniquely identify the records from the table. The primary key must contain unique values. Hence database designer should choose primary key very carefully. For example Consider that we have to create a person_details table. with AadharNo, FirstName, MiddleName, LastName, Address and City. Now making AdharNo as a primary key is helpful here as using this field it becomes easy to identify the records correctly. The result will be CREATE TABLE person_details ( AadharNo int, FirstName VARCHAR(20), MiddleName VARCHAR(20), LastName VARCHAR(20), Address VARCHAR(30), City VARCHAR(10), PRIMARY KEY(AadharNo) % © TECHNICAL PUBLICATIONS - an up-thrust for knowledge Relational Mode) ang ——Feelattonal Mode! ang Patabase Design and Management 2-26 ___~ — — Cf STR. ary key usin CONSTRAINT keyworg , a prim We can create a composite key as example CREATE TABLE person_ details ( AadharNo int NOT NULL, FirstName VARCHAR(20), MiddleName VARCHAR(20), LastName VARCHAR(20) NOT NULL, Address VARCHAR(30), City VARCHAR(10). CONSTRAINT PK_person_details PRIMARY KEY(AadharNo, LastName) yb (2) Foreign Key * Foreign key is used to link two tables. key of another table. Foreign key for one table is actually a primary « The table containing foreign key is called child table and the table conta candidate primary key is called parent key. * Consider Employee Table Dept Table : * Notice that the "EmpID" column in the "Dept" table points to the "EmpID" colt! in the "Employee" table. ¢ The "EmpID" column in the "Employee" table is the PRIMARY KEY in| "Employee" table. pamneee Deni et Nannie par Fewbanewnel AMO! it OM 9 he HONEY. asta ay tte "Hop alte Oo HOURKIGN HEY (nets Fiope lable TE PORTION Any PenWeen babton te DORTIGN at ‘ NREY avnatiaint abs Jeveribe tavalial dlata frame betng lamented Net he KHER Koy atau, bocatane (Epotvbe ty {wate fe edt ny provent action that avanlel dendsan’ HMR (Non to he ane ab thie vation contativedt (ay tie: table 6 The purpowe ot the Aa wn TOMA Key Comat iAlNE bila enfaree referential integrity Bat there any abso pertormanen ty MHOTLOC TY De Tavet Day tie tiicliiagy Then (ay yatir etatabane Penigany The table Dopl awn be crsatoat ORKATE TABLE DRT Dap int Deptame VARGHAR(RO), Binptd int, PRIMARY KRY(DepttD), a RAYCSmp tb) RIRRENO RE HMPLOYRR (HID) ave tatlowe ithe fared hey conateatint (3) Unique Unique constraint fs used to prevent same valued ina eotimn, ty the EMPLOYEE table, for example, YOU MAHE Want to prevent hyo or nore employees Mon haw tig ae identical designation, Phen iy that case we nun ue iniyie conalyalnt We can set the constraint as unique at the tine of creation at table, ar (the table be already created and we want to add the unique constraint then we can uae ALTER command For example 1) ORRATE TABLE RMPLOYEN( Ne KmpID INT NOT NULL, : Name VARCHAR (20) NOT NULL : Designation VARGHAR(20) NOT NULL UNIOUK, = Salary DECIMAL (12 8), ‘ PRIMARY KISY (Ihrap!D) x * I tabh Hready created then alo we can adit the riiignie cond atit aoe Hallowen arma SANOMARN) NOT NULL UNIQUE) (4) NOT NULL © By default the column can have NU JL, values, © NULL means unknown valien © TECHNICAL PUBLICATIONS an upelinial far hrioweeae Database Design and Managemen © We can set the column values as non ¢ Forexample ~ % the constraint Nor N x Uy NULL by usifl (5) CHECK at can be placed in q coh The CHECK For example e th constraint is used to limit the value rang! (6) IN operator The IN operator is just similar to OR operator. lues in WHERE clause. It allows to specify multiple val ‘Syntax Example Consider following table Employee ‘Database Design and Management ie 2-29 The result will be ~ — — __ Relational Mode! and SOL. “empName | eee . per] AAA pio. BBR al D102 orc ow D103 Bo Schema Change Statements Schema can be chan; ged by These commands are also k 'y adding or dropping tables, attributes and constraints. nown as schema evolution commands. There are two commands th. e the si jose are lat change the schema s and thi DROP and : Let us discuss these commands in detail " . The DROP Command « The DROP command i re haan “a is used to remove the object (table, domains and constraints) abase. There are two options for the DROP - CASCAD st command - CASCADE and * To use the RESTRICT option, the user must first individually drop each element in the schema, then drop the schema itself. That means, the schema is dropped only if it has no elements in it, otherwise the DROP command can not be executed. * Otherwise to remove completely some database schema CASCADE option is chosen. For example — to remove the Student_database . Student_database CASCADE; Ifthe table is to be deleted then the SQL command would be - Pees CRACK TLS * The DROP TABLE command not only deletes all the records in the table if successful, but also removes the table definition from the catalog. Lf it is desired to delete only the records but to leave the table definition for future use, then the DELETE command. For example - © The following SQL statement deletes all row: deleting the table s in the "Students" table, without eee The ALTER Command There are SQL commands for alterati: or delete some column from the table usiny ‘on of table. That means we can add new column 1g these alteration commands. ® TECHNICAL PUBLICATIONS - a” up-thrust for knowledge Database Design and Management Syntax for Adding columns TABLE | table_name “name datatype; _ Example Consider following table LastName Example ‘Database Design and Managemeny regement 2-31 wesw 2:3 _____ Relational Model and Sa cute following command ‘Address; Then the result iq] be as follows - Describe DI cri ROP TABLE command of SQL with both the options CASCADE and RESTRICT. Aggregate Functions + An aggregate function allows you to perform a calculation on a set of values to return a single scalar value. * SQL offers five built-in aggregate functions : 1. Average : avg, Minimum : min Maximum : max Total : sum ys PF YN Count : + The aggregate functions that accept an expression parameter can be modified by the keywords DISTINCT or ALL. If neither is specified, the result is the same as if ALL were specified. ® FEPuNIOAL PUBLICATIONS. - an up-thrust for knowledge Relat Dettbase Desi end Meragement _2.s_____ietna/tag, 2-32 . For example ~ 7, e value * The avg function is used to compute averas' Cp, average marks of the students we can cd i? ; ues in the spe er of values in . Count function is used to count the re pice re ey = numeric and non-numeric UNT Tt works on returns the count of all the i he COUNT function that 1. and duplicates, Foren implementation of the i) also. considers Nulls specified table. COUNT Consider following table ¢ The min function is used to get the minimum value from the specified colu example ~ Consider the above created Test table f * The max function is used to get the maximum value from the specified colum” example - Consider the above created Test table = TECHNICAL PUBLICATIONS - an up-thrust for 1 |. value. For example ~ T, 7 © The avg function is used to compute average average marks of the students we can us Se ee values in the spec jon is used to count the total number of count oe © The Count function is u je and non-numeric data ee a ' It works on both numeric am function that returns the eee 1% implementation o nar) abe considers Nulls and duplicates. For =, specified table. CO Consider following table * The min function is used to get the minimum value from the specified colum* example ~ Consider the above created Test table / ' * The max function is used to get the maximum value from the specified colu™™ example - Consider the above created Test table + TECHNICAL PUBLICATIONS. an up-thrust for knowledge — Relations! Mode! ana sau. ¢ The sum function is u S Use d to ge © get total sum value from the specified column. For example - Consider the above created Test tabl a st table SQL Statement SELECT sum(vatue) FROM Test Output 1000 Consider, the following database, Student(RollNo, Name, Address) Subject(Sub_code, Sub_Name) Marks (Roll_no, Sub_code, Marks) Write following queries in SQL. Find average marks of each student, along with the name of Student Solution : SELECT Name, AVG(Marks) FROM Student,Marks \WHERE Student Roll_No=! Marks.Roll_No Built-in Functions * InSQLa built-in function is a piece for pl rogramming, that takes zero or more inputs and returns a value. . jons is ABS(), which when given a value calculates the © Anexample of a built-in funct of the number. absolute (non-negative) value Query SELECT ABS(-9) Result; Output Result — value Returned , | Absolute value of” Remainder of divided by" m raised to the nth power round (ml 1) m rounded to the nth decimal place pRUNC (mE? 1) m truncated 10 the nth decimal place i }— oo nn sIN(n) sine (n) — cos (n) wine) es ee TAN (n) oe con ox sQRT(n) positive square root of date DP(n) e raised to the power n LOG (n2,n1) logarithm of nl, base n2 ‘CEIL (n) : e Phin smallest integer greater than or equal ton ee) greatest in i teger smaller than or equal ton SIGN (n) - ai ifn<0,0ifn=0,and1ifn>0 | String Functions i | _ First letter of each word is chan; ged to uppercase an id all other letters are in lower case. rercase. Design and Me patabase Design and Management _2-35 _ Relational Model and SOL __Allletters are changed to uppercase. _Coneatenation of s1 and 62. Equivalent to s1 | | $2 Returns s with characters removed up to the first i ____ character not in set; defaults to space RTRIM(s,set}) Returns s with final characters removed after the | REPLACE (s, search_s jace_s }) a __last character not in set; defaults to space Returns s with every occurrence of search_s in s replaced by replace_s; default removes search_s SUBSTR (s,m[,n]) Retums a substring from s, beginning in position m and n characters long; default returns to end of s. ENGTH (s) Returns the number of characters in s. Value Returned Date d plus n months ~ Date of the last day of the month containing a Number of months by which e precedes d ‘The date and time in time zone b when date d is for time zone @ Date ofthe first day of the week after d Current date and time Latest of the given dates _ Earliest of the given Database Design and Management 36 Will result in 2019-06-27 10:02:39 EXE Set Operations Set is a collection of elements on which union, intersection and difference oe can be performed. 1) Union : To use this UNION clause, + of columns selected each SELECT statement must have i) The same numbe! ii) The same number of column expressions iii) The same data type and iv) Have them in the same order This clause is used to combine two tables using UNION operator. It replace; 4 operator in the query. The union operator eliminates duplicate while the union 3), will retain the duplicates. Syntax : The basic syntax of a UNION clause is as follows - SELECT column! [, colunn2 | FROM; ‘able! [, table2 | [WHERE condition] UNION SELECT column! [, column2 | FROM tablet [, table2 | (WHERE condition] Here, the given condition could be any given expression based on your requir’™ Example : Find the names of the students who have reserved the ‘DBMS’ book Book The query can then be written by considering the Student, Reserve and Book tat SELECT $.sname FROM Student S, Reserve R, Book B e — S.sid=R.sid AND R.isbn=B isbn AND B.bname="DBMS' SELECT S.sname FROM Student S, Reserve R, Book B _ WHERE S.sid=Rsid AND Risbn=B.isbn AND B.bname='0s" - F Betenase Design and Managemen 2 Intersect Ty, help of Lnterseg 2-97 Relational Model a0 SK. SOMMON entries between the operates ne two tables can be represented with the Places the AND Operator in the query, Syntax: The basic syntay of @INTEReROT os INTERSI RC V clause is as follows - erereettern enn 7 | SBLECT cotwmnt |, cohumng | FROM table! |, tablea | ' {WHERE condition} aoe Example : Fi & 1 Example : Find the students who have reserved both the ‘DBMS’ book and ‘OS’ Book ‘The query can then be writt ideri : a len by considering the Student, Reserve and Book table as ___ FROM Student 8, Reserve R, Book B WHERE S.sid=R.sid AND R.isbn=B.isbn AND =" y a B.bname='DBMS' , SELECT S.sname FROM Student S, Reserve R, Book B WHERE S.sid=R.sid AND R.isbn=B.isbn AND B.bname='0s' 3) Except : The EXCEPT clause is used to represent the set-difference in the query. This query is used to represent the entries that are present in one table and not in other. Syntax : ‘The basic syntax of a EXCEPT clause is as follows - es 0 have reserved both the “DBMS’ book but net reserved ‘OS’ Book The query can then Student, Reserve and Book table as ‘eens ring the Database Design and Management 2-38 ey isi si student 8, Reserve BO WHERE Ssid= Rid sate: Bisbn AND Biname="O8 EBB) Nested Queries In nested queries, a query is written inside a query: The result of inner query ig, in execution of outer query. There are two types of nested queries : ) Independent Query (ii) Corelated Query i) Independent Query : In independent nested queries, query execution starts from innermost query outermost queries. © The execution of inner query is independent of outer query, but the result of im query is used in execution of outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in writing independ nested queries. For example - Consider three tables namely Student, City and Student_City follows - Datadase DESUN aNd Aggy, ser yement — Relational Model arnt 8p Student_city ala ta y wor z vor : wor | 2 102 : 102 a 109 + Example 1- If we wa Rr Vant to tind out sid who live in city ‘Pune’ or ‘Chennai’ Wi pender al Pendent nested query using IN operator, Here we can use the you to specify multiple v. El y ple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions, ™ then write inde} operator allow Step 1: Find cid for cname=’Pune’ or ‘Cher ‘SELECT cid FROM City WHERE cname= nai’. The query will be ‘Pune’ or ‘Chennai’ Step 2: Using cid obtained in step 1 we can find the si ‘SELECT sid FROM Student_City WHERE cid IN ( SELECT cid FROM City . WHERE cname="Pune’ or cname='Chennai' . The query will be ) The inner query will return a se! return those sid for which cid is equal to it will return 1, 2 and 4. Example 2 : If we want to find out SELECT sname FROM Student ‘WHERE sid IN (| SELECT sid FROM Student_City rs 101 and 103 and outer query will t with membe and 103 in this case). Se any member of set (LOL wr Chen sname who live in city ‘Pune’ ol GATIONS knowledge TECHNICAL PUBLICATIONS = 8" up-thrust for Hotatiovel Morty Datadase Design ant Management 1:2 > WHERE cid IN ( SELECT eta FROM City WHERE came = ‘Pune’ or cname® ‘Chennal’ ) Wy) Co , - | ) Co-related cae { queries, the output of inner query depends on the row whig rested queries, the For example ent who live in cit In co-related being currently executed in outer query: Stud y with cid a8 101, it ca, » of Stud If we want to find out sname done with the help of co-related nested query as + SELECT sname FROM Student S WHERE EXISTS: (| SELECT* FROM Student_City SC WHERE S.sid=SC.sid and SC.cid=101 ) Here For each row of Student §, it will find the rows from Student_City where Ss SC.sid and SC.cid=101. If for a sid from Student §, atleast a row exists in Student_City SC with cid=101, ¢ inner query will return true and corresponding sid will be returned as output. E22 string Operations « For string comparisons, we can use the comparison operators =, <, >,<=,>=° " the ordering of strings determined alphabetically as usual. © SQL also permits a variety of functions on character strings such as concatend! suing operator! |, extracting substrings, finding length of string, converting sth to upper case(using function upper(s)) and lowercase(using function lower removing spaces at the end of string(using function(trim(s)) and so on. * Pattern matching can also be performed on stri ; n strings usin, f 5 characters — 8 iB two types of SP © Percent(%): It matches zero, one or multiple characters © Underscore(_): The _ character matches any single charact er. o TECHNICAL PUBLICATIONS - an up-thrust for knowledos os sow psnbase Des at Management a gy ene Motte 208 | ¢ The percentage and underscore can be used in combinations. Patterns are case sensitive, That me: lowercase characters or vice versa, : «For instance ; ‘ans upper case characters do not match ‘Data%" cl ‘i ° Matches any string beginning with “Data”, For instance it could be with “Database”, “DataMining”,"DataStructure” © ‘~~ matches any string of exactly three characters, o ‘___ %'matches any string of at least length 3 characters. The LIKE clause can be used in WHERE clause to search for specific patterns. For example ~ Consider following, Employee Database Mohsin Supriya Sonia (1) Find all the employee with EmpName starting with “s” SQL Statement : Output J om | Sunil ee - an up-thrust for knowiedg® © TECHNICAL PUBLICATIONS Database Design and Managemen = . g and end with a (2) Find the names of employee whose name begin with SQL Statement : SELECT EmpName FROM Employee WHERE EmpName LIKE ‘S%e" Output name begin with S and followed by exacty (3) Find the names of employee whose characters ‘SELECT EmpName FROM Employee WHERE EmpName LiKE Bei Output Tn EmpName Sunil Sonia i, ‘Suraj ae es Join and its Types The SQL Joins clause i: database. A JOIN is a means for combining fields from two tables b common to each. Various types of join operations are — s used to combine records from two or more tables * y using vale Right join Full join Fig. 2.21.1 Types of join operations Database Design and Management 2-42 ——Felatione! Mode, 5 id end with (2) Find the names of employee whose name begin with S 2™ Soe ‘SQL Statement SELECT EmpName FROM Employee ‘WHERE EmpName LIKE ‘S*e" Output Tnphiame Supriya (3) Find the names of employee whose name begin with S and followed by exacy characters ‘SELECT EmpName FROM Employee : WHERE EmpName LIKE ‘S____‘ Output EmpName Sunil en Suraj Join and its Types The SQL Joins clause is used to combine records from two or more ta database. A JOIN is a means for combining fields from two tables by usi common to each. Various types of join operations are — Left join Right join Full join Fig. 2.21.1 Types of join operations Database DeSion ane Management 248 Relational Model and SQL. Example : Consider t ee i Wwo tables cotumn in following tables nn Nine the joins in SQL. Note that eid is common, City 4) Inner Join : The most i . important and frequently used of the joins is the INNER JOIN. They are also known as an EQUIJOIN. : « The INNER JOIN creates a new result table by combining column values of two tables (Table1 and Table2) based upon the join-predicate. «The query compares each row of tablel with each row of Table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of ‘A and B are combined into a result row. It can be represented as : Table 2 The basic syntax of the INNER JOIN is as follows. Syntax: mely Student and City, we can apply inner i bles nal * Example : For above given two tables a re be omuron join. It will return the record that are matching in bo column cid. The query will be Left Join(Outer Join) : : ° y left table, even if there are no he | ©) The SQL LEFT JOIN returns all rows from ¢ in the right table. This means that if the ON clause matches 0 (zero) records in right table; the join will still return 2 row in the result, but with NULL in, column from the right table. © This means that a left join returns values from the right table or NULL © It canbe represented as — all the values from the left table, plus mat, in case of no matching join predicate. * Example : For above given two tables namely Student and City, we can apply! join. It will Return all records from the left table, and the matched records from right table using the common column cid. The query will be The result will be re and Mar pwtase Desi end Management a 4s ___Raelational Model and SOk. 3) Right Join(Outer Join) : «The SQL RIGHT JOIN ye matches in the left table, This MeANS that if the ON will still return a row in ¢ table. «This means that a right values from the left tabl ‘turns all rows from the right table, even if there are 0 clause matches 0) (zero) records in the left table; the join he result, but with NULL in each column from the left join returns all the values from the right table, plus matched le ot NULL in case of no matching join predicate. « Itcan be represented as follows : ¢ Example : For above given two tables namely Student and City, we can apply Right join. It will return all records from the right table, and the matched records from the left table using the common column cid. The query will be The result will be — 4) Full Join (Outer Join) : : * The SQL FULL JOIN combines the results of both left and right outer joins. * The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side. er ee o TECHNICAL PUBLICATIONS - an up-thrust for knowledge Role Database Design and Management Raton Mery “s # It can be represented as, CULL JOIN is as follows : * Syntax: The basic syntax of a FULL JOINS The result will be - © Exai Fi ables namely Studen and City, Je : For above given two tables ly St t we can imple : c hen there is a match in one of the tables. 7. Explain various types of outer join operations with example. 2. Explain different join operations in relational algebra with suitable example. 3. Explain join operations with example. Exist, Any, All Operators The EXISTS operator is used to test for the existence of any record in a sub? The EXISTS operator returns true if the subquery returns one or more records. ° Syntax @ TECHNICAL PUBLICATIONS. - an up-thrust for

You might also like