SQL is a language used to communicate with databases and manage data. The document discusses SQL statements like DDL, DML, and DCL and how they are used to define, manipulate, and control access to database objects and data. It also covers topics like normalization, constraints, primary and foreign keys.
Download as DOC, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
55 views
SQL Questions
SQL is a language used to communicate with databases and manage data. The document discusses SQL statements like DDL, DML, and DCL and how they are used to define, manipulate, and control access to database objects and data. It also covers topics like normalization, constraints, primary and foreign keys.
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 57
1. What is SQL?
1. Structured Query Language (SQL) is a specialized language for
updating, deleting, and requesting information from databases. 2. SQL is responsible for querying and editing information stored in a certain database management system. 3. !e original "ersion called S#Q$#L (structured Englis! query language) %as designed by an &'( researc! center in 1)*+ and 1)*,. 2. Types of SQL statements !ere are four basic types of SQL statements- .ata definition language (..L) statements .ata manipulation language (.(L) statements .ynamic SQL statements (iscellaneous statements 3. What are the DDL, DML an D!L "ommans? DDL Data Definition Lan#ua#e (..L) statements are used to define t!e database structure or sc!ema. Some e/amples- o 01#2# 3 to create ob4ects in t!e database o 2L#1 3 alters t!e structure of t!e database o .156 3 delete ob4ects from t!e database o 1$702# 3 remo"e all records from a table, including all spaces allocated for t!e records are remo"ed o 05((#7 3 add comments to t!e data dictionary o 1#72(# 3 rename an ob4ect DML Data Manipulation Lan#ua#e (.(L) statements are used for managing data %it!in sc!ema ob4ects. Some e/amples- o S#L#0 3 retrie"e data from t!e a database o &7S#1 3 insert data into a table o $6.2# 3 updates e/isting data %it!in a table o .#L## 3 deletes all records from a table, t!e space for t!e records remain o (#18# 3 $6S#1 operation (insert or update) o 02LL 3 call a 6L9SQL or :a"a subprogram o #;6L2&7 6L27 3 e/plain access pat! to data o L50< 2'L# 3 control concurrency D!L Data !ontrol Lan#ua#e $D!L% statements. Some e&les' o 8127 3 gi"es user=s access pri"ileges to database o 1#>5<# 3 %it!dra% access pri"ileges gi"en %it! t!e 8127 command T!L Transa"tion !ontrol (0L) statements are used to manage t!e c!anges made by .(L statements. &t allo%s statements to be grouped toget!er into logical transactions. o 05((& 3 sa"e %or? done o S2>#65&7 3 identify a point in a transaction to %!ic! you can later roll bac? o 15LL'20< 3 restore database to original since t!e last 05((& o S# 127S20&57 3 0!ange transaction options li?e isolation le"el and %!at rollbac? segment to use (. What is )ormali*ation? 7ormalization is t!e process of efficiently organizing data in a database. !ere are t%o goals of t!e normalization process- eliminating redundant data (for e/ample, storing t!e same data in more t!an one table) and ensuring data dependencies ma?e sense (only storing related data in a table). 'ot! of t!ese are %ort!y goals as t!ey reduce t!e amount of space a database consumes and ensure t!at data is logically stored. +irst )ormal +orm $1)+% @irst normal form (17@) sets t!e "ery basic rules for an organized database- #liminate duplicati"e columns from t!e same table. 0reate separate tables for eac! group of related data and identify eac! ro% %it! a unique column or set of columns (t!e primary ?ey). Se"on )ormal +orm $2)+% Second normal form (27@) furt!er addresses t!e concept of remo"ing duplicati"e data- (eet all t!e requirements of t!e first normal form. 1emo"e subsets of data t!at apply to multiple ro%s of a table and place t!em in separate tables. 0reate relations!ips bet%een t!ese ne% tables and t!eir predecessors t!roug! t!e use of foreign ?eys. Thir )ormal +orm $3)+% !ird normal form (37@) goes one large step furt!er- (eet all t!e requirements of t!e second normal form. 1emo"e columns t!at are not dependent upon t!e primary ?ey. +ourth )ormal +orm $()+% @inally, fourt! normal form (+7@) !as one additional requirement- (eet all t!e requirements of t!e t!ird normal form. 2 relation is in +7@ if it !as no multi3"alued dependencies. ,. A!at is constraintsB SQL Ser"er userCs constraints to enforce limitations on t!e data t!at can be entered into a particular column in table. !ere are follo%ing types of constraints. $nique, .efault, 0!ec?, 6rimary <ey, @oreign <ey, 7ot 7ull. Synta/- Synta/ 2L#1 2'L# table37ame D 2.. 05L$(7 column3definition E 2.. 057S12&7 clause E .156 D 61&(21F <#F E @51#&87 <#F constraint3name E $7&Q$# constraint3name E 0G#0< constraint3name E 057S12&7 constraint3name H 2L#1 column3alteration E L50<S&I# D 15A E 2'L# H H ,. Types of "onstraints in sql (icrosoft SQL Ser"er supports t!e follo%ing constraints- 61&(21F <#F $7&Q$# @51#&87 <#F 0G#0< 75 7$LL 2 61&(21F <#F constraint is a unique identifier for a ro% %it!in a database table. #"ery table s!ould !a"e a primary ?ey constraint to uniquely identify eac! ro% and only one primary ?ey constraint can be created for eac! table. !e primary ?ey constraints are used to enforce entity integrity. 2 $7&Q$# constraint enforces t!e uniqueness of t!e "alues in a set of columns, so no duplicate "alues are entered. !e unique ?ey constraints are used to enforce entity integrity as t!e primary ?ey constraints. 2 @51#&87 <#F constraint pre"ents any actions t!at %ould destroy lin? bet%een tables %it! t!e corresponding data "alues. 2 foreign ?ey in one table points to a primary ?ey in anot!er table. @oreign ?eys pre"ent actions t!at %ould lea"e ro%s %it! foreign ?ey "alues %!en t!ere are no primary ?eys %it! t!at "alue. !e foreign ?ey constraints are used to enforce referential integrity. 2 0G#0< constraint is used to limit t!e "alues t!at can be placed in a column. !e c!ec? constraints are used to enforce domain integrity. 2 75 7$LL constraint enforces t!at t!e column %ill not accept null "alues. !e not null constraints are used to enforce domain integrity, as t!e c!ec? constraints. Fou can create constraints %!en t!e table is created, as part of t!e table definition by using t!e 01#2# 2'L# statement. #/amples !e follo%ing e/ample creates a c!ec?Jsale 0G#0< constraint on an employee table- 01#2# 2'L# employee( #mployee&d &7 75 7$LL, L7ame >210G21(3K) 75 7$LL, @7ame >210G21(3K) 75 7$LL, 2ddress >210G21(1KK) 75 7$LL, Gire.ate .2#&(# 75 7$LL, Salary (57#F 75 7$LL 057S12&7 c!ec?Jsale 0G#0< (salary L K) ) Fou can add constraints to an e/isting table by using t!e 2L#1 2'L# statement. !e follo%ing e/ample adds a p?Jemployee primary ?ey constraint on an employee table- 2L#1 2'L# employee 2.. 057S12&7 p?Jemployee 61&(21F <#F (#mployee&d) Fou can add t!e primary or unique ?ey constraint into an e/isting table only %!en t!ere are no duplicate ro%s in t!e table. Fou can drop constraints in an e/isting table by using t!e 2L#1 2'L# statement. !e follo%ing e/ample drops t!e p?Jemployee primary ?ey constraint in t!e employee table- 2L#1 2'L# employee .156 057S12&7 p?Jemployee Sometimes you need to perform some actions t!at require t!e @51#&87 <#F or 0G#0< constraints be disabled, for e/ample, your company do not !ire foreign employees, you made t!e appropriate constraint, but t!e situation %as c!anged and your boss need to !ire t!e foreign employee, but only t!is one. &n t!is case, you need to disable t!e constraint by using t!e 2L#1 2'L# statement. 2fter t!ese actions %ill be performed, you can re3enable t!e @51#&87 <#F and 0G#0< constraints by using t!e 2L#1 2'L# statement. *. What is -rimary .ey? !e primary ?ey of a relational table uniquely identifies eac! record in t!e table. &t can eit!er be a normal attribute t!at is guaranteed to be unique (suc! as Social Security 7umber in a table %it! no more t!an one record per person) or it can be generated by t!e .'(S (suc! as a globally unique identifier, or 8$&., in (icrosoft SQL Ser"er). 6rimary ?eys may consist of a single attribute or multiple attributes in combination. SQL Ser/er- !0E1TE T12LE !ustomer $S3D inte#er -03M104 .E4, Last5)ame /ar"har$36%, +irst5)ame /ar"har$36%%7 'elo% are e/amples for specifying a primary ?ey by altering a table- SQL Ser/er- 1LTE0 T12LE !ustomer 1DD -03M104 .E4 $S3D%7 8. What is +orei#n .ey? 2 foreign ?ey is a field (or fields) t!at points to t!e primary ?ey of anot!er table. !e purpose of t!e foreign ?ey is to ensure referential integrity of t!e data. &n ot!er %ords, only "alues t!at are supposed to appear in t!e database are permitted. SQL Ser/er- !0E1TE T12LE 90DE0S $9rer53D inte#er primary :ey, 9rer5Date atetime, !ustomer5S3D inte#er referen"es !;ST9ME0$S3D%, 1mount ou<le%7 SQL Ser/er- 1LTE0 T12LE 90DE0S 1DD +90E3=) .E4 $"ustomer5si% 0E+E0E)!ES !;ST9ME0$S3D%7 ).%!at is t!e difference bet%een primary ?ey M foreign ?eyB primary ?ey is used to identify a ro% and it doesnot allo% null "alues. &t a"oids duplication of ro%s. %!ereas foreign ?ey refers to a column or combination of columns included in t!e defenition of referential integrity. 16. SQL 3nte#rity !onstraints &ntegrity 0onstraints are used to apply business rules for t!e database tables. !e constraints a"ailable in SQL are +orei#n .ey, )ot )ull, ;nique, !he":. 0onstraints can be defined in t%o %ays 1) !e constraints can be specified immediately after t!e column definition. !is is called column3le"el definition. 2) !e constraints can be specified after all t!e columns are defined. !is is called table3le"el definition. 1% SQL -rimary :ey' !is constraint defines a column or combination of columns %!ic! uniquely identifies eac! ro% in t!e table. Synta& to efine a -rimary :ey at "olumn le/el' column name datatype N057S12&7 constraintJnameO 61&(21F <#F Synta& to efine a -rimary :ey at ta<le le/el' N057S12&7 constraintJnameO 61&(21F <#F (columnJname1,columnJname2,..) column_name1, column_name2 are t!e names of t!e columns %!ic! define t!e primary <ey. !e synta/ %it!in t!e brac?et i.e. N057S12&7 constraintJnameO is optional. +or E&le' o create an employee table %it! 6rimary <ey constraint, t!e query %ould be li?e. -rimary .ey at ta<le le/el' 01#2# 2'L# employee ( id number(,) 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), salary number(1K), location c!ar(1K) )P or 01#2# 2'L# employee ( id number(,) 057S12&7 empJidJp? 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), salary number(1K), location c!ar(1K) )P -rimary .ey at ta<le le/el' 01#2# 2'L# employee ( id number(,), name c!ar(2K), dept c!ar(1K), age number(2), salary number(1K), location c!ar(1K), 057S12&7 empJidJp? 61&(21F <#F (id) )P 2% SQL +orei#n :ey or 0eferential 3nte#rity ' !is constraint identifies any column referencing t!e 61&(21F <#F in anot!er table. &t establis!es a relations!ip bet%een t%o columns in t!e same table or bet%een different tables. @or a column to be defined as a @oreign <ey, it s!ould be a defined as a 6rimary <ey in t!e table %!ic! it is referring. 5ne or more columns can be defined as @oreign ?ey. Synta& to efine a +orei#n :ey at "olumn le/el' N057S12&7 constraintJnameO 1#@#1#70#S 1eferencedJableJname(columnJname) Synta& to efine a +orei#n :ey at ta<le le/el' N057S12&7 constraintJnameO @51#&87 <#F(columnJname) 1#@#1#70#S referencedJtableJname(columnJname)P +or E&le' 1) Lets use t!e QproductQ table and QorderJitemsQ. +orei#n .ey at "olumn le/el' 01#2# 2'L# product ( productJid number(,) 057S12&7 pdJidJp? 61&(21F <#F, productJname c!ar(2K), supplierJname c!ar(2K), unitJprice number(1K) )P 01#2# 2'L# orderJitems ( orderJid number(,) 057S12&7 odJidJp? 61&(21F <#F, productJid number(,) 057S12&7 pdJidJf? 1#@#1#70#S, product(productJid), productJname c!ar(2K), supplierJname c!ar(2K), unitJprice number(1K) )P +orei#n .ey at ta<le le/el' 01#2# 2'L# orderJitems ( orderJid number(,) , productJid number(,), productJname c!ar(2K), supplierJname c!ar(2K), unitJprice number(1K) 057S12&7 odJidJp? 61&(21F <#F(orderJid), 057S12&7 pdJidJf? @51#&87 <#F(productJid) 1#@#1#70#S product(productJid) )P 2) &f t!e employee table !as a =mgrJid= i.e, manager id as a foreign ?ey %!ic! references primary ?ey =id= %it!in t!e same table, t!e query %ould be li?e, 01#2# 2'L# employee ( id number(,) 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), mgrJid number(,) 1#@#1#70#S employee(id), salary number(1K), location c!ar(1K) )P 3% SQL )ot )ull !onstraint ' !is constraint ensures all ro%s in t!e table contain a definite "alue for t!e column %!ic! is specified as not null. A!ic! means a null "alue is not allo%ed. Synta& to efine a )ot )ull "onstraint' N057S12&7 constraint nameO 75 7$LL +or E&le' o create a employee table %it! 7ull "alue, t!e query %ould be li?e 01#2# 2'L# employee ( id number(,), name c!ar(2K) 057S12&7 nmJnn 75 7$LL, dept c!ar(1K), age number(2), salary number(1K), location c!ar(1K) )P (% SQL ;nique .ey' !is constraint ensures t!at a column or a group of columns in eac! ro% !a"e a distinct "alue. 2 column(s) can !a"e a null "alue but t!e "alues cannot be duplicated. Synta& to efine a ;nique :ey at "olumn le/el' N057S12&7 constraintJnameO $7&Q$# Synta& to efine a ;nique :ey at ta<le le/el' N057S12&7 constraintJnameO $7&Q$#(columnJname) +or E&le' o create an employee table %it! $nique ?ey, t!e query %ould be li?e, ;nique .ey at "olumn le/el' 01#2# 2'L# employee ( id number(,) 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), salary number(1K), location c!ar(1K) $7&Q$# )P or 01#2# 2'L# employee ( id number(,) 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), salary number(1K), location c!ar(1K) 057S12&7 locJun $7&Q$# )P ;nique .ey at ta<le le/el' 01#2# 2'L# employee ( id number(,) 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), salary number(1K), location c!ar(1K), 057S12&7 locJun $7&Q$#(location) )P >% SQL !he": !onstraint ' !is constraint defines a business rule on a column. 2ll t!e ro%s must satisfy t!is rule. !e constraint can be applied for a single column or a group of columns. Synta& to efine a !he": "onstraint' N057S12&7 constraintJnameO 0G#0< (condition) +or E&le' &n t!e employee table to select t!e gender of a person, t!e query %ould be li?e !he": !onstraint at "olumn le/el' 01#2# 2'L# employee ( id number(,) 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), gender c!ar(1) 0G#0< (gender in (=(=,=@=)), salary number(1K), location c!ar(1K) )P !he": !onstraint at ta<le le/el' 01#2# 2'L# employee ( id number(,) 61&(21F <#F, name c!ar(2K), dept c!ar(1K), age number(2), gender c!ar(1), salary number(1K), location c!ar(1K), 057S12&7 genderJc? 0G#0< (gender in (=(=,=@=)) )P .ifference bet%een .elete and runcate 0ommandB !e .#L## command is used to remo"e ro%s from a table. 2 AG#1# clause can be used to only remo"e some ro%s. &f no AG#1# condition is specified, all ro%s %ill be remo"ed. 2fter performing a .#L## operation you need to 05((& or 15LL'20< t!e transaction to ma?e t!e c!ange permanent or to undo it. 1$702# remo"es all ro%s from a table. !e operation cannot be rolled bac?. 2s suc!, 1$02# is faster and doesn=t use as muc! undo space as a .#L##. !e .156 command remo"es a table from t!e database. 2ll t!e tables= ro%s, inde/es and pri"ileges %ill also be remo"ed. !e operation cannot be rolled bac?. .156 and 1$702# are ..L commands, %!ereas .#L## is a .(L command. !erefore .#L## operations can be rolled bac? (undone), %!ile .156 and 1$702# operations cannot be rolled bac?. 11. 7ame fi"e 'uilt in functions in SQLB )umeri"al +un"tion ' 2'S(d) 205S(d) 2S&7(d) 227(d) 2272(a,b) '&27.(a,b) '&51(a,b) '&;51(a,b) 0#&L&78(d) 05S(d) 05(d) .#81##S(d) #;6(d) @L551(d) L58(d) L581K(d) (5.(a,b) 65A#1(a,b) 12.&27S(d) Strin# +un"tions ' 2S0&&(s) '&JL#78G(str) 0G21(c) 0G21JL#78G(str) 05702(str1,str2) .&@@#1#70#(s1,s2) G#;512A(s1) &7S#1(s,start,len,s2) L02S#(s) L#@(s,count) L#78G(s) L502#(searc!,s,NstartO) L1&((s) L5A#1(s) 50#JL#78G(str) 12A5G#;(s1) 65S&&57 (Rstring e/pressionL &7 Rstring e/pression 1L) 1#6#2(s,count) 1#6L20#(s,replace,s2) 1&8G(s,count) 11&((s) S5$7.#;(s) S620#(count) Date an Time +un"tions ' .2#.&@@(string, datetime1, datetime2) .2F72(#(date) .2F5@(57G(date) .2F5@A##<(date) .2F5@F#21(date) G5$1(time) (&7$#(time) (57G(date) (57G72(#(date) 75A() S#057.(time) System +un"tions' .22'2S#() $S#1() 0$11#7J$S#1 &.#7&F() 1##re#ate +un"tion' 2ggregate functions are used to perform some computation against group of "alues. #ac! field in a table can be t!oug!t of as one group of "alues. $se of t!e 815$6 'F clause in a select statement allo%s t!e creation of multiple "alue groups 05$7( 2ny E S ) (&7(d) (2;(d) S$((d) 2>8(d) S5(#(b) #>#1F(b) 12. Data 3nte#rity #nforcing data integrity ensures t!e quality of t!e data in t!e database. @or e/ample, if an employee is entered %it! anemployee5i "alue of 123, t!e database s!ould not allo% anot!er employee to !a"e an &. %it! t!e same "alue. &f you !a"e an employee5ratin# column intended to !a"e "alues ranging from 1 to >, t!e database s!ould not accept a "alue of ,. &f t!e table !as a ept5i column t!at stores t!e department number for t!e employee, t!e database s!ould allo% only "alues t!at are "alid for t!e department numbers in t!e company. %o important steps in planning tables are to identify "alid "alues for a column and to decide !o% to enforce t!e integrity of t!e data in t!e column. .ata integrity falls into t!ese categories- #ntity integrity .omain integrity 1eferential integrity $ser3defined integrity Entity 3nte#rity #ntity integrity defines a ro% as a unique entity for a particular table. #ntity integrity enforces t!e integrity of t!e identifier column(s) or t!e primary ?eyof a table (t!roug! inde/es, $7&Q$# constraints, 61&(21F <#F constraints, or &.#7&F properties). Domain 3nte#rity .omain integrity is t!e "alidity of entries for a gi"en column. Fou can enforce domain integrity by restricting t!e type (t!roug! data types), t!e format (t!roug! 0G#0< constraints and rules), or t!e range of possible "alues (t!roug! @51#&87 <#F constraints, 0G#0< constraints, .#@2$L definitions, 75 7$LL definitions, and rules). 0eferential 3nte#rity 1eferential integrity preser"es t!e defined relations!ips bet%een tables %!en records are entered or deleted. &n (icrosoftT SQL Ser"erU 2KKK, referential integrity is based on relations!ips bet%een foreign ?eys and primary ?eys or bet%een foreign ?eys and unique ?eys (t!roug! @51#&87 <#F and 0G#0< constraints). 1eferential integrity ensures t!at ?ey "alues are consistent across tables. Suc! consistency requires t!at t!ere be no references to none/istent "alues and t!at if a ?ey "alue c!anges, all references to it c!ange consistently t!roug!out t!e database. 13. What is the ifferen"e <et?een primary :ey @ forei#n :ey? primary ?ey is used to identify a ro% and it doesnot allo% null "alues. &t a"oids duplication of ro%s. %!ereas foreign ?ey refers to a column or combination of columns included in t!e defenition of referential integrity. 1(. What are the a/anta#es an isa/anta#es of primary :ey an forei#n :ey in SQL? -rimary :ey 1/anta#es 1) &t is a unique ?ey on %!ic! all t!e ot!er candidate ?eys are functionally dependent Disa/anta#e 1) !ere can be more t!an one ?eys on %!ic! all t!e ot!er attributes are dependent on. +orei#n .ey 1/anta#e 1) &t allo%s refrencing anot!er table using t!e primary ?ey for t!e ot!er table 1( . 9perators 2n operator is a symbol specifying an action t!at is performed on one or more e/pressions. (icrosoftT SQL Ser"erU 2KKK uses t!ese operator categories- 2rit!metic operators 2ssignment operator 'it%ise operators 0omparison operators Logical operators String concatenation operator $nary operators 1> . +i/e mathemati"al fun"tions? (at!ematical operators are pro"ided for many 6ostgreSQL types. @or types %it!out common mat!ematical con"entions for all possible permutations (e.g., date9time types) %e describe t!e actual be!a"ior in subsequent sections. abs(/) (same as /) absolute "alue abs(31*.+) 1*.+ cbrt(dp) dp cube root cbrt(2*.K) 3 ceil(dp or numeric) (same as input) smallest integer not less t!an argument ceil(3+2.V) 3+2 degrees(dp) dp radians to degrees degrees(K.,) 2V.W+*VV)*,W,+12 e/p(dp or numeric) (same as input) e/ponential e/p(1.K) 2.*1V2V1V2V+,)K, floor(dp or numeric) (same as input) largest integer not greater t!an argument floor(3+2.V) 3+3 ln(dp or numeric) (same as input) natural logarit!m ln(2.K) K.W)31+*1VK,,))+, log(dp or numeric) (same as input) base 1K logarit!m log(1KK.K) 2 log(b numeric, /numeric) numeric logarit!m to base b log(2.K, W+.K) W.KKKKKKKKKK mod(y, /) (same as argument types) remainder of y9/ mod(),+) 1 pi() dp Q6iQ constant pi() 3.1+1,)2W,3,V)*) po%(/ dp, e dp) dp raise a number to e/ponent e po%().K, 3.K) *2) po%(/ numeric, enumeric) numeric raise a number to e/ponent e po%().K, 3.K) *2) radians(dp) dp degrees to radians radians(+,.K) K.*V,3)V1W33)*++V random() dp random "alue bet%een K.K and 1.K random() round(dp or numeric) (same as input) round to nearest integer round(+2.+) +2 round(" numeric, sinteger) numeric round to s decimal places round(+2.+3V2, 2) +2.++ sign(dp or numeric) (same as input) sign of t!e argument (31, K, X1) sign(3V.+) 31 sqrt(dp or numeric) (same as input) square root sqrt(2.K) 1.+1+213,W23*31 trunc(dp or numeric) (same as input) truncate to%ard zero trunc(+2.V) +2 trunc(" numeric, sinteger) numeric truncate to s decimal places trunc(+2.+3V2, 2) +2.+3 1,. Tri#nomentri" +un"tions? +un"tion Des"ription acos(/) in"erse cosine asin(/) in"erse sine atan(/) in"erse tangent atan2(/, y) in"erse tangent of /9y cos(/) cosine cot(/) cotangent sin(/) sine tan(/) tangent 1A. SQL Strin# +un"tions an 9perators +un"tion 0etu rn Type Des"riptio n E&le 0esult string EE string te/t String concatenation =6ost= EE =greSQL= 6ostgreSQ L bitJlengt!(string) intege r 7umber of bits in string bitJlengt!(=4ose =) 32 c!arJlengt!(string) orc!aracterJlengt!(string) intege r 7umber of c!aracters in string c!arJlengt!(=4o se=) + con"ert(string usingcon"ersionJna me) te/t 0!ange encoding using specified con"ersion name. 0on"ersions can be defined by 01#2# 057>#1S&57 . 2lso t!ere are some pre3 defined con"ersion names. See Ta<le ,B 8 for a"ailable con"ersion names. con"ert(=6ostgr eSQL= using isoJVV,)J1Jto JutfJV) =6ostgreS QL=in $nicode ($@3V) encoding lo%er(string) te/t 0on"ert string to lo%er case lo%er(=5(=) tom octetJlengt!(string) intege r 7umber of bytes in string octetJlengt!(=4o se=) + o"erlay(string placingstring from inte ger NforintegerO) te/t &nsert substring o"erlay(=////a s= placing =!om= from 2 for +) !omas position(substring instring) intege r Location of specified substring position(=om= in =!omas=) 3 substring(string NfromintegerO Nfor integerO) te/t #/tract substring substring(=!o mas= from 2 for 3) !om substring(string frompattern) te/t #/tract substring matc!ing 65S&; regular e/pression substring(=!o mas= from =... Y=) mas substring(string frompattern for esc ape) te/t #/tract substring matc!ing SQL regular substring(=!o mas= from =Z[QoJa[QJ= oma +un"tion 0etu rn Type Des"riptio n E&le 0esult e/pression for =[=) trim(Nleading E trailing E bot!O Nc!aractersO fromstring) te/t 1emo"e t!e longest string containing only t!ec!aracte rs (a space by default) from t!e beginning9en d9bot! ends of t!e string trim(bot! =/= from =/om//=) om upper(string) te/t 0on"ert string to upper case upper(=tom=) 5( 18. DateCTime +un"tions )ame 0eturn Type Des"ription E&le 0esult age(timestamp) inter"al Subtract from today age(timestamp =1),*3KW313=) +3 years V mons 3 days age(timestamp,timestamp ) inter"al Subtract arguments age(=2KK13K+3 1K=, timestamp =1),*3KW313=) +3 years ) mons 2* days currentJdate date oday=s dateP see Se"tion ,.8.(
currentJtime time %it! time zone ime of dayP see Se"tion ,.8.(
currentJtimestamp timestam p %it! time zone .ate and timeP see Se"tion ,.8.(
dateJpart(te/t,timestamp ) double precision 8et subfield (equi"alent to e/tract)P see also <elo? dateJpart(=!our=, timestamp =2KK13K231W 2K-3V-+K=) 2K dateJpart(te/t,inter"al) double precision 8et subfield (equi"alent to e/tract)P see also <elo? dateJpart(=mont !=, inter"al =2 years 3 mont!s=) 3 dateJtrunc(te/t,timestam p) timestam p runcate to specified precisionP see also Se"tion ,.8.2 dateJtrunc(=!our= , timestamp =2KK13K231W 2K-3V-+K=) 2KK13K231W 2K-KK-KKXKK e/tract(field fromtimesta mp) double precision 8et subfieldP see also Se"tion ,.8.1 e/tract(!our from timestamp =2KK13K231W 2K-3V-+K=) 2K e/tract(field frominter"al) double precision 8et subfieldP see also Se"tion ,.8.1 e/tract(mont! from inter"al =2 years 3 mont!s=) 3 isfinite(timestamp) boolean est for finite time isfinite(timestam true )ame 0eturn Type Des"ription E&le 0esult stamp (neit!er in"alid nor infinity) p =2KK13K231W 21-2V-3K=) isfinite(inter"al) boolean est for finite inter"al isfinite(inter"al =+ !ours=) true localtime time ime of dayP see Se"tion ,.8.(
localtimestamp timestam p .ate and timeP see Se"tion ,.8.(
no%() timestam p %it! time zone 0urrent date and time (equi"alent tocurrentJtimestamp )P see Se"tion ,.8.(
timeofday() te/t 0urrent date and timeP see Se"tion ,.8.( timeofday() Aed @eb 21 1*-K1-13.KKK12 W 2KK1 #S 1D. 1##re#ate +un"tions +un"tion 1r#ument Type0eturn Type Des"ripti on
a"g(e/pres sion) smallint, integer,bigi nt, real, double precision, numeric, or inter"al. numeric for any integer type argument, double precision for a floating3 point argument, ot!er%ise t!e same as t!e argument data type t!e a"erage (arit!metic mean) of all input "alues
count(S) bigint number of input "alues
count(e/pre ssion) any bigint number of input "alues for %!ic! t!e "alue ofe/pressi on is not null
ma/(e/pres sion) any numeric, string, or date9time type same as argument type ma/imum "alue ofe/pressi on across all input "alues
min(e/pres sion) any numeric, string, or date9time type same as argument type minimum "alue ofe/pressi on across all input "alues
stdde"(e/pr ession) smallint, integer,bigi nt, real, double precision, ornumeric. double precision for floating3point arguments, ot!er%ise numeric. sample standard de"iation of t!e input "alues
sum(e/pres smallint, integer,bigi bigint for smallint or integer arguments,nu sum +un"tion 1r#ument Type0eturn Type Des"ripti on
sion) nt, real, double precision, numeric, or inter"al meric for bigint arguments, double precisionfor floating3point arguments, ot!er%ise t!e same as t!e argument data type of e/pressi onacross all input "alues "ariance(e/p ression) smallint, integer,bigi nt, real, double precision, ornumeric. double precision for floating3point arguments, ot!er%ise numeric. sample "ariance of t!e input "alues (square of t!e sample standard de"iation) 26 ?hat is ha/in# "lause? SQL' E1F3)= !lause !e G2>&78 clause is used in combination %it! t!e 815$6 'F clause. &t can be used in a S#L#0 statement to filter t!e records t!at a 815$6 'F returns. !e synta/ for t!e G2>&78 clause is- SELE!T "olumn1, "olumn2, ... "olumn5n, a##re#ate5fun"tion $e&pression% +09M ta<les WEE0E prei"ates =09;- 24 "olumn1, "olumn2, ... "olumn5n E1F3)= "onition1 ... "onition5n7 aggregateJfunction can be a function suc! as S;M, !9;)T, M3), or M1G. E&le usin# the S;M fun"tion @or e/ample, you could also use t!e S$( function to return t!e name of t!e department and t!e total sales (in t!e associated department). !e G2>&78 clause %ill filter t!e results so t!at only departments %it! sales greater t!an Y1KKK %ill be returned. SELE!T epartment, S;M$sales% as HTotal salesH +09M orer5etails =09;- 24 epartment E1F3)= S;M$sales% I 16667 E&le usin# the !9;)T fun"tion @or e/ample, you could use t!e 05$7 function to return t!e name of t!e department and t!e number of employees (in t!e associated department) t!at ma?e o"er Y2,,KKK 9 year. !e G2>&78 clause %ill filter t!e results so t!at only departments %it! more t!an 1K employees %ill be returned. SELE!T epartment, !9;)T$J% as H)um<er of employeesH +09M employees WEE0E salary I 2>666 =09;- 24 epartment E1F3)= !9;)T$J% I 167 E&le usin# the M3) fun"tion @or e/ample, you could also use t!e (&7 function to return t!e name of eac! department and t!e minimum salary in t!e department. !e G2>&78 clause %ill return only t!ose departments %!ere t!e starting salary is Y3,,KKK. SELE!T epartment, M3)$salary% as HLo?est salaryH +09M employees =09;- 24 epartment E1F3)= M3)$salary% K 3>6667 E&le usin# the M1G fun"tion @or e/ample, you could also use t!e (2; function to return t!e name of eac! department and t!e ma/imum salary in t!e department. !e G2>&78 clause %ill return only t!ose departments %!ose ma/imum salary is less t!an Y,K,KKK. SELE!T epartment, M1G$salary% as HEi#hest salaryH +09M employees =09;- 24 epartment E1F3)= M1G$salary% L >66667 21. SQL' =09;- 24 !lause !e 815$6 'F clause can be used in a S#L#0 statement to collect data across multiple records and group t!e results by one or more columns. !e synta/ for t!e 815$6 'F clause is- SELE!T "olumn1, "olumn2, ... "olumn5n, a##re#ate5fun"tion $e&pression% +09M ta<les WEE0E prei"ates =09;- 24 "olumn1, "olumn2, ... "olumn5n7 aggregateJfunction can be a function suc! as S;M, !9;)T, M3), or M1G. E&le usin# the S;M fun"tion @or e/ample, you could also use t!e S$( function to return t!e name of t!e department and t!e total sales (in t!e associated department). SELE!T epartment, S;M$sales% as HTotal salesH +09M orer5etails =09;- 24 epartment7 'ecause you !a"e listed one column in your S#L#0 statement t!at is not encapsulated in t!e S$( function, you must use a 815$6 'F clause. !e department field must, t!erefore, be listed in t!e 815$6 'F section. E&le usin# the !9;)T fun"tion @or e/ample, you could use t!e 05$7 function to return t!e name of t!e department and t!e number of employees (in t!e associated department) t!at ma?e o"er Y2,,KKK 9 year. SELE!T epartment, !9;)T$J% as H)um<er of employeesH +09M employees WEE0E salary I 2>666 =09;- 24 epartment7 E&le usin# the M3) fun"tion @or e/ample, you could also use t!e (&7 function to return t!e name of eac! department and t!e minimum salary in t!e department. SELE!T epartment, M3)$salary% as HLo?est salaryH +09M employees =09;- 24 epartment7 E&le usin# the M1G fun"tion @or e/ample, you could also use t!e (2; function to return t!e name of eac! department and t!e ma/imum salary in t!e department. SELE!T epartment, M1G$salary% as HEi#hest salaryH +09M employees =09;- 24 epartment7 2,. 'rea? Statements in SQLB !e brea? command can be used to create report brea?s. A!en "alue in a column c!anges a brea? e"ent is generated and t!e action is e/ecuted. !is %ay you can s?ip a line (S<&6 1) %!en a "alue c!anges in a column. &n addition duplicate "alues can be suppressed (75.$6). Fou can specify more t!an one brea? column by adding more on clauses at t!e end. 'rea? Statements %!ic! are 1. 0ompute 2. 0ompute 'y 2W. A!at is :oins in SQLB SQL M93) !e :5&7 ?ey%ord is used in an SQL statement to query data from t%o or more tables, based on a relations!ip bet%een certain columns in t!ese tables. ables in a database are often related to eac! ot!er %it! ?eys. 2 primary ?ey is a column (or a combination of columns) %it! a unique "alue for eac! ro%. #ac! primary ?ey "alue must be unique %it!in t!e table. !e purpose is to bind data toget!er, across tables, %it!out repeating all of t!e data in e"ery table. Loo? at t!e Q6ersonsQ table- -53 Last)ame +irst)ame 1ress !ity 1 Gansen 5la imotei"n 1K Sandnes 2 S"endson o"e 'org"n 23 Sandnes 3 6ettersen <ari Storgt 2K Sta"anger 7ote t!at t!e Q6J&dQ column is t!e primary ?ey in t!e Q6ersonsQ table. !is means t!at no t%o ro%s can !a"e t!e same 6J&d. !e 6J&d distinguis!es t%o persons e"en if t!ey !a"e t!e same name. 7e/t, %e !a"e t!e Q5rdersQ table- 953 9rer)o -53 1 **V), 3 2 ++W*V 3 3 22+,W 1 + 2+,W2 1 , 3+*W+ 1, 7ote t!at t!e Q5J&dQ column is t!e primary ?ey in t!e Q5rdersQ table and t!at t!e Q6J&dQ column refers to t!e persons in t!e Q6ersonsQ table %it!out using t!eir names. 7otice t!at t!e relations!ip bet%een t!e t%o tables abo"e is t!e Q6J&dQ column. 2A. Different SQL M93)s 'efore %e continue %it! e/amples, %e %ill list t!e types of :5&7 you can use, and t!e differences bet%een t!em. M93)- 1eturn ro%s %!en t!ere is at least one matc! in bot! tables LE+T M93)- 1eturn all ro%s from t!e left table, e"en if t!ere are no matc!es in t!e rig!t table 03=ET M93)- 1eturn all ro%s from t!e rig!t table, e"en if t!ere are no matc!es in t!e left table +;LL M93)- 1eturn ro%s %!en t!ere is a matc! in one of t!e tables 2V. SQL 3))E0 M93) .ey?or !e &77#1 :5&7 ?ey%ord return ro%s %!en t!ere is at least one matc! in bot! tables. SQL 3))E0 M93) Synta& S#L#0 columnJname(s) @15( tableJname1 &77#1 :5&7 tableJname2 57 tableJname1.columnJname\tableJname2.columnJname -S' &77#1 :5&7 is t!e same as :5&7. SQL 3))E0 M93) E&le !e Q6ersonsQ table- -53 Last)ame +irst)ame 1ress !ity 1 Gansen 5la imotei"n 1K Sandnes 2 S"endson o"e 'org"n 23 Sandnes 3 6ettersen <ari Storgt 2K Sta"anger !e Q5rdersQ table- 953 9rer)o -53 1 **V), 3 2 ++W*V 3 3 22+,W 1 + 2+,W2 1 , 3+*W+ 1, 7o% %e %ant to list all t!e persons %it! any orders. Ae use t!e follo%ing S#L#0 statement- S#L#0 6ersons.Last7ame, 6ersons.@irst7ame, 5rders.5rder7o @15( 6ersons &77#1 :5&7 5rders 57 6ersons.6J&d\5rders.6J&d 51.#1 'F 6ersons.Last7ame !e result3set %ill loo? li?e t!is- Last)ame +irst)ame 9rer)o Gansen 5la 22+,W Gansen 5la 2+,W2 6ettersen <ari **V), 6ettersen <ari ++W*V !e &77#1 :5&7 ?ey%ord return ro%s %!en t!ere is at least one matc! in bot! tables. &f t!ere are ro%s in Q6ersonsQ t!at do not !a"e matc!es in Q5rdersQ, t!ose ro%s %ill 75 be listed. 28. SQL LE+T M93) .ey?or !e L#@ :5&7 ?ey%ord returns all ro%s from t!e left table (tableJname1), e"en if t!ere are no matc!es in t!e rig!t table (tableJname2). SQL LE+T M93) Synta& S#L#0 columnJname(s) @15( tableJname1 L#@ :5&7 tableJname2 57 tableJname1.columnJname\tableJname2.columnJname -S' &n some databases L#@ :5&7 is called L#@ 5$#1 :5&7. SQL LE+T M93) E&le !e Q6ersonsQ table- -53 Last)ame +irst)ame 1ress !ity 1 Gansen 5la imotei"n 1K Sandnes 2 S"endson o"e 'org"n 23 Sandnes 3 6ettersen <ari Storgt 2K Sta"anger !e Q5rdersQ table- 953 9rer)o -53 1 **V), 3 2 ++W*V 3 3 22+,W 1 + 2+,W2 1 , 3+*W+ 1, 7o% %e %ant to list all t!e persons and t!eir orders 3 if any, from t!e tables abo"e. Ae use t!e follo%ing S#L#0 statement- S#L#0 6ersons.Last7ame, 6ersons.@irst7ame, 5rders.5rder7o @15( 6ersons L#@ :5&7 5rders 57 6ersons.6J&d\5rders.6J&d 51.#1 'F 6ersons.Last7ame !e result3set %ill loo? li?e t!is- Last)ame +irst)ame 9rer)o Gansen 5la 22+,W Gansen 5la 2+,W2 6ettersen <ari **V), 6ettersen <ari ++W*V S"endson o"e !e L#@ :5&7 ?ey%ord returns all t!e ro%s from t!e left table (6ersons), e"en if t!ere are no matc!es in t!e rig!t table (5rders). SQL 03=ET M93) .ey?or !e 1&8G :5&7 ?ey%ord 1eturn all ro%s from t!e rig!t table (tableJname2), e"en if t!ere are no matc!es in t!e left table (tableJname1). SQL 03=ET M93) Synta& S#L#0 columnJname(s) @15( tableJname1 1&8G :5&7 tableJname2 57 tableJname1.columnJname\tableJname2.columnJname -S' &n some databases 1&8G :5&7 is called 1&8G 5$#1 :5&7. SQL 03=ET M93) E&le !e Q6ersonsQ table- -53 Last)ame +irst)ame 1ress !ity 1 Gansen 5la imotei"n 1K Sandnes 2 S"endson o"e 'org"n 23 Sandnes 3 6ettersen <ari Storgt 2K Sta"anger !e Q5rdersQ table- 953 9rer)o -53 1 **V), 3 2 ++W*V 3 3 22+,W 1 + 2+,W2 1 , 3+*W+ 1, 7o% %e %ant to list all t!e orders %it! containing persons 3 if any, from t!e tables abo"e. Ae use t!e follo%ing S#L#0 statement- S#L#0 6ersons.Last7ame, 6ersons.@irst7ame, 5rders.5rder7o @15( 6ersons 1&8G :5&7 5rders 57 6ersons.6J&d\5rders.6J&d 51.#1 'F 6ersons.Last7ame !e result3set %ill loo? li?e t!is- Last)ame +irst)ame 9rer)o Gansen 5la 22+,W Gansen 5la 2+,W2 6ettersen <ari **V), 6ettersen <ari ++W*V 3+*W+ !e 1&8G :5&7 ?ey%ord returns all t!e ro%s from t!e rig!t table (5rders), e"en if t!ere are no matc!es in t!e left table (6ersons). SQL +;LL M93) .ey?or !e @$LL :5&7 ?ey%ord return ro%s %!en t!ere is a matc! in one of t!e tables. SQL +;LL M93) Synta& S#L#0 columnJname(s) @15( tableJname1 @$LL :5&7 tableJname2 57 tableJname1.columnJname\tableJname2.columnJname SQL +;LL M93) E&le !e Q6ersonsQ table- -53 Last)ame +irst)ame 1ress !ity 1 Gansen 5la imotei"n 1K Sandnes 2 S"endson o"e 'org"n 23 Sandnes 3 6ettersen <ari Storgt 2K Sta"anger !e Q5rdersQ table- 953 9rer)o -53 1 **V), 3 2 ++W*V 3 3 22+,W 1 + 2+,W2 1 , 3+*W+ 1, 7o% %e %ant to list all t!e persons and t!eir orders, and all t!e orders %it! t!eir persons. Ae use t!e follo%ing S#L#0 statement- S#L#0 6ersons.Last7ame, 6ersons.@irst7ame, 5rders.5rder7o @15( 6ersons @$LL :5&7 5rders 57 6ersons.6J&d\5rders.6J&d 51.#1 'F 6ersons.Last7ame !e result3set %ill loo? li?e t!is- Last)ame +irst)ame 9rer)o Gansen 5la 22+,W Gansen 5la 2+,W2 6ettersen <ari **V), 6ettersen <ari ++W*V S"endson o"e 3+*W+ !e @$LL :5&7 ?ey%ord returns all t!e ro%s from t!e left table (6ersons), and all t!e ro%s from t!e rig!t table (5rders). &f t!ere are ro%s in Q6ersonsQ t!at do not !a"e matc!es in Q5rdersQ, or if t!ere are ro%s in Q5rdersQ t!at do not !a"e matc!es in Q6ersonsQ, t!ose ro%s %ill be listed as %ell. 3K. %!at is the difference bet%een &nner 4oin and full outer 4oin in terms of t!e 7umber of ro%s returnedB &nner :oin %ill return ro%s t!at !a"e matc!ing records in bot! table, but in case of full outer 4oin it %ill return all records from left table and from rig!t table. &n Left35uter 4oin all t!e record from t!e left3most table %ill be fetc!ed and if records found in t!e 2nd table t!en field "alues %ill be displayed else it %ill display 7ull in t!e 2nd table fields. #/. 0reate table #(672(# (&. int, #(672(# "arc!ar(2K)) 01#2# table #(62..1#SS (&. int, 2..1#SS "arc!ar(2K)) &7S#1 &75 #(672(# >2L$#S(1, =.##627=) &7S#1 &75 #(672(# >2L$#S(2, =12(#SG=) &7S#1 &75 #(672(# >2L$#S(3, =612.##6=) &7S#1 &75 #(62..1#SS >2L$#S(1, ='2782L51#=) &7S#1 &75 #(62..1#SS >2L$#S(2, =.#LG&=) &7S#1 &75 #(62..1#SS >2L$#S(+, =.#LG&=) S#L#0 S @15( #(672(# &. #(672(# 33333333333 33333333333333333333 1 .##627 2 12(#SG 3 612.##6 S#L#0 S @15( #(62..1#SS &. 2..1#SS 33333333333 33333333333333333333 1 '2782L51# 2 .#LG& + .#LG& #/ample - &77#1 :5&7 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\ S#L#0 #(672(#.&., #(672(#.#(672(#, #(62..1#SS.2..1#SS @15( #(672(# :5&7 #(62..1#SS 57 #(62..1#SS.&. \ #(672(#.&. 5utput of t!e abo"e :5&7 Query (i.e &nner Query) 33333333333333333333333333333333333333333333333333333 &. #(672(# 2..1#SS 33333333333 33333333333333333333 33333333333333333333 1 .##627 '2782L51# 2 12(#SG .#LG& #/ample - @$LL 5$#1 :5&7 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\ S#L#0 #(672(#.&., #(672(#.#(672(#, #(62..1#SS.2..1#SS @15( #(672(# @$LL 5$#1 :5&7 #(62..1#SS 57 #(62..1#SS.&. \ #(672(#.&. 5utput of t!e abo"e @$LL 5$#1 :5&7 Query 33333333333333333333333333333333333333333333333333333 &. #(672(# 2..1#SS 33333333333 33333333333333333333 33333333333333333333 1 .##627 '2782L51# 2 12(#SG .#LG& 3 612.##6 7$LL 7$LL 7$LL .#LG& #/ample - L#@ 5$#1 :5&7 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\ S#L#0 #(672(#.&., #(672(#.#(672(#, #(62..1#SS.2..1#SS @15( #(672(# L#@ 5$#1 :5&7 #(62..1#SS 57 #(62..1#SS.&. \ #(672(#.&. 5utput of t!e abo"e L#@ 5$#1 :5&7 Query 33333333333333333333333333333333333333333333333333333 &. #(672(# 2..1#SS 33333333333 33333333333333333333 33333333333333333333 1 .##627 '2782L51# 2 12(#SG .#LG& 3 612.##6 7$LL #/ample - 1&8G 5$#1 :5&7 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\ S#L#0 #(672(#.&., #(672(#.#(672(#, #(62..1#SS.2..1#SS @15( #(672(# 1&8G 5$#1 :5&7 #(62..1#SS 57 #(62..1#SS.&. \ #(672(#.&. 5utput of t!e abo"e 1&8G 5$#1 :5&7 Query 33333333333333333333333333333333333333333333333333333 &. #(672(# 2..1#SS 33333333333 33333333333333333333 33333333333333333333 1 .##627 '2782L51# 2 12(#SG .#LG& 7$LL 7$LL .#LG& 31 .A!at is t!e difference bet%een left outer 4oin and (X) outer 4oinB A!en & use left outer 4oin t!e cost of t!e SQL query is !ig!, and %!en & use t!e (X) operator t!e 4oin cost is muc! less. !ere are t!ree types of outer 4oins, left, rig!t and full. 2 left outer 4oin contains all records of t!e QleftQ table e"en if it !as no matc!es in t!e Qrig!tQ table specified in t!e 4oin. 2 rig!t outer 4oin contains all records in t!e Qrig!tQ able e"en if it !as no matc!es in t!e QleftQ table. 2 full outer 4oin contains all records of bot! t!e left and rig!t tables. 32. SQL Su<query Subquery or &nner query or 7ested query is a query in a query. 2 subquery is usually added in t!e AG#1# 0lause of t!e sql statement. (ost of t!e time, a subquery is used %!en you ?no% !o% to searc! for a "alue using a S#L#0 statement, but do not ?no% t!e e/act "alue. Subqueries are an alternate %ay of returning data from multiple tables. Subqueries can be used %it! t!e follo%ing sql statements along %it! t!e comparision operators li?e \, R, L, L\, R\ etc. +or E&le' 1) $sually, a subquery s!ould return only one record, but sometimes it can also return multiple records %!en used %it! operators li?e &7, 75 &7 in t!e %!ere clause. !e query %ould be li?e, S#L#0 firstJname, lastJname, sub4ect @15( studentJdetails AG#1# games 75 &7 (=0ric?et=, =@ootball=)P !e output %ould be similar to- first5name last5name su<Ne"t 3333333333333 3333333333333 3333333333 S!e?ar 8o%da 'adminton 6riya 0!andra 0!ess 2) Lets consider t!e studentJdetails table %!ic! %e !a"e used earlier. &f you ?no% t!e name of t!e students %!o are studying science sub4ect, you can get t!eir id=s by using t!is query belo%, S#L#0 id, firstJname @15( studentJdetails AG#1# firstJname &7 (=1a!ul=, =Step!en=)P but, if you do not ?no% t!eir names, t!en to get t!eir id=s you need to %rite t!e query in t!is manner, S#L#0 id, firstJname @15( studentJdetails AG#1# firstJname &7 (S#L#0 firstJname @15( studentJdetails AG#1# sub4ect\ =Science=)P 5utput- i first5name 33333333 3333333333333 1KK 1a!ul 1K2 Step!en &n t!e abo"e sql statement, first t!e inner query is processed first and t!en t!e outer query is processed. 3) Subquery can be used %it! &7S#1 statement to add ro%s of data from one or more tables to anot!er table. Lets try to group all t!e students %!o study (at!s in a table =mat!sJgroup=. &7S#1 &75 mat!sJgroup(id, name) S#L#0 id, firstJname EE = = EE lastJname @15( studentJdetails AG#1# sub4ect\ =(at!s= +) 2 subquery can be used in t!e S#L#0 statement as follo%s. Lets use t!e product and orderJitems table defined in t!e sqlJ4oins section. select p.productJname, p.supplierJname, (select orderJid from orderJitems %!ere productJid \ 1K1) as orderJid from product p %!ere p.productJid \ 1K1 prou"t5name supplier5name orer5i 333333333333333333 333333333333333333 3333333333 ele"ision 5nida ,1K3 33.!orrelate Su<query 2 query is called correlated subquery %!en bot! t!e inner query and t!e outer query are interdependent. @or e"ery ro% processed by t!e inner query, t!e outer query is processed as %ell. !e inner query depends on t!e outer query before it can be processed. S#L#0 p.productJname @15( product p AG#1# p.productJid \ (S#L#0 o.productJid @15( orderJitems o AG#1# o.productJid \ p.productJid)P 3(. SQL !omparison .ey?ors !ere are ot!er comparison ?ey%ords a"ailable in sql %!ic! are used to en!ance t!e searc! capabilities of a sql query. !ey are Q&7Q, Q'#A##7...27.Q, Q&S 7$LLQ, QL&<#Q. Comparision Operators Description L&<# column "alue is similar to specified c!aracter(s). &7 column "alue is equal to any one of a specified set of "alues. '#A##7...27. column "alue is bet%een t%o "alues, including t!e end "alues specified in t!e range. &S 7$LL column "alue does not e/ist. SQL L3.E 9perator !e L&<# operator is used to list all ro%s in a table %!ose column "alues matc! a specified pattern. &t is useful %!en you %ant to searc! ro%s to matc! a specific pattern, or %!en you do not ?no% t!e entire "alue. @or t!is purpose %e use a %ildcard c!aracter =Z=. +or e&le' o select all t!e students %!ose name begins %it! =S= S#L#0 firstJname, lastJname @15( studentJdetails AG#1# firstJname L&<# =SZ=P !e output %ould be similar to- first5name last5name 3333333333333 3333333333333 Step!en @leming S!e?ar 8o%da !e abo"e select statement searc!es for all t!e ro%s %!ere t!e first letter of t!e column firstJname is =S= and rest of t!e letters in t!e name can be any c!aracter. !ere is anot!er %ildcard c!aracter you can use %it! L&<# operator. &t is t!e underscore c!aracter, = J = . &n a searc! string, t!e underscore signifies a single c!aracter. +or e&le' to display all t!e names %it! =a= second c!aracter, S#L#0 firstJname, lastJname @15( studentJdetails AG#1# firstJname L&<# =JaZ=P !e output %ould be similar to- first5name last5name 3333333333333 3333333333333 1a!ul S!arma )9TE'#ac! underscore act as a place!older for only one c!aracter. So you can use more t!an one underscore. #g- = JJiZ =3t!is !as t%o underscores to%ards t!e left, =SJJ4Z= 3 t!is !as t%o underscores bet%een c!aracter =S= and =i=. SQL 2ETWEE) ... 1)D 9perator !e operator '#A##7 and 27., are used to compare data for a range of "alues. +or E&le' to find t!e names of t!e students bet%een age 1K to 1, years, t!e query %ould be li?e, S#L#0 firstJname, lastJname, age @15( studentJdetails AG#1# age '#A##7 1K 27. 1,P !e output %ould be similar to- first5name last5name a#e 3333333333333 3333333333333 3333 33 1a!ul S!arma 1K 2na4ali '!ag%at 12 S!e?ar 8o%da 1, SQL 3) 9perator' !e &7 operator is used %!en you %ant to compare a column %it! more t!an one "alue. &t is similar to an 51 condition. +or e&le' &f you %ant to find t!e names of students %!o are studying eit!er (at!s or Science, t!e query %ould be li?e, S#L#0 firstJname, lastJname, sub4ect @15( studentJdetails AG#1# sub4ect &7 (=(at!s=, =Science=)P !e output %ould be similar to- first5name last5name su<Ne"t 3333333333333 3333333333333 333333333 3 2na4ali '!ag%at (at!s S!e?ar 8o%da (at!s 1a!ul S!arma Science Step!en @leming Science Fou can include more sub4ects in t!e list li?e (=mat!s=,=science=,=!istory=) )9TE'!e data used to compare is case sensiti"e. SQL 3S );LL 9perator 2 column "alue is 7$LL if it does not e/ist. !e &S 7$LL operator is used to display all t!e ro%s for columns t!at do not !a"e a "alue. +or E&le' &f you %ant to find t!e names of students %!o do not participate in any games, t!e query %ould be as gi"en belo% S#L#0 firstJname, lastJname @15( studentJdetails AG#1# games &S 7$LL !ere %ould be no output as %e !a"e e"ery student participate in a game in t!e table studentJdetails, else t!e names of t!e students %!o do not participate in any games %ould be displayed. 3>. 1LL !e first of t!e operators t!at %e %ill consider is 2LL. $sed %it! one of t!e comparison operators, 2LL compares a single "alue against a set of data from a query. #ac! "alue from t!e query=s results is combined %it! t!e scalar "alue to generate a single scalar e/pression. &f all of t!e scalar e/pressions e"aluate to true t!en t!e result of t!e 2LL e/pression %ill be true. 5t!er%ise t!e result %ill be false, or un?no%n if t!e results of t!e e/pressions cannot be determined. o demonstrate %e can e/ecute a query against t!e #ngineers table in t!e :o'S database. Let=s assume t!at a business rule is to be implemented t!at specifies t!at no engineer may !a"e an o"ertime rate lo%er t!an anot!er engineer=s basic !ourly pay. Ae can use 2LL %it! 75 to ma?e t!is comparison as follo%s- S#L#0 #ngineer&d, #ngineer7ame, 5"ertime1ate @15( #ngineers AG#1# 75 5"ertime1ate L\ 2LL (S#L#0 Gourly1ate @15( #ngineers) #/ecuting t!is query re"eals t!at t!ere are t%o engineers %!ose o"ertime rate is lo%er t!an permitted. S9ME an 1)4 !e S5(# and 27F operators pro"ide equi"alent functionality. 2s %it! t!e 2LL operator, eac! creates a series of scalar e/pressions based upon a single "alue, a comparison operator and t!e results of a single3 column query. !e difference is t!at t!e S5(# and 27F operators return true if at least one of t!e generated e/pressions e"aluates as true. !ese operators allo% us to modify t!e pre"ious e/ample query so t!at t!e 75 is no longer required. &nstead, %e can as? for t!e list of engineers %!o !a"e an o"ertime rate t!at is lo%er t!an any ot!er engineer=s basic !ourly rate, as follo%s- S#L#0 #ngineer&d, #ngineer7ame, 5"ertime1ate @15( #ngineers AG#1# 5"ertime1ate R 27F (S#L#0 Gourly1ate @15( #ngineers) 2s t!e 27F and S5(# operators are equi"alent, you can interc!ange t!e t%o ?ey%ords %it!out affecting t!e results- S#L#0 #ngineer&d, #ngineer7ame, 5"ertime1ate @15( #ngineers AG#1# 5"ertime1ate R S5(# (S#L#0 Gourly1ate @15( #ngineers) 9perator -re"een"e Ae can no% add all of t!e logical operators, including t!ose seen in pre"ious articles, to t!e table of precedence. ;nary 2it?ise 9perators ] 1rithmeti" 9perators S 9 Z ;nary 1rithmeti" 9perators X 3 1rithmeti" C !on"atenation 9perators NX arit!meticO NX concatenation)O 3 2it?ise 9perators M ^ E !omparison 9perators \, L, R, L\, R\, RL, _\, _L, _R Lo#i"al 75 27. 2LL 27F '#A##7 &7 L&<# 51 S5(# 3W. %!at is e/ist in SQL ser"erB (any times you=re required to %rite query to determine if a record e/ists. ypically you use t!is to determine %!et!er to insert or update a records. $sing t!e #;&SS ?ey%ord is a great %ay to accomplis! t!is. Gere=s a simple e/ample from t!e pubs database using #;&SS- if #;&SS (select S from aut!ors %!ere auJid \ =1*2332311*W=) 6rint =1ecord e/its 3 $pdate= #LS# 6rint =1ecord doesn==t e/ist 3 &nsert= !e #;&SS function ta?es one parameter %!ic! is a SQL statement. &f any records e/ist t!at matc! t!e criteria it returns true, ot!er%ise it returns false. !is gi"es you a clean, efficient %ay to %rite a stored procedure t!at does eit!er an insert or update. !e ot!er benefit of #;&SS is t!at once it finds a single record t!at matc!es it stops processing. !is doesn=t !a"e a !uge impact if you=re c!ec?ing on a primary ?ey. &t does !a"e a big impact if you=re c!ec?ing for e/istance based on anot!er field. 0onsider t!e follo%ing t%o queries- if e/ists (select S from aut!ors %!ere state \ =ca=) 6rint =1ecord e/its= #LS# 6rint =1ecord doesn==t e/ist= if (select count(S) from aut!ors %!ere state \ =1*2332311*W=) L K 6rint =1ecord e/its= #LS# 6rint =1ecord doesn==t e/ist= &n t!e pubs database t!ere are only 23 records in t!e aut!ors table. #"en %it! t!at small number of records, t!e &@ #;&SS "ersion runs + times faster t!an selecting a count. !is is because it stops as soon as it finds a single record t!at matc!es t!e criteria. !e second statement must process all t!e ro%s t!at matc!. 3*. %!at is >ie% in SQL ser"erB Fie? 2 "ie% is a "irtual table t!at consists of columns from one or more tables. !oug! it is similar to a table, it is stored in t!e database. &t is a query stored as an ob4ect. Gence, a "ie% is an ob4ect t!at deri"es its data from one or more tables. !ese tables are referred to as base or underlying tables. 5nce you !a"e defined a "ie%, you can reference it li?e any ot!er table in a database. 2 "ie% ser"es as a security mec!anism. !is ensures t!at users are able to retrie"e and modify only t!e data seen by t!em. $sers cannot see or access t!e remaining data in t!e underlying tables. 2 "ie% also ser"es as a mec!anism to simplify query e/ecution. 0omple/ queries can be stored in t!e form as a "ie%, and data from t!e "ie% can be e/tracted using simple queries. E&le 0onsider t!e 6ublis!ers table belo%. &f you %ant users to see only t%o columns in t!e table, you can create a "ie% called "%6ublis!ers t!at %ill refer to t!e 6ublis!ers table and t!e t%o columns required. Fou can grant 6ermissions to users to use t!e "ie% and re"o?e 6ermissions from t!e base 6ublis!ers table. !is %ay, users %ill be able to "ie% only t!e t%o columns referred to by t!e "ie%. !ey %ill not be able to query on t!e 6ublis!ers table. -u<lishers 6ubld 6ub7ame 0ity State 0ountry K*3W 7e% (oon 'oo?s 'oston (2 $S2 KV** 'innet M Gardly Aas!ington .0 $S2 13V) 2lgodata &nfosystems 'er?eley 02 $S2 1W22 @i"e La?es 6ublis!ing 0!icago &L $S2 FW -u<lishers 6ubld 6ub7ame K*3W 7e% (oon 'oo?s KV** 'innet M Gardly 13V) 2lgodata &nfosystems 1W22 @i"e La?es 6ublis!ing >ie%s ensure t!e security of data by restricting access to t!e follo%ing data- Specific ro%s of t!e tables. Specific columns of t!e tables. Specific ro%s and columns of t!e tables. 1o%s fetc!ed by using 4oins. Statistical summary of data in a gi"en tables. Subsets of anot!er "ie% or a subset of "ie%s and tables. Some common e/amples of "ie%s are- 2 subset of ro%s or columns of a base table. 2 union of t%o or more tables. 2 4oin of t%o or more tables. 2 statistical summary of base tables. 2 subset of anot!er "ie%, or some combination of "ie%s and base table. !reatin# Fie?s 2 "ie% can be created by using t!e 01#2# >&#A statement. Synta& 01#2# >&#A "ie%Jname N(columnJnameN,columnJnameO`.)O NA&G #701F6&57O 2S selectJstatement NA&G 0G#0< 56&57O A!ere- "ie%Jname specifies t!e name of t!e "ie% and must follo% t!e rules for identifiers. columnJname specifies t!e name of t!e column to be used in "ie%. &f t!e columnJname option is not specified, t!en t!e "ie% is created %it! t!e same columns as specified in t!e selectJstatement. A&G #701F6&57 encrypts t!e te/t for t!e "ie% in t!e syscomments table. 2S specifies t!e actions t!at %ill be performed by t!e "ie%. selectJstatement specifies t!e S#L#0 Statement t!at defines a "ie%. !e "ie% may use t!e data contained in ot!er "ie%s and tables. A&G 0G#0< 56&57 forces t!e data modification statements to fulfill t!e criteria gi"en in t!e S#L#0 statement defining t!e "ie%. &t also ensures t!at t!e data is "isible after t!e modifications are made permanent. !e restrictions imposed on "ie%s are as follo%s- 2 "ie% can be created only in t!e current database. !e name of a "ie% must follo% t!e rules for identifiers and must not be t!e same as t!at of t!e base table. 2 "ie% can be created only if t!ere is a S#L#0 permission on its base table. 2 S#L#0 &75 statement cannot be used in "ie% declaration statement. 2 trigger or an inde/ cannot be defined on a "ie%. !e 01#2# >&#A statement cannot be combined %it! ot!er SQL statements in a single batc!. E&le 01#2# >&#A "%0ustomer 2S S#L#0 0ustomer&d, 0ompany 7ame, 6!one @15( 0ustomers 0reates a "ie% called "%0ustomer. 7ote t!at t!e "ie% is a query stored as an ob4ect. !e data is deri"ed from t!e columns of t!e base table 0ustomers. Fou use t!e "ie% by querying t!e "ie% li?e a table. S#L#0 S@15( "%0$S5(#1 !e output of t!e S#L#0 statement is- 0ustomer&d 0ompany 7ame 6!one 2L@<& 2lfreds @utter?iste K3K3KK*+321 2757 2ntonio (oreno aqueria (,),,,33)32 ()1 ro%s affected) 2 "ie% is a "irtual table. !is c!apter s!o%s !o% to create, update, and delete a "ie%. SQL !0E1TE F3EW Statement &n SQL, a "ie% is a "irtual table based on t!e result3set of an SQL statement. 2 "ie% contains ro%s and columns, 4ust li?e a real table. !e fields in a "ie% are fields from one or more real tables in t!e database. Fou can add SQL functions, AG#1#, and :5&7 statements to a "ie% and present t!e data as if t!e data %ere coming from one single table. SQL !0E1TE F3EW Synta& 01#2# >&#A "ie%Jname 2S S#L#0 columnJname(s) @15( tableJname AG#1# condition )ote' 2 "ie% al%ays s!o%s up3to3date data_ !e database engine recreates t!e data, using t!e "ie%=s SQL statement, e"ery time a user queries a "ie%. SQL !0E1TE F3EW E&les &f you !a"e t!e 7ort!%ind database you can see t!at it !as se"eral "ie%s installed by default. !e "ie% Q0urrent 6roduct ListQ lists all acti"e products (products t!at are not discontinued) from t!e Q6roductsQ table. !e "ie% is created %it! t!e follo%ing SQL- 01#2# >&#A N0urrent 6roduct ListO 2S S#L#0 6roduct&.,6roduct7ame @15( 6roducts AG#1# .iscontinued\7o Ae can query t!e "ie% abo"e as follo%s- S#L#0 S @15( N0urrent 6roduct ListO 2not!er "ie% in t!e 7ort!%ind sample database selects e"ery product in t!e Q6roductsQ table %it! a unit price !ig!er t!an t!e a"erage unit price- 01#2# >&#A N6roducts 2bo"e 2"erage 6riceO 2S S#L#0 6roduct7ame,$nit6rice @15( 6roducts AG#1# $nit6riceL(S#L#0 2>8($nit6rice) @15( 6roducts) Ae can query t!e "ie% abo"e as follo%s- S#L#0 S @15( N6roducts 2bo"e 2"erage 6riceO 2not!er "ie% in t!e 7ort!%ind database calculates t!e total sale for eac! category in 1))*. 7ote t!at t!is "ie% selects its data from anot!er "ie% called Q6roduct Sales for 1))*Q- 01#2# >&#A N0ategory Sales @or 1))*O 2S S#L#0 .&S&70 0ategory7ame,Sum(6roductSales) 2S 0ategorySales @15( N6roduct Sales for 1))*O 815$6 'F 0ategory7ame Ae can query t!e "ie% abo"e as follo%s- S#L#0 S @15( N0ategory Sales @or 1))*O Ae can also add a condition to t!e query. 7o% %e %ant to see t!e total sale only for t!e category Q'e"eragesQ- S#L#0 S @15( N0ategory Sales @or 1))*O AG#1# 0ategory7ame\='e"erages= SQL ;patin# a Fie? Fou can update a "ie% by using t!e follo%ing synta/- SQL !0E1TE 90 0E-L1!E F3EW Synta& 01#2# 51 1#6L20# >&#A "ie%Jname 2S S#L#0 columnJname(s) @15( tableJname AG#1# condition 7o% %e %ant to add t!e Q0ategoryQ column to t!e Q0urrent 6roduct ListQ "ie%. Ae %ill update t!e "ie% %it! t!e follo%ing SQL- 01#2# >&#A N0urrent 6roduct ListO 2S S#L#0 6roduct&.,6roduct7ame,0ategory @15( 6roducts AG#1# .iscontinued\7o SQL Droppin# a Fie? Fou can delete a "ie% %it! t!e .156 >&#A command. SQL D09- F3EW Synta& .156 >&#A "ie%Jname 3V. A!at are t!e differences bet%een tables and "ie%sB 2 table is %!ere you store your data. !e table actually occupies space on dis?. 2 sample table mig!t be t!e #(6L5F## table %!ic! !as t!e columns #(6&., #(6J72(#, and S2L21F. 2 "ie% is a stored query. 2 sample "ie% mig!t loo? li?e t!e follo%ing- 01#2# >&#A empJ"ie% 2S S#L#0 empid,empJname @15( employeeP 7otice t!at in t!e "ie%, & !a"e omitted t!e S2L21F column. Fou can t!en query t!e "ie% similar to t!e follo%ing- S#L#0 S @15( empJ"ie%P 5racle %ill ?no% t!is is a "ie% and automatically re%rite t!e query to return only t!e #(6&. and #(6J72(# columns from t!e #(6L5F## table. >ie%s are used primarily to store a common query in t!e database. Ait!out t!e "ie%, you mig!t !a"e t!e same comple/ query stored in multiple locations in your application code. &f you need to ma?e a c!ange, you %ould !a"e to c!ange t!e query in all locations. Go%e"er, if t!at query %ere in a "ie%, you %ould only !a"e to c!ange it in one location. !e ot!er common reason for a "ie% is for security purposes. &f & grant a user t!e ability to query #(6J>&#A and t!ey do not !a"e permissions to query t!e #(6L5F## table, t!en t!ey could ne"er see t!e S2L21F column. 3D. SQL 3ne& &nde/ in sql is created on e/isting tables to retrie"e t!e ro%s quic?ly. A!en t!ere are t!ousands of records in a table, retrie"ing information %ill ta?e a long time. !erefore inde/es are created on columns %!ic! are accessed frequently, so t!at t!e information can be retrie"ed quic?ly. &nde/es can be created on a single column or a group of columns. A!en a inde/ is created, it first sorts t!e data and t!en it assigns a 15A&. for eac! ro%. Synta& to "reate 3ne&' 01#2# &7.#; inde/Jname 57 tableJname (columnJname1,columnJname2...)P Synta& to "reate SQL unique 3ne&' 01#2# $7&Q$# &7.#; inde/Jname 57 tableJname (columnJname1,columnJname2...)P index_name is t!e name of t!e &7.#;. table_name is t!e name of t!e table to %!ic! t!e inde/ed column belongs. column_name1, column_name2.. is t!e list of columns %!ic! ma?e up t!e &7.#;. &n 5racle t!ere are t%o types of SQL inde/ namely, implicit and e/plicit. 3mpli"it 3ne&es' !ey are created %!en a column is e/plicity defined %it! 61&(21F <#F, $7&Q$# <#F 0onstraint. E&pli"it 3ne&es' !ey are created using t!e Qcreate inde/.. Q synta/. )9TE' 1% #"en t!oug! sql inde/es are created to access t!e ro%s in t!e table quic?ly, t!ey slo% do%n .(L operations li?e &7S#1, $6.2#, .#L## on t!e table, because t!e inde/es and tables bot! are updated along %!en a .(L operation is performed. So use inde/es only on columns %!ic! are used to searc! t!e table frequently. 2% &s is not required to create inde/es on table %!ic! !a"e less data. 3% &n oracle database you can define up to si/teen (1W) columns in an &7.#;. +K. Whar is an ine&? What are the types of ine&es? Eo? many "lustere ine&es "an <e "reate on a ta<le? 3 "reate a separate ine& on ea"h "olumn of a ta<le. ?hat are the a/anta#es an isa/anta#es of this approa"h? &nde/es in SQL Ser"er are similar to t!e inde/es in boo?s. !ey !elp SQL Ser"er retrie"e t!e data quic?er. 3ne&es are of t?o types. 0lustered inde/es and non3clustered inde/es. A!en you craete a clustered inde/ on a table, all t!e ro%s in t!e table are stored in t!e order of t!e clustered inde/ ?ey. So, t!ere can be only one clustered inde/ per table. 7on3clustered inde/es !a"e t!eir o%n storage separate from t!e table data storage. 7on3clustered inde/es are stored as '3tree structures (so do clustered inde/es), %it! t!e leaf le"el nodes !a"ing t!e inde/ ?ey and it=s ro% locater. !e ro% located could be t!e 1&. or t!e 0lustered inde/ ?ey, depending up on t!e absence or presence of clustered inde/ on t!e table. &f you create an inde/ on eac! column of a table, it impro"es t!e query performance, as t!e query optimizer can c!oose from all t!e e/isting inde/es to come up %it! an efficient e/ecution plan. 2t t!e same t ime, data modification operations (suc! as &7S#1, $6.2#, .#L##) %ill become slo%, as e"ery time data c!anges in t!e table, all t!e inde/es need to be updated. 2not!er disad"antage is t!at, inde/es need dis? space, t!e more inde/es you !a"e, more dis? space is used. +1Why is a ;)39) 1LL faster than a ;)39)? $7&57 2LL faster t!an a $7&57 because for union operation ser"er needs to remo"e t!e duplicate "alues but for union all its not. !ats %!y t!e $75&7 2LL is fater t!an $7&57 5peration. &t is recommended t!at if you ?no% t!at t!e union set operation ne"er returns duplicate "alues t!an you must use $7&57 2LL instead of $7&57. Eo? many types of ata moels are there? !ere are no standards in t!is area. 2ut!ors and t!eorists ma?e it up as t!ey go. !e entity3relations!ip model (#1) !as !undreds of deri"iti"es (bac!man, c!en, ibm, &.#@1/ etc.). t!e most popular of t!e 55 models is $nified (odeling Language ($(L). 2ctually $(L and &.#@1/ are closest to becoming a standard t!at can support soft%are products. 1ational already !as products and &.#@1/ is t!e language of #1%in. .on=t be fooled by t!ese "ariations. !ey all represent t!e same t!ings, you !a"e to be "ery careful t!at you understand all of t!e non3 standard symbols or you %ill surely ma?e mista?es in interpreting %!at t!e pictures mean. What is enormali*ation an ?hen ?oul you #o for it? 2s t!e name indicates, denormalization is t!e re"erse process of normalization. &t=s t!e controlled introduction of redundancy in to t!e database design. &t !elps impro"e t!e query performance as t!e number of 4oins could be reduced. WhatOs the ifferen"e <et?een a primary :ey an a unique :ey? 'ot! primary ?ey and unique enforce uniqueness of t!e column on %!ic! t!ey are defined. 'ut by default primary ?ey creates a clustered inde/ on t!e column, %!ere are unique creates a nonclustered inde/ by default. 2not!er ma4or difference is t!at, primary ?ey doesn=t allo% 7$LLs, but unique ?ey allo%s one 7$LL only. Define "aniate :ey, alternate :ey, "omposite :ey. 2 candidate ?ey is one t!at can identify eac! ro% of a table uniquely. 8enerally a candidate ?ey becomes t!e primary ?ey of t!e table. &f t!e table !as more t!an one candidate ?ey, one of t!em %ill become t!e primary ?ey, and t!e rest are called alternate ?eys. 2 ?ey formed by combining at least t%o or more columns is called composite ?ey. What are efaults? 3s there a "olumn to ?hi"h a efault "anOt <e <oun? 2 default is a "alue t!at %ill be used by a column, if no "alue is supplied to t!at column %!ile inserting data. &.#7&F columns and timestamp columns can=t !a"e defaults bound to t!em. See 01#2# .#@$2L in boo?s online. Whar is an ine&? What are the types of ine&es? Eo? many "lustere ine&es "an <e "reate on a ta<le? 3 "reate a separate ine& on ea"h "olumn of a ta<le. ?hat are the a/anta#es an isa/anta#es of this approa"h? &nde/es in SQL Ser"er are similar to t!e inde/es in boo?s. !ey !elp SQL Ser"er retrie"e t!e data quic?er. 3ne&es are of t?o types. 0lustered inde/es and non3clustered inde/es. A!en you craete a clustered inde/ on a table, all t!e ro%s in t!e table are stored in t!e order of t!e clustered inde/ ?ey. So, t!ere can be only one clustered inde/ per table. 7on3clustered inde/es !a"e t!eir o%n storage separate from t!e table data storage. 7on3clustered inde/es are stored as '3tree structures (so do clustered inde/es), %it! t!e leaf le"el nodes !a"ing t!e inde/ ?ey and it=s ro% locater. !e ro% located could be t!e 1&. or t!e 0lustered inde/ ?ey, depending up on t!e absence or presence of clustered inde/ on t!e table. &f you create an inde/ on eac! column of a table, it impro"es t!e query performance, as t!e query optimizer can c!oose from all t!e e/isting inde/es to come up %it! an efficient e/ecution plan. 2t t!e same t ime, data modification operations (suc! as &7S#1, $6.2#, .#L##) %ill become slo%, as e"ery time data c!anges in t!e table, all t!e inde/es need to be updated. 2not!er disad"antage is t!at, inde/es need dis? space, t!e more inde/es you !a"e, more dis? space is used. What are "ursors? E&plain ifferent types of "ursors. What are the isa/anta#es of "ursors? Eo? "an you a/oi "ursors? 0ursors allo% ro%3by3ro% prcessing of t!e resultsets. ypes of cursors- Stati", Dynami", +or?arBonly, .eysetBri/en. See boo?s online for more information. Disa/anta#es of "ursors' #ac! time you fetc! a ro% from t!e cursor, it results in a net%or? roundtrip, %!ere as a normal S#L#0 query ma?es only one ro%undtrip, !o%e"er large t!e resultset is. 0ursors are also costly because t!ey require more resources and temporary storage (results in more &5 operations). @urt!ere, t!ere are restrictions on t!e S#L#0 statements t!at can be used %it! some types of cursors. (ost of t!e times, set based operations can be used instead of cursors. Gere is an e/ample- &f you !a"e to gi"e a flat !i?e to your employees using t!e follo%ing criteria- Salary bet%een 3KKKK and +KKKK 33 ,KKK !i?e Salary bet%een +KKKK and ,,KKK 33 *KKK !i?e Salary bet%een ,,KKK and W,KKK 33 )KKK !i?e &n t!is situation many de"elopers tend to use a cursor, determine eac! employee=s salary and update !is salary according to t!e abo"e formula. 'ut t!e same can be ac!ie"ed by multiple update statements or can be combined in a single $6.2# statement as s!o%n belo%- $6.2# tblJemp S# salary \ 02S# AG#7 salary '#A##7 3KKKK 27. +KKKK G#7 salary X ,KKK AG#7 salary '#A##7 +KKKK 27. ,,KKK G#7 salary X *KKK AG#7 salary '#A##7 ,,KKK 27. W,KKK G#7 salary X 1KKKK #7.
2not!er situation in %!ic! de"elopers tend to use cursors- Fou need to call a stored procedure %!en a column in a particular ro% meets certain condition. Fou don=t !a"e to use cursors for t!is. !is can be ac!ie"ed using AG&L# loop, as long as t!ere is a unique ?ey to identify eac! ro%. @or e/amples of using AG&L# loop for ro% by ro% processing, What is a Noin an e&plain ifferent types of Noins? :oins are used in queries to e/plain !o% different tables are related. :oins also let you select data from a table depending upon data from anot!er table. ypes of 4oins- &77#1 :5&7s, 5$#1 :5&7s, 015SS :5&7s. 5$#1 :5&7s are furt!er classified as L#@ 5$#1 :5&7S, 1&8G 5$#1 :5&7S and @$LL 5$#1 :5&7S. What is a Store -ro"eure? &ts not!ing but a set of 3SQL statements combined to perform a single tas? of se"eral tas?s. &ts basically li?e a (acro so %!en you in"o?e t!e Stored procedure, you actually run a set of statements. What is the <asi" ifferen"e <et?een "lustere an a nonB "lustere ine&? !e difference is t!at, 0lustered inde/ is unique for any gi"en table and %e can !a"e only one clustered inde/ on a table. !e leaf le"el of a clustered inde/ is t!e actual data and t!e data is resorted in case of clustered inde/. A!ereas in case of non3clustered inde/ t!e leaf le"el is actually a pointer to t!e data in ro%s so %e can !a"e as many non3 clustered inde/es as %e can on t!e db. What are "ursors? Aell cursors !elp us to do an operation on a set of data t!at %e retrei"e by commands suc! as Select columns from table. @or e/ample - &f %e !a"e duplicate records in a table %e can remo"e it by declaring a cursor %!ic! %ould c!ec? t!e records during retrei"al one by one and remo"e ro%s %!ic! !a"e duplicate "alues. Whi"h T!-C3- port oes SQL Ser/er run on? SQL Ser"er runs on port 1+33 but %e can also c!ange it for better security. !an ?e use Trun"ate "omman on a ta<le ?hi"h is referen"e <y +90E3=) .E4? 7o. Ae cannot use runcate command on a table %it! @oreign <ey because of referential integrity. What is the use of D2!! "ommans? .'00 stands for database consistency c!ec?er. Ae use t!ese commands to c!ec? t!e consistency of t!e databases, i.e., maintenance, "alidation tas? and status c!ec?s. What is the ifferen"e <et?een a E1F3)= !L1;SE an a WEE0E !L1;SE? Ga"ing 0lause is basically used only %it! t!e 815$6 'F function in a query. AG#1# 0lause is applied to eac! ro% before t!ey are part of t!e 815$6 'F function in a query. What is a Lin:e Ser/er? Lin?ed Ser"ers is a concept in SQL Ser"er by %!ic! %e can add ot!er SQL Ser"er to a 8roup and query bot! t!e SQL Ser"er dbs using 3 SQL Statements. !an you lin: only other SQL Ser/ers or any ata<ase ser/ers su"h as 9ra"le? Ae can lin? any ser"er pro"ided %e !a"e t!e 5L#3.' pro"ider from (icrosoft to allo% a lin?. @or 5racle %e !a"e a 5L#3.' pro"ider for oracle t!at microsoft pro"ides to add it as a lin?ed ser"er to t!e sql ser"er group. Eo? o you trou<leshoot SQL Ser/er if its runnin# /ery slo?? @irst c!ec? t!e processor and memory usage to see t!at processor is not abo"e VKZ utilization and memory not abo"e +K3+,Z utilization t!en c!ec? t!e dis? utilization using 6erformance (onitor, Secondly, use SQL 6rofiler to c!ec? for t!e users and current SQL acti"ities and 4obs running %!ic! mig!t be a problem. !ird %ould be to run $6.2#JS2&S&0S command to update t!e inde/es. What is lo# shippin#? 0an %e do logs!ipping %it! SQL Ser"er *.K 3 Logs!ipping is a ne% feature of SQL Ser"er 2KKK. Ae s!ould !a"e t%o SQL Ser"er 3 #nterprise #ditions. @rom #nterprise (anager %e can configure t!e logs!ipping. &n logs!ipping t!e transactional log file from one ser"er is automatically updated into t!e bac?up database on t!e ot!er ser"er. &f one ser"er fails, t!e ot!er ser"er %ill !a"e t!e same db and %e can use t!is as t!e .1 (disaster reco"ery) plan. Let us say the SQL Ser/er "rashe an you are re<uilin# the ata<ases in"luin# the master ata<ase ?hat pro"eure to you follo?? @or restoring t!e master db %e !a"e to stop t!e SQL Ser"er first and t!en from command line %e can type SQLS#1>#1 .m %!ic! %ill basically bring it into t!e maintenance mode after %!ic! %e can restore t!e master db. What is 2!-? When o ?e use it? 'ul?0opy is a tool used to copy !uge amount of data from tables and "ie%s. 'ut it %onCt copy t!e structures of t!e same. What is the ifferen"e <et?een ora"le,sql an sql ser/er B 5racle is based on 1.'(S. SQL is Structured Query Language. SQL Ser"er is anot!er tool for 1.'(S pro"ided by (icroSoft. ?hy you nee ine&in# ? ?here that is stroe an ?hat you mean <y s"hema o<Ne"t? +or ?hat purpose ?e are usin# /ie?? Ae cant create an &nde/ on &nde/.. &nde/ is stoed in userJinde/ table.#"ery ob4ect t!at !as been created on Sc!ema is Sc!ema 5b4ect li?e able,>ie% etc.&f %e %ant to s!are t!e particular data to "arious users %e !a"e to use t!e "irtual table for t!e 'ase table...So t!t is a "ie%. inde/ing is used for faster searc! or to retrie"e data faster from "arious table. Sc!ema containing set of tables, basically sc!ema means logical separation of t!e database. >ie% is crated for faster retrie"al of data. &t=s customized "irtual table. %e can create a single "ie% of multiple tables. 5nly t!e dra%bac? is.."ie% needs to be get refres!ed for retrie"ing updated data. Differen"e <et?een Store -ro"eure an Tri##er? %e can call stored procedure e/plicitly. but trigger is automatically in"o?ed %!en t!e action defined in trigger is done. e/- create trigger after &nsert on t!is trigger in"o?ed after %e insert somet!ing on t!at table. Stored procedure can=t be inacti"e but trigger can be &nacti"e. riggers are used to initiate a particular acti"ity after fulfilling certain condition.&t need to define and can be enable and disable according to need. What is the a/anta#e to use tri##er in your -L? riggers are fired implicitly on t!e tables9"ie%s on %!ic! t!ey are created. !ere are "arious ad"antages of using a trigger. Some of t!em are- Suppose %e need to "alidate a .(L statement(insert9$pdate9.elete) t!at modifies a table t!en %e can %rite a trigger on t!e table t!at gets fired implicitly %!ene"er .(L statement is e/ecuted on t!at table. 2not!er reason of using triggers can be for automatic updation of one or more tables %!ene"er a .(L9..L statement is e/ecuted for t!e table on %!ic! t!e trigger is created. riggers can be used to enforce constraints. @or eg - 2ny insert9update9 .elete statements s!ould not be allo%ed on a particular table after office !ours. @or enforcing t!is constraint riggers s!ould be used. riggers can be used to publis! information about database e"ents to subscribers. .atabase e"ent can be a system e"ent li?e .atabase startup or s!utdo%n or it can be a user e"en li?e $ser loggin in or user logoff. What the ifferen"e <et?een ;)39) an ;)39)1LL? $nion %ill remo"e t!e duplicate ro%s from t!e result set %!ile $nion all does=nt. What is the ifferen"e <et?een T0;)!1TE an DELETE "ommans? 'ot! %ill result in deleting all t!e ro%s in t!e table .1$702# call cannot be rolled bac? as it is a ..L command and all memory space for t!at table is released bac? to t!e ser"er. 1$702# is muc! faster.A!ereas .#L## call is an .(L command and can be rolled bac?. Whi"h system ta<le "ontains information on "onstraints on all the ta<les "reate ? yes, $S#1J057S12&7S, system table contains information on constraints on all t!e tables created E&plain normali*ation ? 7ormalisation means refining t!e redundancy and maintain stablisation. t!ere are four types of normalisation - first normal forms, second normal forms, t!ird normal forms and fourt! 7ormal forms. Eo? to fin out the ata<ase name from SQLJ-L;S "omman prompt? Select S from globalJnameP !is %ill gi"e t!e datbase name %!ic! u r currently connected to..... What is the ifferen"e <et?een SQL an SQL Ser/er ? SQLSer/er is an 1.'(S 4ust li?e oracle,.'2 from (icrosoft %!ereas Stru"ture Query Lan#ua#e $SQL%, pronounced QsequelQ, is a language t!at pro"ides an interface to relational database systems. &t %as de"eloped by &'( in t!e 1)*Ks for use in System 1. SQL is a de facto standard, as %ell as an &S5 and 27S& standard. SQL is used to perform "arious operations on 1.'(S. What is iffren"e <et?een !oBrelate su< query an neste su< query? !orrelate su<query runs once for eac! ro% selected by t!e outer query. &t contains a reference to a "alue from t!e ro% selected by t!e outer query. )este su<query runs only once for t!e entire nesting (outer) query. &t does not contain any reference to t!e outer query ro%. @or e/ample, !orrelate Su<query' select e1.empname, e1.basicsal, e1.deptno from emp e1 %!ere e1.basicsal \ (select ma/(basicsal) from emp e2 %!ere e2.deptno \ e1.deptno) )este Su<query' select empname, basicsal, deptno from emp %!ere (deptno, basicsal) in (select deptno, ma/(basicsal) from emp group by deptno) WE1T 9-E01T90 -E0+90MS -1TTE0) M1T!E3)=? 6attern matc!ing operator is L&<# and it !as to used %it! t%o attributes 1. Z and 2. J ( underscore ) Z means matc!es zero or more c!aracters and under score means mat!ing e/actly one c!aracter 1%What is ifferen"e <et?een 9ra"le an MS 1""ess? 2% What are isa/anta#es in 9ra"le an MS 1""ess? 3% What are feratures@a/anta#es in 9ra"le an MS 1""ess? 5racle=s features for distributed transactions, materialized "ie%s and replication are not a"ailable %it! (S 2ccess. !ese features enable 5racle to efficiently store data for multinational companies across t!e globe. 2lso t!ese features increase scalability of applications based on 5racle. What is ata<ase? 2 database is a collection of data t!at is organized so t!at itscontents can easily be accessed, managed and updated. open t!is url - !ttp-99%%%.%ebopedia.com9#1(9d9database.!tml What is "luster."luster ine& an non "luster ine& ? 0lustered &nde/-3 2 0lustered inde/ is a special type of inde/ t!at reorders t!e %ay records in t!e table are p!ysically stored. !erefore table may !a"e only one clustered inde/.7on30lustered &nde/-3 2 7on30lustered inde/ is a special type of inde/ in %!ic! t!e logical order of t!e inde/ does not matc! t!e p!ysical stored order of t!e ro%s in t!e dis?. !e leaf nodes of a non3clustered inde/ does not consists of t!e data pages. instead t!e leaf node contains inde/ ro%s. Eo? "an i hie a parti"ular ta<le name of our s"hema? you can !ide t!e table name by creating synonyms. e.g) you can create a synonym y for table / create synonym y for /P What is ifferen"e <et?een D2MS an 0D2MS? !e main difference of .'(S M 1.'(S is 1.'(S !a"e 7ormalization. 7ormalization means to refining t!e redundant and maintain t!e stablization. t!e .'(S !asn=t normalization concept. What are the a/anta#es an isa/anta#es of primary :ey an forei#n :ey in SQL? -rimary :ey 2d"antages 1) &t is a unique ?ey on %!ic! all t!e ot!er candidate ?eys are functionally dependent .isad"antage 1) !ere can be more t!an one ?eys on %!ic! all t!e ot!er attributes are dependent on. +orei#n .ey 2d"antage 1)&t allo%s refrencing anot!er table using t!e primary ?ey for t!e ot!er table Whi"h ate fun"tion is use to fin the ifferen"e <et?een t?o ates? datediff for #g- select datediff (dd,=23KW32KK*=,=*3KW32KK*=) output is , ,K. Go% many clustered inde/es can be created on a tableB 2 clustered inde/ sorts and stores t!e data ro%s in t!e table based on t!e inde/ ?ey "alues. !erefore only one clustered inde/ can be created on eac! table because t!e data ro%s t!emsel"es can only be sorted in one order. o create a different clustered inde/ on t!e same table, c!ange t!e !reate as !lustere property setting on t!e e/isting clustered inde/ before creating t!e second inde/. ,1. Go% many non clustered inde/es can be created on a tableB Fou can create multiple nonclustered inde/es on a table or inde/ed "ie%. 8enerally, nonclustered inde/es are created to impro"e t!e performance of frequently used queries not co"ered by t!e clustered inde/. 7onclustered inde/es are implemented in t!e follo%ing %ays- 61&(21F <#F and $7&Q$# constraints A!en you create a 61&(21F <#F constraint, a unique clustered inde/ on t!e column or columns is automatically created if a clustered inde/ on t!e table does not already e/ist and you do not specify a unique nonclustered inde/. !e primary ?ey column cannot allo% 7$LL "alues. A!en you create a $7&Q$# constraint, a unique nonclustered inde/ is created to enforce a $7&Q$# constraint by default. Fou can specify a unique clustered inde/ if a clustered inde/ on t!e table does not already e/ist. @or more information, see PRIMARY KEY Constraints and UNIQUE Constraints. &nde/ independent of a constraint 'y default, a nonclustered inde/ is created if clustered is not specified. !e ma/imum number of nonclustered inde/es t!at can be created per table is ))). !is includes any inde/es created by 61&(21F <#F or $7&Q$# constraints, but does not include ;(L or spatial inde/es. 7onclustered inde/ on an inde/ed "ie% 2fter a unique clustered inde/ !as been created on a "ie%, nonclustered inde/es can be created. @or more information, see Creating Indexed Views. ,2. %!at is stored procedure in sql ser"erB (icrosoft SQL Serer pro"ides t!e stored !roced"re mec!anism to simplify t!e database de"elopment process by grouping #ransact$SQL statements into manageable bloc?s. 2enefits of Store -ro"eures A!y s!ould you use stored proceduresB Let=s ta?e a loo? at t!e ?ey benefits of t!is tec!nology- -re"ompile e&e"ution. SQL Ser"er compiles eac! stored procedure once and t!en reutilizes t!e e/ecution plan. !is results in tremendous performance boosts %!en stored procedures are called repeatedly. 0eu"e "lientCser/er traffi". &f net%or? band%idt! is a concern in your en"ironment, you=ll be !appy to learn t!at stored procedures can reduce long SQL %"eries to a single line t!at is transmitted o"er t!e %ire. Effi"ient reuse of "oe an pro#rammin# a<stra"tion. Stored procedures can be used by multiple users and client programs. &f you utilize t!em in a planned manner, you=ll find t!e de"elopment cycle ta?es less time. Enhan"e se"urity "ontrols. Fou can grant users permission to e/ecute a stored procedure independently of underlying ta&'e permissions. Stored procedures are "ery similar to user3defined functions, but t!ere are subtle differences. @or more information, read Co(!aring Stored Proced"res and User$)efined *"nctions. Stru"ture Stored procedures are e/tremely similar to t!e constructs seen in ot!er programming languages. !ey accept data in t!e form of input parameters t!at are specified at e/ecution time. !ese input parameters (if implemented) are utilized in t!e e/ecution of a series of statements t!at produce some result. !is result is returned to t!e calling en"ironment t!roug! t!e use of a recordset, output parameters and a return code. !at may sound li?e a mout!ful, but you=ll find t!at stored procedures are actually quite simple. E&le Let=s ta?e a loo? at a practical e/ample. 2ssume %e !a"e t!e table s!o%n at t!e bottom of t!is page, named &n"entory. !is information is updated in real3time and %are!ouse managers are constantly c!ec?ing t!e le"els of products stored at t!eir %are!ouse and a"ailable for s!ipment. &n t!e past, eac! manager %ould run queries similar to t!e follo%ing- S#L#0 6roduct, Quantity @15( &n"entory AG#1# Aare!ouse \ =@L= !is resulted in "ery inefficient performance at t!e SQL Ser"er. #ac! time a %are!ouse manager e/ecuted t!e query, t!e database ser"er %as forced to recompile t!e query and e/ecute it from scratc!. &t also required t!e %are!ouse manager to !a"e ?no%ledge of SQL and appropriate permissions to access t!e table information. Ae can simplify t!is process t!roug! t!e use of a stored procedure. Let=s create a procedure called spJ8et&n"entory t!at retrie"es t!e in"entory le"els for a gi"en %are!ouse. Gere=s t!e SQL code- 01#2# 6150#.$1# spJ8et&n"entory alocation "arc!ar(1K) 2S S#L#0 6roduct, Quantity @15( &n"entory AG#1# Aare!ouse \ alocation 5ur @lorida %are!ouse manager can t!en access in"entory le"els by issuing t!e command #;#0$# spJ8et&n"entory =@L= !e 7e% For? %are!ouse manager can use t!e same stored procedure to access t!at area=s in"entory. #;#0$# spJ8et&n"entory =7F= 8ranted, t!is is a simple e/ample, but t!e benefits of abstraction can be seen !ere. !e %are!ouse manager does not need to understand SQL or t!e inner %or?ings of t!e procedure. @rom a performance perspecti"e, t!e stored procedure %ill %or? %onders. !e SQL Se"er creates an e/ecution plan once and t!en reutilizes it by plugging in t!e appropriate parameters at e/ecution time. 7o% t!at you="e learned t!e benefits of stored procedures, get out t!ere and use t!em_ ry a fe% e/amples and measure t!e performance en!ancements ac!ie"ed 33 you=ll be amazed_ &n"entory able 3D -rou"t Warehouse Quantity 1+2 8reen beans 7F 1KK 21+ 6eas @L 2KK V2, 0orn 7F 1+K ,12 Lima beans 7F 1VK +)1 omatoes @L VK 3*) Aatermelon @L V, ,1. ypes of Stored 6rocedures !ere are many types of stored procedures a"ailable in (icrosoft SQL Ser"er 2KK,. !is topic briefly describes eac! stored procedure type and includes an e/ample of eac!. User$defined Stored Proced"res Stored procedures are modules or routines t!at encapsulate code for reuse. 2 stored procedure can ta?e input parameters, return tabular or scalar results and messages to t!e client, in"o?e data definition language (..L) and data manipulation language (.(L) statements, and return output parameters. &n SQL Ser"er 2KK,, a stored procedure can be of t%o types- ransact3SQL or 0L1. Transa"tBSQL 2 ransact3SQL stored procedure is a sa"ed collection of ransact3SQL statements t!at can ta?e and return user3supplied parameters. @or e/ample, a stored procedure mig!t contain t!e statements needed to insert a ne% ro% into one or more tables based on information supplied by t!e client application. 5r, t!e stored procedure mig!t return data from t!e database to t!e client application. @or e/ample, an e3commerce Aeb application mig!t use a stored procedure to return information about specific products based on searc! criteria specified by t!e online user. !L0 2 0L1 stored procedure is a reference to a (icrosoft .7# @rame%or? common language runtime (0L1) met!od t!at can ta?e and return user3supplied parameters. !ey are implemented as public, static met!ods on a class in a .7# @rame%or? assembly. @or more information, see 0L1 Stored 6rocedures. Extended Stored Proced"res 3mportant' !is feature %ill be remo"ed in a future "ersion of (icrosoft SQL Ser"er. 2"oid using t!is feature in ne% de"elopment %or?, and plan to modify applications t!at currently use t!is feature. $se CLR Integration instead. #/tended stored procedures let you create your o%n e/ternal routines in a programming language suc! as 0. #/tended stored procedures are .LLs t!at an instance of (icrosoft SQL Ser"er can dynamically load and run. #/tended stored procedures run directly in t!e address space of an instance of SQL Ser"er and are programmed by using t!e SQL Ser"er #/tended Stored 6rocedure 26&. )ote' 0L1 &ntegration pro"ides a more robust and secure alternati"e to %riting e/tended stored procedures. S+ste( Stored Proced"res (any administrati"e acti"ities in SQL Ser"er 2KK, are performed t!roug! a special ?ind of procedure ?no%n as a system stored procedure. @or e/ample, sys.sp5"han#e<o?ner is a system stored procedure. System stored procedures are p!ysically stored in t!e 1esource database and !a"e t!e sp5 prefi/. System stored procedures logically appear in t!e sys sc!ema of e"ery system3 and user3defined database. &n SQL Ser"er 2KK,, 8127, .#7F, and 1#>5<# permissions can be applied to system stored procedures. @or a complete list of system stored procedures, see System Stored 6rocedures (ransact3SQL). SQL Ser"er supports t!e system stored procedures t!at pro"ide an interface from SQL Ser"er to e/ternal programs for "arious maintenance acti"ities. !ese e/tended stored procedures use t!e &p5 prefi/. @or a complete list of e/tended stored procedures, see 8eneral #/tended Stored 6rocedures (ransact3SQL). ,2. &s it possible to pass a parameter in Stored 6rocedureB !ere are t%o %ays to pass parameters to a stored procedure using SQL#/ec. 5ne %ay, %!ic! %or?s across all "ersions of >isual @o/6ro, is to build t!e SQL command as a string "ariable. !e ad"antage of t!is met!od is t!at you can c!ec? t!e string and see e/actly %!ic! SQL command you are passing to t!e bac? end. !e ot!er %ay is to pass t!e @o/pro "ariables preceded %it! question mar?s, as in a parameterized "ie%. &n >isual @o/6ro "ersion ,.K and later "ersions, t!is allo%s you to obtain "alues from t!e stored procedure t!at are being returned as output parameters.