Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
39 views
221 pages
SQL Part III With Anno
Uploaded by
praedie
AI-enhanced title
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
Download now
Download
Save SQL_Part__III_with_anno For Later
Download
Save
Save SQL_Part__III_with_anno For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
39 views
221 pages
SQL Part III With Anno
Uploaded by
praedie
AI-enhanced title
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
Download now
Download
Save SQL_Part__III_with_anno For Later
Carousel Previous
Carousel Next
Download
Save
Save SQL_Part__III_with_anno For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 221
Search
Fullscreen
Query Language * After designing a data base, that is ER diagram followed by conversion in relational model followed by normalization and indexing, now next task is how to store, retrieve and modify data in the data base. * Thought here we will be concentrating more on the retrieval part. Query languages are used for this purpose. KGYT* QUERY LANGUAGE + ALanguages using which user request some information from the database. Non-Procedural Query Language Procedural Query Language KGYTProcedural Query Language * Here users instruct the system to performs a sequence of operations on the data base in order to compute the desired result. * Means user provides both what data to be retrieved and how data to be retrieved. e.g. Relational Algebra. KGYTNon-Procedural Query Language * In nonprocedural language, the user describes the desired information without giving a specific procedure for obtaining that information. * What data to be retrieved e.g. Relational Calculus. Tuple relational calculus, Domain relational calculus are declarative query languages based on mathematical logic KGYT* Relational Algebra (Procedural) and Relational Calculus (non-procedural) are mathematical system/ query languages which are used for query on relational model. * RAand RC are not executed in any computer they provide the fundamental mathematics on which SQL is based. * SQL (structured query language) works on RDBMS, and it includes elements of both procedural or non-procedural query language. Relational model RDBMS RA, RC sat Algo Code Conceptual Reality Theoretical Practical Chess. Battle Field KGYTBreakRELATIONAL ALGEBRA * RA like any other mathematical system provides a number of operators and use relations (tables) as operands and produce a new relation as their result. * Every operator in the RA accepts (one or two) relation/table as input arguments and returns always a single relation instance as the result without a name. KGYT* It also does not consider duplicity by default as it is based on set theory. Same query is written in RA and SQL the result may be different as SQL considers duplication. * Asit is pure mathematics no use of English keywords. Operators are represented using symbols. KGYTBASIC / FUNDAMENTAL OPERATORS + The fundamental operations in the relational algebra are select, project, union, set difference, Cartesian product, and Rename. (9) (1) (U) (-) (x) (p) KGYTDERIVED OPERATORS * There are several other operations namely: set intersection, natural join, and assignment. LET By Ture Pais eae (x) eesti) C) AnB=A-(A-B) Dye (%-. 11) PSs KGYTThe select, project, and rename operations are called unary operations, because they operate on one relation. Union, Cartesian product and set difference operate on pairs of relations and are, therefore, called binary operations. Relational algebra also provides the framework for query optimization. KGYTRelational schema - A relation schema R, denoted by R (Ay, A;, ..., A,), is made up of a relation name R and a list of attributes, A;, A;, ..., A,. Each attribute A; is the name of a role played by some domain D in the relation schema R. It is use to describe a Relation. E.g. Schema representation of Table Student is as — STUDENT (NAME, ID, CITY, COUNTRY, HOBBY). Relational Instance - Relations with its data at particular instant of time. KGYTQf D,, D,, ...... D, are domains in a relational model, then the relation is a table, which is a subset of (NET-JUNE-2013) (A) D,+D,+...+D, (B) D, xD, x... xD, (c)D, UD, U...UD, (D) D, -D,-...-D, KGYTBreakThe Project Operation (Vertical Selection) Main idea behind project operator is to select desired columns. The project operation is a unary operation that returns its argument relation, with certain attributes left out. Projection is denoted by the uppercase Greek letter pi (1). A eotumn_name (table_name) KGYT* We list those attributes that we wish to appear in the result as a subscript to N, argument relation follows in parentheses. * Minimum number of columns selected can be 1, Maximum selected Columns can be n - 1. ee KGYT* Some points to remember * Eliminates duplicate rows in a result relation by default. © Tlaa,a2,an ("), Ay, Ag, An refers to the set of attributes to be projected. * Itis not commutative. KGYT= > Q 4Q Suppose R,(A, B) and R,(C, D) are two relation schemas. Let r, and r, be the corresponding relation instances. B is a foreign key that refers to C in R,. If data in r, and r, satisfy referential integrity constraints, which of the following is ALWAYS TRUE? (Gate-2012) (2 Marks) a) Malta) — Melt.) = 9 b) TMe(ra) - Malta) = ¢) Tats) = TMelr2) ) Tals) - Telr2) # ®BreakThe Select Operation (Horizontal Selection) The select operation selects tuples that satisfy a given predicate/Condition p. Lowercase Greek letter sigma (a) is used to denote selection. It is a unary operator. Eliminates only tuples/rows. condition (table_name) = KGYTKGYT* Predicate appears as a subscript to o, the argument relation is in parentheses after the o. * Commutative in Nature, 6,,( 0,2(r))= 0,2 0,,(r)) KGYT* Some points to remember We allow comparisons using =, #, <, >, $ and 2 in the selection predicate. Using the connectives and (A), or (V), and not (-), we can combine several predicates into a larger predicate. Minimum number of tuples selected can be 0, Maximum selected tuples can be all. Degree (Result relation) = degree (parent relation), where degree refers to no. of attributes. 0 <= cardinality (result relation) <= cardinality (parent relation), where cardinality refers to no. of tuples. KGYTQ What is the optimized version of the relation algebra expression Tear (Ta2(O¢(G,2(r)))), where A,, A, are sets of attributes in r with A,CA, and F,, F, are Boolean expressions based on the attributes in r? (Gate-2014) (2 Marks) a) TearlOeer a r2\(")) b) Tear (Oper veal") €) Marler a r2y(")) ) Taa(Oper veay(t))Q Consider the following schemas: (NET-DEC-2013) Branch = (Branch-name, Assets, Branch-city) Customer = (Customer-name, Bank name, Customer-city) Borrow = (Branch-name, loan number, customer account-number) Deposit = (Branch-name, Account- number, Customer-name, Balance) Using relational Algebra, the Query that finds customers who have balance more than 10,000 is (A) 7 customer-name (O batance > 10000 (Deposit) (B) 0 customer-name ( balance > 10000 (Deposit) (C) 7 castomer-name (© balance >10000 (Borrow) (D) 6 customer-name (7 patance >10000 (Borrow) KGYTQ Which of the following query transformations (i.e., replacing the I.h.s. expression by the r.h.s. expression) is incorrect? R, and R, are relations. C,, C, are selection conditions and A,, A, are attributes of R,. (Gate-1998) (2 Marks) a) 5 6 (0 cp Ry) > 9 ea (0 cy (Ry)) b) 6 cq (M1 Ry) > Mar (9 cx (Ry) ©) cy (Ry U Ro) > © cq (Ry) UO cq (Ra) ) Max (0 ca(Ry)) > cy (ME ar (Ry)) KGYTBreakThe Union Operation * Itis a binary operation, denoted, as in set theory, by U. * Written as, Expression, U Expression, r Us={t | t€rort €s} * Fora union operation r U s to be valid, we require that two conditions hold: + The relations r and s must be of the same arity. That is, they must have the same number of attributes, the domains of the ith attribute of r and the ith attribute of s must be the same, for all i. * Mainly used to fetch data from different relations. KGYT* Some points to remember * Deg (R U S) = Deg(R) = Deg(S) * Max (IRI, ISI) <= IRUSI <= (IRI+ISI) KGYTBreakThe Set-Difference Operation The set-difference operation, denoted by -, allows us to find tuples that are in one relation but are not in another. It is a binary operator. The expression r - s produces a relation containing those tuples in r but not ins. We must ensure that set differences are taken between compatible relations. For a set-difference operation r — s to be valid, we require that the relations r and s be of the same arity, and that the domains of the ith attribute of r and the ith attribute of s be the same, for all i. * O<=IR-SI<=IRI KGYTBreakThe Cartes Product Operation * The Cartesian-product operation, denoted by a cross (x), allows us to combine information from any two relations. * Itis a binary operator; we write the Cartesian product of relations R, and R, as R, x Ra. * Cartesian-product operation associates every tuple of R, with every tuple of R,. R, XR, = {rs | r€ R, ands € R,}, contains one tuple
(concatenation of tuples r and s) for each pair of tuples r € Ry, S € Ry. T R*R, wln|R|> 2\O|v\a vi a!O|o N|<|x<|o KGYTR, XR, returns a relational instance whose schema contains all the fields of R, (in order as they appear in R,) and all fields of R, (in order as they appear in R,). If R, has m tuples and R, has n tuples the result will be having = m*n tuples. Same attribute name may appear in both R, and R,, we need to devise a naming schema to distinguish between these attributes. KGYTce 4BreakRename Operation The results of relational algebra are also relations but without any name. The rename operation allows us to rename the output relation. It is denoted with small Greek letter rho p. Where the result of expression E is saved with name of x. Prin, 2,03, a4,...any(E) KGYTQ Write a RELATIONAL ALGEBRA query to find the account_no along with balance with 8% interest as total amount, with table name as balance sheet? KGYTBreakAdditional Relational-Algebra Operations * If we restrict ourselves to just the fundamental operations, certain common queries are lengthy to express. Therefore, we use additional operations. * These additional operations do not add any power to the algebra. * They are used to simplify the queries. KGYTSet-Intersection Operation We will be using 1 symbol to denote set intersection. ras=r-(r-s) Set intersection is not a fundamental operation and does not add any power to the relational algebra. rns={t|t€randte€s} 0 <=1RAS1 <= min (IRI, ISI) KGYTBreak‘The Natural Operation The natural join is a binary operation that allows us to combine certain selections and a Cartesian product into one operation. The natural join of r and s, denoted by r > s The natural-join operation forms a Cartesian product of its two arguments, performs a selection forcing equality on those attributes that appear in both relation schemas and finally removes duplicate attributes. KGYT* The natural join of r and s is a relation on schema R U S formally defined as follows: mss Mpys (GA asAvndzsAyn..ardasA, (r x 5)) win|e | > 2|0|-0\0 ula|ola N|<|x|o KGYTKGYTBreakQ Consider the relations R(A, B) and S(B, C) and the following four relational algebra queries over Rand S: IM, (RDAS) II. R Dt N1,(S) IL. R-9 (F4(R) x M,(S)) WV. My, a5 (RS) Where R:B refers to the column B in table R. One can determine that: (NET-JULY- 2016) (a) |, Ill and IV are the same query. (b) II, Ill and IV are the same query. (c) |, Il and IV are the same query. (d) |, Il and Ill are the same query KGYTQ (NET-DEC-2015) Consider the following three tables R, S and Tin this % satura joins (=). () 4 the projection of : z 3 r 4 « f the join operations are | rs | 3] ea] p> b ab a 5b ols al 4 lb ais f bbls Fossible answer blag nis question are aleo given sa balow a = qs fr 2 aj § 1 2 3 s 2 4 : . a | a 5 6 af Jf. 4 8 fp 2 ls | RB 4 8 jf salsa] > 8 iz sal? sap ls 8 jf os se 5s sip 5 3 © © @ @) ee cing tainly meme o @ 2 & e © ® @ KGYTQ The following functional dependencies hold for relations R(A, B, C) and S(B, D, E). BOA ADC The relation R contains 200 tuples and the relation S contains 100 tuples. What is the maximum number of tuples possible in the natural join R > S? (Gate-2010) (2 Marks) a) 100 b) 200 c) 300 d) 2000 KGYTQ Let R and S be two relations with the following schema (Gate-2008) (2 Marks) R(P.Q, R1, R2, R3) S$ (P.Q, $1, $2) where {P, Q}is the key for both schemas. Which of the following queries are equivalent? i) NM, (R a S) ii) Mp (R) > 1, (S) iii) Np (Mp (R) 9 Mp q(S)) iv) Mp (Mp q(R) ~ (Mp, q(R-Mp, a (S))) ) Only Land Il b) Only | and tl ¢) Only |, Il and ll d) Only |, Ill and IV iXQ Let r be a relation instance with schema R = (A, B, C, D). We define r, = Na p.c (r) and r, = Map (r). Let s =r, * r, where * denotes natural join. Given that the decomposition of r into r, and r, is lossy, which one of the following is TRUE? (Gate-2005) (1 Marks) (A)scr (B)rUs=s (C)rcs (D)r*s=sQLet rand s be two relations over the relation schemes R and S respectively, and let A be an attribute in R. The relational algebra expression o ,_,(r & s) is always equal to (Gate-2001) (1 Marks) a) o,_,(r) b)r C) Og. (Fr) Das d) None of the aboveQ Consider the join of a relation R with a relation S. If R has m tuples and S has n tuples, then the maximum and minimum sizes of the join respectively are: (Gate- 1999) (1 Marks) (A) m+n and 0 (B) mn and oO (C) m+n and m-n (D) mn and m+n KGYTBreakTheta Conditional Join * The theta join/ Conditional join operation is a variant of the natural-join operation that allows us to combine a selection and a Cartesian product into a single operation. + The theta join operation r Py s is defined as follows: y hy s = ay(r x s) KGYTQ Suppose database table T,(P, R) currently has tuples {(10, 5), (15, 8), (25, 6)} and table T,(A, C) currently has {(10, 6), (25, 3), (10, 5)}. Consider the following three relational algebra queries RA,, RA, and RA,: (NET-AUG-2016) RA,: T; Dot 41.p272.4 Tz where De is natural join symbol RA,: T, =D4 519-12.4 T2 where =< is left outer join symbol RAS Ty Pd ty petza andtir=T2c T2 The number of tuples in the resulting table of RA,, RA, and RA, are given by: (a) 2, 4, 2 respectively (b) 2, 3, 2 respectively (c) 3, 3, 1 respectively (d) 3, 4, 1 respectively KGYTQ Consider the following relations A, B and C: B A ID | Name Age| 2 60. ‘Arun 15 | Shreya 24 ‘99 | Rohit ii [ID | Name | Age c 15 [Shreya | 24] [1D | Phone | Area| 25 | Hari | 40 10 | 2200 | 02 [9s | Rohit [ 20{ [99[ 2100 | a1 | 99 | Rohit | 11 How many tuples does the result of the following relational algebra expression contain? Assume that the schema of AUB is the same as that of A. (Gate-2007) (2 Marks) (AUB) 4 gigs aovcideas© a)7 b)4 5 ao KGYTQ Let R1 (A, B, C) and R2 (D, E) be two relation schema, where the primary keys are shown underlined, and let C be a foreign key in R1 referring to R2. Suppose there is no violation of the above referential integrity constraint in the corresponding relation instances r1 and r2. Which one of the following relational algebra expressions would necessarily produce an empty relation? (Gate-2004) (1 Marks) a) No(r2)-M¢(r) b) Ne(ry)-Np(r2) €) No(ts>4ceo%a) KGYTBreakOuter join Operations The outer-join operation is an extension of the join operation to deal with missing information. The outer join operation works ina manner similar to the natural join operation, but Preserves those tuples that would be lost in a join by creating tuples in the result containing null values. We can use the outer-join operation to avoid this loss of information. There are actually three forms of the operation: left outer join, denoted >«;; right outer join, denoted p¢;; and full outer join, denoted KGYTLeft Outer Join * The left outer join (3«)takes all tuples in the left relation that did not match with any tuple in the right relation, pads the tuples with null values for all other attributes from the right relation, and adds them to the result of the natural join. wlrole|> u|n|\O\a N|<|0 DID |v ao KGYTQ Consider the relations r(A, B) and s(B, C), where s.B is a primary key and r.B is a foreign key referencing s.B. Consider the query Q:r 4 (0 gs (s)) Let LOJ denote the natural left outer-join operation. Assume that r and s contain no null values. Which of the following is NOT equivalent to Q? (Gate-2018) (2 Marks) a) 6 ges(t 04 5) b) 6 ges(r LON) €) F LOI (0 gs (5) d) 0 g.s(r) LOJ s KGYTight Outer J * The left outer join (»<)takes all tuples in the left relation that did not match with any tuple in the right relation, pads the tuples with null values for all other attributes from the right relation, and adds them to the result of the natural join. wlole|> u|p|\O\o N|<|>0 DIO |v ao KGYTFull Outer Join + The full outer join(><) does both the left and right outer join operations, padding tuples from the left relation that did not match any from the right relation, as well as tuples from the right relation that did not match any from the left relation, and adding them to the result of the join. wlole|> DID |v ao u|2|O\a N|<|0 KGYTQ Consider two relations R,(A, B) with the tuples (1, 5), (3, 7) and R,(A, C) = (1, 7), (4, 9). Assume that R(A, B, C) is the full natural outer join of R, and R,. Consider the following tuples of the form (A, B, C) a=(1,5, null), , 7, null), g=(4, null, 9). Which one of the following statements is correct? (Gate-2015) (1 Marks) (A) R contains a, b, e, f, g but not c,d (B) R contains a, b, c, d, e, f, g (C) R contains e, f, g but not a, b (D) R contains e but not f, g KGYTQ Consider the following 2 tables R R, ° > wolfe fo n[xleln]o The number of rows where null entries are present in the table R, —P>
2)(Q * R)) KGYT P Qa R [Xy¥]Z] PX T¥]T] [YTV ‘X1] ¥1[ Zi X2]¥1{ 2 ‘Y1{ Vi X1/ YI] Z2 XI] Y27 5 ‘Y¥3 | V2 ‘X27 ¥2 | Z2 XI] YI] 6 ‘¥2 | V3 ‘X27 Y¥4]Z4 X3/Y3/ 1 ‘Y2] V2Q With respect to relational algebra, which of the following operations are included from mathematical set theory? (NET-JUNE-2019) 1) Join 2) Intersection 3) Cartesian Product 4) Project a) land4 b)2and3 c)3and4 d) 2and 4 KGYTQ Consider the relational schema given below, where eld of the relation dependent is a foreign key referring to empid of the relation employee. Assume that every employee has at least one associated dependent in the dependent relation. (Gate-2014) (2 Marks) employee (empid, empName, empAge) dependent(depld, eld, depName, depAge) Consider the following relational algebra query: Nempld(employee) — Nempld(employeeempigzein)(empagesdepage)FePendent) The above query evaluates to the set of empids of employees whose age is greater than that of (A) some dependent. (B) all dependents. (C) some of ar aE = all of aie KeiQ Consider a join (relation algebra) between relations r(R)and s(S) using the nested loop method. There are 3 buffers each of size equal to disk block size, out of which one buffer is reserved for intermediate results. Assuming size(r(R)) < size(s(S)), the join will have fewer number of disk block accesses if (Gate-2014) (2 Marks) a) relation r(R) is in the outer loop. b) relation s(S) is in the outer loop. ¢) join selection factor between r(R) and s(S) is more than 0.5. d) join selection factor between r(R) and s(S) is less than 0.5. KGYTQ Consider a relational table r with sufficient number of records, having attributes A,, A,..., A, and let 1< p
Select A,, A,, (Column name) () = fromr,,r,,..., (Relation/table name) oy — Where P; (Condition) KGYTPP Select Ay, Ayn A, * — (Column name) FOO Fy Fae on (Relation/table name) “> AWthereP;—— (Condition) 1. Itis to be noted only select and from are mandatory clauses, and if not required then it is not essential to write where. If the where clause is omitted, the predicate P is true. > 2.” SQL in general is not case sensitive i.e. it doesn’t matter whether we write query in upper or lower case. 3. In the formal, mathematical definition of the relational model, a relation is a set. Thus, duplicate tuples would never appear in relations. 4. In practice, duplicate elimination is time-consuming. Therefore, SQL allows duplicates in relations as well as in the results of ressions. In those cases where we want to force the elimination of duplicates, we insert the keyword@istinct after select, will discuss in detail later. 5. SQL allows us to use the ieeyoroi ae specify explicitly that duplicates are not removed, Since duplicate retention is the default, we shall not use all in our examples OO KGYTSelect Clause + The function of Select clause in SQL is more or less same as that of ‘TI’ projection in the relational algebra. It is used to pick the column required in result of the query out of all the columns in relation/table.. (Vertical filtering) + Select Ay, Ayros Ay (Column name) The order in which columns are represented in the select clause, will be same the column will appear in the relation. + Itis to be noted that in Relational Algebra ‘TI’ projection is not mandatory and should be used only when we require less than all the column available in the table, but is SQL even if we need all the column we must use Select, the argument is it makes SQL query more readable. KGYT* But to make things easy we can use ‘*’ to specify that we need all columns Select * + The select clause may also contain arithmetic expressions involving the operators +, -, / and * operating on constants or attributes of tuples. however, that it does not result in any change to the relation/table. KGYTSdub * poor bench,Selec} — Loan rp» ennosh pom dearShit — dichin Comk narra prow ole positenSted acekne , belare AleL prom AllouwkQGelect operation in SQL is equivalent to (Gate-2015) (1 Marks}— 7 . a a 5 (c) projection operation in relational algebra, except that select in SQL retains dupficates—¢~ —~ » (D) the projection operation in relational algebra—4 KGYTBreak. SQL includes: Select Clause . Where clause in SQL is same ational algebra where we specify the conditions/Predicate (horizontal nee . Where clause can have expressions involving the comparison operators <, Ld a SQL allows us to use the comparison operators to compare strings and arithmetic. expressions. - SQL allows the use of the logical connectives and, or, and not in the where clause. f comparison operator to simplify where clauses that specify that a value be less than or equal to some value and greater than or equal to some other value. . Similarly, we can use the not between Zomparison operator. KGYTSclet Allok vw from Acoust Lhe bd
21; —— °° 7 (b) Select Name from people where Height > 180; —— (c) Select Name from people where (Age > 21) or (Height > 180); If the SQL queries (a) and (b) above, return 10 rows and 7 rows in the result set respectively, then what is one possible number.gf rows returned by the SQL query ? (NET-DEC-2015) i OK (49 ak Asie! \s g++ KGYTWritsQ Consider a database table T containing two columns X and Y each of type integer. After the creation of the table, one record (X=1, Y=1) is inserted in the table. Let MX and My denote the respective maximum values of X and Y among all records in the table at any point in time’ Using MX and MY, new records are inserted in the table 128 times with X and Y-values being MX+1,_ 2*MY+1 respectively. It may be noted that each time after the insertion, values of MX and MY change. What will be the output of the following SQL query after the steps mentioned above are carried out? (Gate-2011) (2 Marks) SELECT.Y FROM T WHERE X=7; wee (B) 255-?! x [7 \ \ as 2), | (e129 5) 7 4 fos Nx hr Ss | 3l ' ¢ | @ Nes 7 fa i | we 7 (D) 257 Re May ee Y= ay)BreakSet Operation 1. The SQL operations union, intersect, and except/minus operate on relations and corresponds to the mathematical set-theory operations U, 9 and — respectively. Y 2. The union operation automatically-eliminates duplicates, unlike the select clause, If we want to retain all duplicates, we must write union all in place of union. 3. The intersect operation automatically eliminates duplicates, If we wantte-retain-all duplicates, we must write intersect all in place of intersect. 4. \f we want to retain duplicates, we must write except all in place of except. KGYTSkid conhvomeQ Consider the following ORACLE relations: One (x, y) = {<2, 5>, <1, 6>, <1, 6>, <1, 6>, <4, 8>, <4, 8>} Two (x, y) = {<2, 55>, <1, 1>, <4, 4>, <1, 6>, <4, 8>, <4, 8>, <9, 9>, <1, 6>} Consider the following two SQL queries SQ1 and SQ2: ‘SQ1: SELECT * FROM One EXCEPT (SELECT * FROM Two); $Q2: SELECT * FROM One EXCEPT ALL (SELECT * FROM Two); For each of the SQL queries, what is the cardinality (number of rows) of the result obtained when applied to the instances above? (NET-AUG-2016) (a) 2 and 1 respectively (b) 1 and 2 respectively (c) 2 and 2 respectively (d) 1 and 1 respectively KGYTBreakQueries on Multiple Relations So far, our example queries were on a single relation. Queries often need to access information from multiple relations. The from clause by itself defines a Cartesian product of the relations listed in the clause. Cartesian product of two relations, which concatenates each tuple of the first relation with every tuple of the second KGYTSince the same attribute name may appear in both r, and r ,, we prefix the name of the relation from which the attribute originally came, before the attribute name. For those attributes that appear in only one of the two schemas, we shall usually drop the relation-name prefix. This simplification does not lead to any ambiguity. Cartesian Product is commutative in nature KGYTR,* Re KGYTConk rome, — bal At omt Nog ohn eg EpoSdet tod na ne drone brand, auek, derston Ae — ards branes Beck bnoare Gh Med a ne = eapesia Abe ad bred. = Deals?QGiven two relations R,(A, B) and R,(C, D), the result of following query Select distinct A, B from R,, Rp is guaranteed to be same as R, provided one of the following conditions is satisfied. (NET-NOV-2017) (a) R, has no duplicates and R, is empty. (b) R, has no duplicates and R, is non - empty. (c) Both R, and R, have no duplicates. (d) R, has no duplicates and R, is non - empty KGYTQ Consider the set of relations shown below and the SQL query that follows (Gate-2003) (2 Marks) ‘Students: (Roll_number, Name, Date_of_birth) Ro £ ee. os ‘Courses: (Course number, Course_name, Instructor) A et Grades: (Roll_number, Course_number, Grade) Select distinct Name ph ee from Students, Courses, Grades bh where (Students. Roll-nuniber = Grates Rell_humber) ‘and Courses.nstructor = Korth f —4-—_—_—_] ‘and Grades grade: ‘Which of the following sets is computed by the above-query? cabanas === iain a ee aon yaaa coe una ndan e ist k ba B AGeNimes of students who have got an A grade in at least ane af the courses taught by Korth (0) None of the above—\,Q Given relations r(w, x) and s(y, 2), the result of ‘SELECT DISTINCT w, x FROM r, s is guaranteed to be same as r, provided (GATE-2003) (1 Marks) (a) r has no duplicates and s is non-empty (B) r ands have no duplicates (C) s has no duplicates and ris non-empty (D) rand s have the same number of tuples KGYTBreakNatural Join . To make the life of an SQL programmer easier for this common case, SQL supports an operation called the natural join. . The natural join operation like cartesian product operates on two relations and produces a relation as the result. . Natural join considers only those pairs of tuples with the same value on those attributes that appear in the schemas of both relations. KGYT1. Notice that we do not repeat those attributes that appear in the schemas of both relations; rather they appear only once. 2. Notice also the order in which the attributes are listed: first the attributes common to the schemas of both relations, second those attributes unique to the schema of the first relation, and finally, those attributes unique to the schema of the second relation. 3. commutative in nature KGYTA from clause in an SQL query can have multiple relations combined using natural join, as shown here: select A,, A,,...,A, from r, natural join r, natural join .. . natural join r,, where P; KGYTic x R,*R, R,B | R,B R, 0 R, KGYTQ Database table by name Loan_Records is given below. (Gate - 2011) (2 Marks) Borrower: Bank Manager| Loan Amount Ramesh Sunderajan 1000.00 Suresh Ramgopal 5000.00 Mahesh Sunderajan 7000.00 ‘What is the output of the following SQL query? ‘SELECT Count(*) FROM ( (SELECT Borrower, Bank_Manager FROM Loan_Records) AS S NATURAL JOIN (SELECT Bank_Manager, Loan_Amount FROM Loan_Records) AST); (A)3 (B)9 (c)5 (06 KGYTQ Consider the following relation schema pertaining to a students database: Student (rolino, name, address) Enroll (rollno, courseno, coursename) where the primary keys are shown underlined. The number of tuples in the Student and Enroll tables are 120 and 8 respectively. What are the maximum and minimum number of tuples that can be present in (Student * Enroll), where ‘*’ denotes natural join? (Gate-2004) (2 Marks) (a) 8,8 (B) 120,8 (c) 960, 8 (D) 960, 120 KGYTQ Consider the following SQL query (GATE-2003)(1 Marks) (A) Io, (xx select distinct a4, a3)... Aq ee FFOM Ey Fyyeneeey Fun (B) where P For an arbitrary predicate P, this query is equivalentto (C) Ml o,(RURU which of the following relational algebra expressions ? i 8p (0) 2 %linen KGYT Tl 9, (mbarpd.. xi) Din) ++ Ulm) siti)BreakJo’ inner 1. Join or inner join is a operation which works same as cartesian product but when it is used with “using” keyword it provides additional functionality. 2. Join with using — Provides ability to explicitly chose columns which must be used by join for comparison and removal of redundant tuples, i.e. if there are more than one column which are common between two table but we do not want each of them to be considered, then we can use join with using. KGYT1. So join is a form of the natural join construct that allows you to specify exactly which columns should be equated. + R,(A,B, C) + R,(B, C, D) 2. Consider the operation R, join R, using ( B). The operation is similar to R, natural join R,, except that a pair of tuples t, from R, and t, from R, match if t,. B = t,. B; even if R, and Ry both have an attribute named C, it is not required that t,. C= KGYTQIn RDBMS, which type of Join returns all rows that satisfy the join condition? (NET-JULY-2018) (a) Inner Join (b) Outer Join (c) Semi Join (d) Anti Join KGYTOuter Jo The join operations we studied earlier that do not preserve nonmatched tuples are called inner join operations, to distinguish them from the outer-join operations. ‘The problem with natural join or join is only those values that appears in both relations will manage to reach final table, but if some value is explicitly in table one or in second table then that information will be lost, and that will be loss of information. ‘The outer join operation works ina manner similar to the join operations we have already studied, but preserve those tuples that would be lost in a join, by creating tuples in the result containing null values. KGYT+ There are in fact three forms of outer join: 1. The left outer join (left join) preserves tuples only in the relation named before (to the left of) the left outer join operation. 2. The right outer join (right join) preserves tuples only in the relation named after (to the right of) the right ‘outer join operation. 3. The full outer join preserves tuples in both relations. KGYTRimeR, Ry DER, A [R,B[R,B] C Ry aR, KGYTQConsider the following two tables and four queries in SQL. (GATE - 2018) (1 Marks) Book (isbn, bname) ec) | Query 1: SELECT B.isbn, S.copies Query 2: SELECT B.isbn, S.copies Stock (isbn, copies) FROM Book B INNER JOIN Stock S FROM Book B LEFT OUTER JOIN Stock S ON Biisbn = S.isbn; ON B.isbn = S.isbn; ‘Query 3: SELECT B.isbn, S.copies Query 4: SELECT B.isbn, S.copies FROM Book 8 RIGHT OUTER JOIN Stock S FROM Book 8 FULL OUTER JOIN Stock S ‘Which one of the queries above is certain to have an output that is a superset of the outputs of the other three queries? (a) Query 1 (b) Query 2 (c) Query 3 (d) Query 4 KGYTQ Suppose ORACLE relation R(A, B) currently has tuples {(1, 2), (1, 3), (3, 4)} and relation S(B, C) currently has {(2, 5), (4, 6), (7, 8)}- Consider the following two SQL queries SQ1 and SQ2 : SQ4: Select * From R Full Join $ On R.! =S.B; $Q2: Select * From R Inner Join S On R.B = 5.8; The numbers of tuples in the result of the SQL query SQ1 and the SQL query SQ2 are given by: (NET-DEC-2015) (a) 2 and 6 respectively (b) 6 and 2 respectively (c) 2 and 4 respectively (d) 4 and 2 respectively KGYTBreakn/rename . SQL aliases are used to give a table, or a column ina table, a temporary name. Just create a new copy but do not change anything in the data base. . Aliases are often used to make column names more readable. . Ituses the as clause, taking the form: old-name as new-name. The as clause can appear in both the select and from clauses. . An alias only exists for the duration of the query. KGYTQ The SAL expression Select distinct T.branch_name from branch T, branch $ where T.assets > S.assets and S.branch_city= Mumbai” finds the names of (NET-SEP-2013) (A) All branches that have greater assets than some branch located in Mumbai. (B) All branches that have greater assets than all branches in Mumbai. (C) The branch that has greatest asset in Mumbai. (D) Any branch that has greater assets than any branch it Mumbai. KGYTAggregate Functions Aggregate functions are functions that take a collection (a set or multiset) of values as input and return a single value. SQL offers five built-in aggregate functions: + Average: avg + Minimum: min * Maximum: max * Total: sum * Count: count KGYT. The input to sum and avg must be a collection of numbers, but the other operators can operate on collections of nonnumeric data types, such as strings, as well. . We use the aggregate function count frequently to count the number of tuples in a relation. The notation for this function in SQL is count (*). . Count is the only aggregate function which can work with null, all other aggregate functions simply ignore null. KGYTQ Consider a table along with two query? Select avg (balance) from account Account_no balance _| Branch_name Abc123 100 N_delhi Pgr123 500 S_mumbai Wyz123 null S_delhi Select sum(balance)/count(balance) from account KGYTQinsal, is an Aggregate function. (NET-NOV-2017) (a) SELECT (b) CREATE (c) AVG (a) MODIFY KGYTBreakOrdering the Display of Tuples * SQL offers the user some control over the order in which tuples in a relation are displayed. The order by clause causes the tuples in the result of a query to appear in sorted order. KGYTString Operations . SQL specifies strings by enclosing them in single quotes, for example, ‘Computer’. . The SQL standard specifies that the equality operation on strings is case sensitive; as a result the expression ‘Computer’ = ‘computer’ evaluates to false. . However, some database systems, such as MySQL and SQL Server, do not distinguish uppercase from lowercase when matching strings; as a result, would evaluate to true on these databases. . This default behavior can, however, be changed, either at the database level or at the level of specific attributes. KGYT1. SQL also permits a variety of functions on character strings, such as concatenating, extracting substrings, finding the length of strings, converting strings to uppercase and lowercase, removing spaces at the end of the string and so on. 2. There are variations on the exact set of string functions supported by different database systems. 3. Asingle quote character that is part of a string can be specified by using two single quote characters; for example, the string It’s right can be specified by Its right. KGYT* Pattern matching can be performed on strings, using the operator like. We describe patterns by using two special characters: * Percent (%): The % character matches any substring. * Underscore (_): The _ character matches any character. KGYT* '%Comp%’ matches any string containing “Comp” as a substring, for example, ‘Intro to Computer Science’, and Computational Biology’. ’ matches any string of exactly three characters. ” matches any string of at least three characters. KGYT“ . For patterns to include the special pattern characters (that is, % and_), SQL allows the specification of an escape character. . The escape character is used immediately before a special pattern character to indicate that the special pattern character is to be treated like a normal character. . We define the escape character for a like comparison using the escape keyword. To illustrate, consider the following patterns, which use a backslash (\) as the escape character: . like ‘ab\%cd%’ escape ’\’ matches all strings beginning with “ab%cd”. like ‘ab\\cd%’ escape ‘\’ matches all strings beginning with “ab\cd”. KGYT1. SQL allows us to search for mismatches instead of matches by using the not like comparison operator. Some databases provide variants of the like operation which do not distinguish lower and upper case. 2. SQL:1999 also offers a similar to operation, which provides more powerful pattern matching than the like operation; the syntax for specifying patterns is similar to that used in Unix regular expressions. KGYTQ Consider a “CUSTOMERS” database table having a column “CITY” filled with all the names of Indian cities (in capital letters). The SQL statement that finds all cities that have “GAR” somewhere in its name, is: (NET-DEC-2015) (a) Select * from customers where city = ‘%GAR%’ (b) Select * from customers where city = ‘SGARS’ (c) Select * from customers where city like ‘%GAR%’ (d) Select * from customers where city as ‘%GAR’ KGYTBreakGroup by clause 1. There are circumstances where we would like to work on a set of tuples in a relation rather than working on the whole table as one unit. 2. The attribute or attributes given in the group by clause are used to form groups. Tuples with the same value on all attributes in the group by clause are placed in one group. KGYTQA relational database contains two tables Student and Performance as shown below: (GATE - 2019) (2 Marks) The primary key of the Student table is Roll_no. For the Performance table, the columns Roll_no. and Subject_code together from the primary key. Consider the SQL query given below: Student Performance ‘SELECT S.Student_name, sum (P.Marks) ‘Roll_no. | Student_name Roll_no. | Subject_code | Marks FROM Student S, Performance P ¥ Amit T A % WHERE P.Marks > 84 z Paya T B B GROUP BY S.Student_name; 3 Visit T c w The number of rows returned by the above SQL query is z Reka z x 5 5 ‘Smita Z c ba 7 c ©Q (NET-DEC-2018) Consider the following tables (relations) Students Name 18CS101_ | Ramesh 1scsi02_ | Mukesh 18¢s103_| Ramesh Performance Course Marks, iscsi01__| DBMS ‘60 18Cs101 | Compiler Design 65 ascsi02 | DEMS so iscsi03._ | DBMS 85 18CS102_| Compiler Design 75 18CS103 _| Operating System 70 ajo bjt KGYT Primary keys in the tables are shown using underline. Now, consider the following query : SELECT $ Name, Sum (P-Marks) FROM Students S, Performance P WHERE S Roll-No = P-Roll-No GROUP BY SName ‘The number of rows returned by above query is 2 )3Q Consider a database that has the relation schema EMP (Empld, EmpName, and DeptName). An instance of the schema EMP and a SQL query on it are given below. (GATE-2018) (2 Marks) The output of executing the SQL query is SELECT AVOTEC Ram) FROM EC ‘WHERE (DeptName,NurIN (SELECT DeptName,COUNT(Empla) AS (DeptName, Nun) FROMEMP. GROUP BY DeptName) ||| emf fof) | of 5 Bagge a aae aa3e eeleaaeeresl KGYTQ Consider the following ORACLE relations: R(A,B, C) ={<1, 2, 3>, <1, 2, 0>, <1, 3, 1>, <6, 2, 3>, <1, 4, 2>, <3, 1, 4>} (B,C, D) = {<2, 3, 7>, <1, 4, 5>, <1, 2, 3>, <2, 3, 4>, <3, 1, 4>}. Consider the following two SQL queries SQ1 and SQ2 : SQ : SELECT R-B, AVG (5B) FROMR,S WHERE R-A = GROUP BY R°B; CAND S-D<7 ‘$Q2 : SELECT DISTINCT S-B, MIN (S-C) FROM S GROUP BY S:B HAVING COUNT (DISTINCT $-D) > 1; If Mis the number of tuples returned by SQ1 and Nis the number of tuples returned by SQ2 then (NET-JULY-2016) (a)M (b) (om (ym KGYTQ Consider the following relations (Gate-2015) (2 Marks) SELECT S. Student_Name, sum (P.Marks) FROM Student S, Performance P WHERE S. Roll_No = PRoll_No GROUP BY S.Student_Name The number of rows that will be returned by the SQL query is KGYT ‘Students Student Name Raj Rohit Raj Performance Course Marks Math 80 English 70 Math 75 English 80 Physics 6s vealed MathQ The STUDENT information in a university stored in the relation STUDENT (Name, SEX, Marks, DEPT_Name) Consider the following SQL Query SELECT DEPT_Name from STUDENT where SEX ='M’ group by DEPT_Name having avg (Marks) > SELECT avg (Marks) from STUDENT. It Returns the Name of the Department for which: (NET-JUNE-2015) (a) The Average marks of Male students is more than the average marks of students in the same Department (b) The average marks of male students is more than the average marks of students in the University (c) The average marks of students is more than the average marks of male students in the university (d) The average marks of Male students is more than the average marks of male students in the university KGYTQ Consider the following database table named water_schemes : water — schemes The number of tuples returned by the following SQL query is saietaatno| Wistricisieean| Gapaey . GATE(2015 SET 1) T hiner 20 with total(name, capacity) as i Eakaser By select district_name, sum(capacity) 2 pesnes 10 from water_schemes 3 Bikaner 20 group by district_name 1 Chua 10 with total_avg(capacity) as 2 Churu 20 select avg(capacity) 1 Dungargarh 10 from total select name from total, total_avg where total.capacity 2 total_avg.capacityQThe employee information in a company is stored in the relation Employee (name, sex, salary, deptName) Consider the following SQL query select deptName from Employee where sex = 'M' group by deptName having avg (salary) > (select avg (salary) from Employee) It returns the names of the department in which (Gate-2004) (2 Marks) (NET-JUNE-2013) (A) the average salary is more than the average salary in the company (B) the average salary of male employees is more than the average salary of all male employees in the company (C) the average salary of male employees is more than the average salary of employees in the same department (D) the average salary of male employees is more than the average salary in the company KGYTBreakThe SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The clause is used for defining a temporary relation such that the output of this temporary relation is available and is used by the query that is associated with the WITH clause. WITH clause is not supported by all database system. KGYT. When an SQL query uses grouping, it is important to ensure that the only attributes that appear in the select statement without being aggregated are those that are present in the group by clause. . In other words, any attribute that is not present in the group by clause must appear only inside an aggregate function if it appears in the select clause, otherwise the query is treated as erroneous. . The Having Clause - At times, it is useful to state a condition that applies to groups rather than to tuples. . To express such a query, we use the having clause of SQL. SQL applies predicates in the having clause after groups have been formed. . Any attribute that is present in the having clause without being aggregated must appear in the group by clause, otherwise the query is treated as erroneous. KGYT+ The meaning of a query containing aggregation, group by, or having clauses is defined by the following sequence of operations: 1. 2. ‘As was the case for queries without aggregation, the from clause is first evaluated to get a relation. If a where clause is present, the predicate in the where clause is applied on the result relation of the from clause. . Tuples satisfying the where predicate are then placed into groups by the group by clause if it is present. If the group by clause is absent, the entire set of tuples satisfying the where predicate is treated as being in one group. . The having clause, if it is present, is applied to each group; the groups that do not satisfy the having clause predicate are removed. . The select clause uses the remaining groups to generate tuples of the result of the query, applying the aggregate functions to get a single result tuple for each group. KGYTQWhich of the following statements are TRUE about an SQL query? (Gate-2012) (2 Marks) P: An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause Q: An SQL query can contain a HAVING clause only if it has a GROUP BY clause R : All attributes used in the GROUP BY clause must appear in the SELECT clause S: Not all attributes used in the GROUP BY clause need to appear in the SELECT clause (a) P and R (B) Pands (C)QandR (D) QandsdivisionQ Division operation is ideally suited to handle queries of the type: (NET-DEC-2014) (A) customers who have no account in any of the branches in Delhi. (8) customers who have an account at all branches in Delhi. (C) customers who have an account in at least one branch in Delhi. (D) customers who have only joint account in any one branch in Delhi KGYTNested Subqueries A subquery is a select-from- where expression that is nested within another query. A common use of sub- queries is to perform + Tests for set membership * make set comparisons + determine set cardinality, by nesting subqueries in the where clause. SQL allows testing tuples for membership in a rel ‘The in connective tests for set membership, where the set is a collection of values produced by a select clause. The not in connective tests for the absence of set membership. KGYTQ Consider the following relations A, B, C. How many tuples does the result of the following relational algebra expression contain? Assume that the schema of A U B is the same as that of A. (Gate-2012) (2 Marks) RB = ID | Name | Age oc a eee ~ 15 | Shreya | 24 ID | Phone | Areal aims Hiieeg ee | a 25 | Hari | 40 10 | 2200 | 02 loo | Rohit 1 98 Rohit 20 99 2100 o1 99 Rohit ai SELECT A.id FROM A WHERE A.age > ALL (SELECT B.age FROM B WHERE B. name = “arun") wes ()3 (co (04Q Consider the following relation: ‘Works (emp_name, company_name, salary) Here, emp_name is primary key. Consider the following SQL query Select emp_name From works T where salary > (select avg (salary) from works S where T.company_name= S.company_name) The above query is for following : (NET-JAN-2017) (a) Find the highest paid employee who earns more than the average salary of all employees of his company. (b) Find the highest paid employee who earns more than the average salary of all the employees of all the companies. (c) Find all employees who earn more than the average salary of all employees of all the companies. (d) Find all employees who earn more than the average salary of all employees of their company. KGYTQ.The relation book (title, price) contains the titles and prices of different books. Assuming that no two books have the same price, what does the following SQL query list? (Gate - 2005) (2 Marks) select title from book as B where (select count(*) from book as T where T.price > B.price) <5 (A) Titles of the four most expensive books (B) Title of the fifth most inexpensive book (C) Title of the fifth most expensive book (0) Titles of the five most expensive books‘Q Consider a relation book (title, price) which contains the titles and prices of different books. Assuming that no two books have the same price, what does the following SQL query list? (NET-JULY-2018) Select title from book as B where (select count (*) from book as T where T.price > 8.price) < 7 (2) Titles of the six most expensive books. (b) Title of the sixth most expensive books. (¢) Titles of the seven most expensive books. (d) Title of the seventh most expensive books. KGYTQ Consider the following relation (GATE-2015) (2 Marks) Cinema (theater, address, capacity) Which of the following options will be needed at the end of the SQL query SELECT P1.address FROM Cinema P1 Such that it always finds the addresses of theaters with maximum capacity? (A) WHERE P1. Capacity> = All (select P2. Capacity from Cinema P2) (B) WHERE P1. Capacity> = Any (select P2. Capacity from Cinema P2) (C) WHERE P1. Capacity> Alll (select max(P2. Capacity) from Cinema P2) (D) WHERE P1. Capacity> Any (select max (P2. Capacity) from Cinema P2) KGYTQ Consider the following database table named top_scorer. (Gate-2017) (2 Marks) SELECT ta.player FROM top_scorer AS ta WHERE ta.goals > ALL ( SELECT tb.goals FROM top_scorer AS tb WHERE tb.country = ‘Spain’ JAND ta.goals > ANY (SELECT tc.goals FROM top_scorer AS tc WHERE tc.country = 'Germany') The number of tuples returned by the above SQL query is top_scorer ae seer [a Klose | Germany | 16 Ronaldo | Brazil |__15 GMiller_| Germany | _14 Fontaine | France | 13. Pele Brazil | 12 Klinsmann | Germany| —11 Kocsis | Hungary [11 Baristwta_| Argentina | 10 Cubillas [Peru 10. Lato | Poland | 10 Lineker_| England |" 10 T Moller_| Germany | 10. Rahn | Germany | 10Q Consider the query : SELECT student_name FROM student_data WHERE rolino (SELECT rolino FROM student_marks WHERE SEM1_MARK=SEM2_MARK); Which of the following is true? (NET-JUNE-2008) (A) It gives the name of the student whose marks in semester 1 and semester 2 are same. (B) It gives all the names and roll nos of those students whose marks in semester 1 and semester 2 are same. (C) It gives the names of all the students whose marks in semester 1 and semester 2 are same. (D) It gives roll numbers of all students whose marks in semester 1 and semester 2 are same. KGYTQConsider the query : SELECT student_name FROM students WHERE class_name = (SELECT class_name FROM students WHERE math_marks=100); what will be the output ? (NET-DEC-2007) (A) the list of names of students with 100 marks in mathematics (B) the names of all students of all classes in which at least one student has 100 marks in mathematics (C) the names of all students in all classes having 100 marks in mathematics (D) the names and class of all students whose marks in mathematics is 100 KGYTQ Given the following schema (GATE-2014) (2 Marks) ‘employees(emp-id, first-name, last-name, hire-date, dept-id, salary) departments(dept-id, dept-name, manager-id, location-id) You want to display the last names and hire dates of all latest hires in their respective departments in the location ID 1700. You issue the following query: SELECT last-name, hire-date FROM employees WHERE (dept-id, hire-date) IN (SELECT dept-id, MAX(hire-date) FROM employees JOIN departments USING(dept-id) WHERE location-id = 1700 GROUP BY dept-id); ‘What is the outcome? (A) It executes but does not give the correct result, (8) it executes and gives the correct result. (C) It generates an error because of pairwise comparison. (0) It generates an error because the GROUP BY clause cannot be used with table joins in a subquery KGYTQSQL allows tuples in relations, and correspondingly defines the multiplicity of tuples in the result of joins. Which ‘one of the following queries always gives the same answer as the nested query shown below (GATE-2014) (1 Marks) select * from R where a in (select S.a from S) (A) select R.* from R, S where R.a: a (B) select distinct R.* from R,S where R.a=S.a (C) select R.* from R,(select distinct a from S) as $1 where R. (D) select R.* from R,S where R.a=S.a and is unique RTest for Empty Relations Select branch_name from branch asa ‘Where assets <= 1,00,000 and exists(Select * from Branch as b where branch_city = ‘Gwalior’ and a.branch_name = b.branch_name) * SQL includes a feature for testing whether a subquery has any tuples in its result. The exists construct returns the value true if, the argument subquery is nonempty. + The above query also illustrates a feature of SQL where a correlation name from an outer query, can be used in a subquery in the where clause. A subquery that uses a correlation name from an outer query is called a correlated subquery. KGYTQ Consider the following relational schema (Gate-2014) (2 Marks) ‘employee(emaid, empName, empDept) customer(custid, custName, salesRepld, rating) salesRepid is a foreign key referring to empid of the employee relation. Assume that each employee makes a sale to at least one customer. What does the following query return? SELECT empName FROM employee E WHERE NOT EXISTS (SELECT custid FROM customer C WHERE C.salesRepid = E.Empld AND C.rating = GOOD’); {a} Names of all the employees with at least one oftheir customers having 2 ‘GOOD’ rating. {8) Names ofall the employees with at most one oftheir customers having a ‘GOOD’ rating. (C) Names of all the employees with none of their customers having a ‘GOOD’ rating. {0) Names of all the employees with all their customers having 3 ‘GOOD’ rating. KGYTPassenger (pid, pname, age) Reservation (pid, cass tid) ‘What pids are returned by the following SAL query for the above instance of the tables? (Gate-2010) (2 Marks) SUECT pid FROM Reservation WHERE class ‘AC’ AND. EXISTS (SELECT * FROM Passenger WHERE age > 65 AND Passenger. pid = Reservation pid) wo (12 13 Reservation Passenger 5 = pid class tid pid pname | age 0 sachin | 65 y me 20) 1 Rahul | 66 z i Baan. z cue | 2 sc 8201 3 anil | 69 3 ae _| 8208. 1 sc #204 3 ac | 8202 KGYT (1,5SELECT E.1D FROM Employee WHERE EXISTS (SELECT E2.salary FROM Employee E2 WHERE E2.DeptName = 'CS’ AND E.salary > E2.salary) (ayo (B)4 (cs KGYT (0) 6 1D__| salary _| DeptName 1 10000 EC 2 40000 EC 3 30000 cs 4 40000 ME 5 50000 ME 6 60000 ME 7 | 70000 csQ Consider the table Student(stuid, name, course, marks). Which one of the following two queries is correct to find the highest marks student in course 5 ? (NET-DEC-2013) Q.1. Select S.stuid From student S Where not exists (select + from student e where e course = 'S’ and e marks > s marks) Q.2. Select s.stu.id From student $ Where s - marks > any (select distinct marks from student § where s - course = 5) (ayaa (8) Q.2 {C) Both Q. 1and Q.2 (D) Neither Q. 1 nor Q. 2 KGYTQConsider the table employee(empid, name, department, salary) and the two queries Q1 ,Q2 below. Assuming that department 5 has more than one employee, and we want to find the employees who get higher salary than anyone in the department 5, which one of the statements is TRUE for any arbitrary employee table? (Gate-2007) (2 Marks) Q1 : Select e.empid From employee e Where not exists (Select * From employee s where s.department = “5” and s.salary >=e.salary) Q2 : Select e.empid From employee e Where e.salary > Any (Select distinct salary From employee s Where s.department = “S") (A) Q1 is the correct query (B) Q2 is the correct query (C) Both Q1 and Q2 produce the same answer. (0) Neither Q1 nor Q2 is the correct query KGYTQWhich construct in SQL is used to test whether a subquery has any tuples in its result? (NET-JUNE-2009) (A) UNIQUE (B) EXISTS (©) GROUP By (D) EXCEPT KGYTnullQin SQL, relations can contain null values, and comparisons with null values are treated as unknown. Suppose all comparisons with a null value are treated as false. Which of the following pairs is not equivalent? (Gate-2000) (2 Marks) (A) x= 5 AND not(not(x = 5) (8) x= 5 AND x> 4 and x < 6, where x is an integer (C)x <5 AND not (x=5) (0) None of the above KGYTQ.35 The relation scheme given below is used to store information about the employees of ‘a company, where empld lis the key and deptd indicates the department to which the employee is assigned. Each employee is assigned to exactly one department. ‘emp( empl name, gender, salary, deptld) Consider the following SOL query select deptld, count(*) from emp where gender = “female” and salary > (select avg(salary) from emp) group by deptid; The above query gives, for each department in the company, the number of female employees whose salary is greater than the average salary of {@) female employees in the department. (0) employees in the department (©) female employees in the company. () employees in the company. (GATE- 2021)
You might also like
CH 6
PDF
No ratings yet
CH 6
55 pages
Chapter 5-Relational Algebra and Calculus (3)
PDF
No ratings yet
Chapter 5-Relational Algebra and Calculus (3)
46 pages
Chapter 01 Relational Algebra
PDF
No ratings yet
Chapter 01 Relational Algebra
92 pages
1368343861.2711ch algebra (1)
PDF
No ratings yet
1368343861.2711ch algebra (1)
34 pages
Lecture 77777
PDF
No ratings yet
Lecture 77777
104 pages
Chapter 5 DBMS
PDF
No ratings yet
Chapter 5 DBMS
22 pages
Chapter 6
PDF
No ratings yet
Chapter 6
26 pages
RelationalAlgebra RelationalCalculus SQL
PDF
No ratings yet
RelationalAlgebra RelationalCalculus SQL
119 pages
5 RelationaAlgebra
PDF
No ratings yet
5 RelationaAlgebra
66 pages
Realtional Model - Relational Algebra
PDF
No ratings yet
Realtional Model - Relational Algebra
67 pages
Relational Algebra
PDF
No ratings yet
Relational Algebra
58 pages
Chapter 5 - Relational Algebra (1)
PDF
No ratings yet
Chapter 5 - Relational Algebra (1)
40 pages
Lec # 15,16 - Relational Algebra
PDF
No ratings yet
Lec # 15,16 - Relational Algebra
35 pages
Relational Algebra
PDF
No ratings yet
Relational Algebra
34 pages
Relational Model: What Are Query Languages?
PDF
No ratings yet
Relational Model: What Are Query Languages?
12 pages
Chapter 5 Relational Algebra v2
PDF
No ratings yet
Chapter 5 Relational Algebra v2
82 pages
Ch5 Relational Algebra 2023
PDF
No ratings yet
Ch5 Relational Algebra 2023
26 pages
DB Ch06
PDF
No ratings yet
DB Ch06
106 pages
DBMS
PDF
No ratings yet
DBMS
5 pages
Relational Algebra
PDF
No ratings yet
Relational Algebra
35 pages
rELATIONAL algebra
PDF
No ratings yet
rELATIONAL algebra
39 pages
Relational Algebra in Dbms
PDF
No ratings yet
Relational Algebra in Dbms
28 pages
The Relational Algebra
PDF
No ratings yet
The Relational Algebra
64 pages
Relational algebra
PDF
No ratings yet
Relational algebra
87 pages
5-M2_ Relational Algebra-23-01-2025
PDF
No ratings yet
5-M2_ Relational Algebra-23-01-2025
19 pages
Chapter 4 - RA
PDF
No ratings yet
Chapter 4 - RA
59 pages
Unit III Relational Algebra and Relational Calculus
PDF
No ratings yet
Unit III Relational Algebra and Relational Calculus
74 pages
Chapter 6
PDF
No ratings yet
Chapter 6
50 pages
Chapter - Seven: The Relational Algebra and Relational Calculus
PDF
No ratings yet
Chapter - Seven: The Relational Algebra and Relational Calculus
25 pages
6ms1102 Ch6 Relational Algebra
PDF
No ratings yet
6ms1102 Ch6 Relational Algebra
15 pages
4 Relational Algebra
PDF
No ratings yet
4 Relational Algebra
87 pages
Unit-2 CH II
PDF
No ratings yet
Unit-2 CH II
58 pages
DBMS Unit-2
PDF
No ratings yet
DBMS Unit-2
16 pages
Relational Algebra
PDF
No ratings yet
Relational Algebra
7 pages
DBMS Mod 2
PDF
No ratings yet
DBMS Mod 2
15 pages
UNIT2
PDF
No ratings yet
UNIT2
79 pages
Difference Between The Following
PDF
No ratings yet
Difference Between The Following
13 pages
CIS3530L06
PDF
No ratings yet
CIS3530L06
39 pages
Relational Algebra Final PPT 08-06-2023
PDF
No ratings yet
Relational Algebra Final PPT 08-06-2023
70 pages
database chapter 6
PDF
No ratings yet
database chapter 6
37 pages
DBMS_Unit-2 relational algebra
PDF
No ratings yet
DBMS_Unit-2 relational algebra
113 pages
Relational Algebra
PDF
No ratings yet
Relational Algebra
67 pages
Relational Algebra
PDF
No ratings yet
Relational Algebra
11 pages
Relational - Algrbra 1
PDF
No ratings yet
Relational - Algrbra 1
57 pages
Uni Ii
PDF
No ratings yet
Uni Ii
26 pages
(Employee) We Combine Several Predicates Into A Larger Predicates by Using The Connectives (And), (Or), (Not)
PDF
No ratings yet
(Employee) We Combine Several Predicates Into A Larger Predicates by Using The Connectives (And), (Or), (Not)
12 pages
DBMS2
PDF
No ratings yet
DBMS2
79 pages
CS2202_RelAlgebra
PDF
No ratings yet
CS2202_RelAlgebra
55 pages
chap 6
PDF
No ratings yet
chap 6
27 pages
5_RelationaAlgebra
PDF
No ratings yet
5_RelationaAlgebra
65 pages
DBMS Series 2
PDF
No ratings yet
DBMS Series 2
26 pages
Relational Algebra
PDF
No ratings yet
Relational Algebra
27 pages
Unit 4 Dbms
PDF
No ratings yet
Unit 4 Dbms
106 pages
Chap6-Relational Algebra
PDF
No ratings yet
Chap6-Relational Algebra
49 pages
Overview of DBM
PDF
No ratings yet
Overview of DBM
188 pages
Chapter 6 Query Languges
PDF
No ratings yet
Chapter 6 Query Languges
26 pages
DBMS - Unit 3 - Notes (Relational Algebra)
PDF
No ratings yet
DBMS - Unit 3 - Notes (Relational Algebra)
45 pages
Unit 3 Query Languages
PDF
No ratings yet
Unit 3 Query Languages
80 pages
DBMS Unit 2 Notes Full
PDF
No ratings yet
DBMS Unit 2 Notes Full
40 pages