You are on page 1of 42
Sa * SQL stards for Structured Quesy Langucge - x Ser isa Standard language for Storing , Trenipulaking and ~vetrteving data th databases . % S@L commands are classified into five types: They me 1. DDL commands » DML Commands 2 3. DCL Commands 4. TCL commands Ss - DEL commands DDL — Data Definition Languoge DML > Data Mamipuiakion Larnguege BcL + Pata Control Languoge Tel ~~ Transaction Contret Language . DEL ~ Data Quesy Language - SQL commants qt 1 oot | DML \ bei [ tex | eC ea Grant Lcormit | scteck Drop L_ deiele Revoie | t— Rolikack Arter jake. _ upd L_ savopeint Arucralé Table :- A table is an arrangement of dato tn tre forrn Of FNS ard colUMNS - CREATING A TABLE The syntax for creattrg a toble CREATE TABLE Z2TABLENAMGE > ¢ ZCOLUMN-I> DATATYPE , DATATYPE, < COLUMN -N> DATATYPE 4 Eg. CREATE TABLE Student ¢ Rotino Number, Name Vaerchar>(20), Marks Number d . REcoRD INTo TABLE TNISERTING A The Syntax for inserting a record to @ bake is ZTABLENAMED VALUES ( VALUE-I, VAVE-2 INSERT INTO -- .VAWE-N ) : 2 Eg: INSERT INTO Student values( tool, ‘Suresh! +5); ; ? TNSERT . TNSERT INTO Student values ( XRollno, ‘Zrniame' , RMark5). This Command is used to take tmpuk from the Keyboard and Store tt tn a table. UPDATING A RECORD IN A TABLE The Syntax for updating o wetord in a babe is UPDATE ZTABLENAMES SET = VALUE E-g. Updote Student get Marks =80 Where Rolin > Ico! * DELETING A RECORD FROM A TABLE The Syntax for deleting 2 xecord from a EAbe 8. NAME> WHERE DELETE FROM ; Eg- Select * from student 5 RETRIEVING A Specific RECORD FROM A TABLE The Syntax fer vebrfeveng a Specttrc record cnatabie ts SELECT & FROM ZTABLENAME> WHERE DATATYPE * > Eg: ALTER TABLE Student ADD addrass Voomher2{20): DROPPING A CoLuMN FROM A TABLE The Syntax for drepping a colump from a toe & ALTER TABLE DROP COLUMN! ZCOLUMNNAME S e ATER TABLE Stuclent DROP COLUMN addryoss « —_— > MODIFYING THE SIZE OF A COLUMN IN A TABLE The Syntax for rmodifying Ene Size of acelumMD in table is ALTER TABLE 2TABLENAME> MODIFY K£COLUMNNAME D> pataype (NEW SIZE), E-g. ALTER TABLE Student mopiFy addvess Verehara(ho) ADDING A PRIMARY KEY Syntax ALTER TABLE IRBLENAME> ADD CONSTRAINT ZCONSTRAINT NAME> PRIMARY KEY (COLUMN NAME); eg: ALTER TABLE Stuclent APD CONSTRAINT pK _stuclent Prieray Key ¢ Rollo’) 5 DROPPING A PRIMARY KEY 2 Ez = —_ Syntax Name> DROP PRIMARY EEY;- ALTER TABLE 4TABLE ey oF a Aree TABLE student DROP PRIMARY KEY 5 DROPPING A TABLE _——— The syntax for dropping a table iS DRoP TARE
; E-g-. DROP TABLE Student ; > DIFFERENCE BETWEEN DROP AND TRUNCATE The DROP corsmand tS Used to rernove te unde ender ete . The structure of the sobledess Ft eng. database, table, ore all une rd is used to TO exitS mn the Eable . The structure of WS penile the TRUNCATE corer OWS FTO' GRANT COMMAND SSS Tet 16 used to provide access OF pstvéleges on the database object to tre USEYs - Syntax Geant < pRiviLege—-NAME > ON 2 OBJECT - NAME > < USER-NAME 7 5 GRANT SevecT on STUDENT To KIRAN RevonE COMMAND nadie een Tk vemeves UseT access vightS or privileges on the database objects Symtax > - REVOKE = Z PRIVILEGE_NAME > ON ZOBIECT_NAME > FRON ZUSER-NAME> 5 E-g- REVOKE CREATE TABLE FRON KIRAN 5, COMMIT COMMAND * - qhe commit command is Used Eo Save chargs imvoked by a transaction to the datahase. E-g- COMMIT RoLLBACK coMMAND , _ _ qhe ~vollback Command © used to undo raNSackOrg nat have not been Savad to tno dattabaga - Eg: RoLBACT SAVE PONT Tk tS used to create a nen Save pornt Syntax: - SAVEPOINT 45 GRove BY clause Te ts used to arrange Stmtlay data CNto group. Syntax: SELECT COLUMN-1, COLUNN~2 FRON
GRovp BY COLUMN-I 4 eg: — erect sum( Sac FROM EMPLOYEE Grove BY ——dDEPTNO', ORDER BY clause Tt tS used to Sov— Ene data tn a column aither iy ascending order or desconceng ordev . Syntax: - SELECT COLUMN -|! FROM AS SELECT COLUMN, COLUMN-2 FROM = WHERE CoNnDITION eg: CReaTe VIEW vi AS Ssevect CNAME, cNo ' ROM CUSTOMER WHERE — county ='Irdia! » Disploving the yecords in a vow Eg. Select * from wie A View cern be updated) lwtth the CREATE OR REPLACE VIEW Statement . Dropping a view A vtew ts deleted with the DRoP VIEW Statement Era, Deon Views Vit > ? Types of views VieWS ave of two types: They ave: \- Simple view Q- Complex view Simple view Complex view It %% created from \- Te tS created from Move onty one table than one tobe. a. We canrot use 2. We can use group tunctrons group functions like minl), mort), angl ) like mail), countl ) Sum) ete. etc ‘ 3. DML Operations can 3- DML operations canmot ke be performed Pestormed, WH. Tk cannot contain Lye Tt can Ccomraryn. not Du |) Not Mull COLUMNS Columns from bom tabs. Aron base tables Jotns A Join is a birary operator which allows 0 combine cartesian product awd Selection in one Single Stakement , The purpose of creating o jet ts to combire the data . from two or more tobles - There ave mainly two types OF jotns They He 1. Inner Jotn Q- outer Join. Taner Jotn is classified tnto three EYPES- 1. Theta Jota 2. Gaur Joon 3- Natural Join. Outer Join %s classified into three types 1. Left outer Jotn Q. Réght euber Tot - 3. Fun outer Jorn . Fheta Toto + ab avons us Eo join tio tables based] on the condition represented bY ‘teneta Tk tg denoted by the Sysbol v5 TE work for all Comparison Operators <,>,<5,2 et: Equi Jotn : - Tf} the operator Used im theta jow vestrickad to only equality eperatoY Lpon TE CS Kron as Goysi joe Natuyal Join :- In this type of jofn, there should be atleast one Commen attribute between tWo TeEAETONs - The aterxtbutes Should have the same name and dorman, Tt is a Variation of Equtt Jou Cuter JotM :— any thts type of jot, the table vetains each vecord even tt mo c&ner renee rrecore| exrets - Lefe outer Join ,_ Tt veturns all the xecords from Ene Latble on the left oven tt no matching yecords have been found an the tebe on Ene seght » When TO orctehtng, xecord ts found im the ble OM LENE wight , NULL [Ss Tetundd]. a 8 Right Outer Jorn :- Tb returns all the records from ENC OO table on the wight even if 1 machong mecords have been found tm the ttd!e@ A 8 Ow the lett: When HO mmateneng YeCord tS found in the tabie on tno left , NULL & yebuTnad - Select *% from Customer left cuter jotn ordey bett outer Jotn . — Om Customer: custid = order. CUStd + Aanpobueq | TAO ‘ugawang | bao] nanyeGseq | XJod (uous tt 200) Sh kacactr | SOE nanibuesq | Guus yseay <00) ost eefaung | TOK penybueq | Zax Us ot ose ozzjd | IK ranwGusg | ZAK poet loo a ee easn> MS SAD [wororo pirspro (AtDISND Reght outer Jot) Select % from customer +igitt outer jr oe On cuotemer-ciigtd = oxder - tustid > ~Sa0(} ass | eaRar wa] hot . . Seq} | ase [owrrenott gor | mnyehieq uu si Iaay sq were | =Oe nanypGseq ZAK yseurd 101 taal] OSf veesd Lor panyobseq ? esaane > Select * from Customer full outer Pin Odo, OD Customer -custid = exder- custid Furl Outer Tous, saot ass Barouant vol 7 + nantobusq ome |Uoume | +001 panebueq Blkod qquowey | TOa| ost | axvkauey| 20x | nanrebueq OG, 4svAao S29] O01 seu \a0| too} sce acbang | cok | mnyoGusq | Prasns Purspro “pasno | Bou p.o | areas : 1 Full Outer Joto :- Tw a Full duter Join, all records from both Yalaktons axe tncluded tn tre vesutt, trve spective of the matching Condutton - a BR Custname custaddress custcity 1001 pinesh AY2 Berngalury \oo2r Hermantn Pay Bengalun 1003 Akash 00 Benga co - Surmnacoeth abe Bengaluru ovdexttom pizza Burger Honeycake plumcake Natuval Jote — Select & from Customer inner join oxdes 2 OM Customer. custid = Order.custid + 8aa| fa) ash ago, cok pantobueg cau usa \o01 lao! Jose | eaiing | cok funieusq ZeK a = lag, {OSE vezd | (A | ranyoSueq ZAK ysowr apo jarsqpop |ppaspxo re ar aw ougsn? | paasno pusn> v String functions tn SeL- es SNo Function — char —length ¢ >) Concatt > Aeasel > Ucoase lowes CD Upper 6) Qeteney atstml > Description —_—_———_—- Returns the enuanber of Characters In the J wen Stwong Returns the comeab] notice, Of tO SETUNgS Returns the lowercase Characters oF the guven Sesing Returning the given cestng dy Uppercase . Returning the give stating TD lower case Returns Ene given string bm Upper cace | Returns the Stxtng atter ernoving leading space, im the given stetng Rewiomns the strting atloy Bermorng 4rallltang Spaces, un the given String | S-No Function aoe xi) weverse () Bkxemp C9 tmotr C7 locate (> bent oct l) heal) Desertpicn | oo Returns the sting ater werroving leading ond Aeraing Rebmne the Yeverse of the given string Compares two StrtogS = m1 are) returns etter Returns the posteior of the frre OCCUTT ANS on bho substring to mningsuy, Returns the Pesttton a tne first eceurrance Sf the substring ty mamnesing, Sen Returns a Bunce Tepresen~ tatCon of the binany value. Returns a String veprecen = Lartton O} the octel VQ\u9 Returns a String Tepreseo ~ tattoney une hexadecimal Valuo. Recursive Queries Recension tS tmplemented to SEL using conten table expressions ( CTE )- server, Oracle ancl Postgre AL DB2, Microsoft SQL Support Yecursive quest es using CIES. oS HR CTE Stands for Common Table Expresslon . Zt % a temporary named vesuik set ENat com te ¥efervencec| Within a SELECT, TNseRt, VPPAIE ov DELETE Statement - cowry A CIE t6 a warmed tempor Tesult Set that exishS lwithin the Scope OF A songle Statement and that Can be veferved to lates Within tnat Staternent, possibly wonuttiple tomes - To Spectty common table expresetons , Use a world dates bnat hae one oF THOKE COMMA -Separaléd suUbclaugas eg: with Cte! ag (Select a,b fron table!) , eter a6 ( Select c, d from toble2 ) Select b,d from ctei jotm cker Where Ctel-a = ckeraec Recursive Common Table Expressions A recursive common table expreseto % one having a subquesy that refers Eo TES CWP ame . WiTd Recursive cte(m) AS ¢ SELECT 1 UNION ALL Seuect mtl FROM cte WHERE 45° Beiect % from cte, output wn F “(| The recursive Select past amnust Mok CON 1. AGGeEgaTe FUNCTIONGUM ) &. GRouP BY B- oRDER BY 4 DISTINCT am those corsbuss, Tetggers A trigger defines a set of actions brat ove performed when an event occuvs i a datatace - Advantages Enforcing complex business vUles that camnot be established using integrity constraints # preventing imvalid transacttons % Gathering Statistica! Emformatlom OD table accesses » * Generattng value automatically for derived Columns % Auditing sensitive data . tfted into tree bYpes : TypeS of Triggers triggers co be clase’ 1. Lever Treggers a. Event Trrggers 3. ening Trtagexs - Level Tréggers :~ joaee ee they ate of to types: ThoY axe |. Row level kevtggovs Q+ Statement pevel Esrg gers - Ron level triggers % Tt fires for evesy vecord that got affectect with Ehe execution of DML statements ke INSERT, DELETE AND UPDATE * It alwoys use a FOR EACH Row clauw in d triggering statement Statement level triggers K Ib ftves once for each Statement tra i6 execttec] Event triggers qhere are three type Of event briggeys . 1. DOL Event trtages aS SS at fires with the execution of EVEN por stalerent ( crente, ATER, peop, TRUNCATE > Q. DML Event tntg ges — Te fives wrth the executton Of every pMLstalensnt Cansert, DELETE, UPDATE ) 3. Database event txegge’ Te fires With the execubton oF evetY dortorkerse operation which can be LOGON, LOGOFF, SHUTDOWN | SERVERERROR eke, Timing triggers there are two types of temtog txtggeté + 1. Before tregger It fires before executing DML statement » Q. After extggex = Tt fives after executt Tg DML Statemont Syntax for Creating a trigger CREATE OR REPLACE TRIGGER < trigger-—name> Berore | arTeR | INSTEAD OF INSERT | pevete | UPDATE ON REFERENCING (OLD AS oO, NEW AS N) FoR EACH ROW WHEN (test _condition ) DECLARE -- yartable declaratton >, BEGIN —- Executable SeAreoMments |, EXCEPTION error Handteng BEAEIMANE, END ; ENP, CREATE oR REPLACE TRIGGER Checkge BeroRe TNSERT OR UPDATE ON Student | foR EACH Row Bean ar pnen-age > 30 THEN rratse_appltcation_evier (~ 26001, ‘age shouted net, | 1 Arar - be greater tran 30 ) 2 END IP 5 ENP, Embedded SoL The S@L Stamdand defines exrnbecidiings 4 SPL ty a Variety Of progrormmning targuages Such as c, eva etc. A l\omguage im whrteb S@u ayuertes ane ernbedda} iS Yeferved to ag a host larguage . Aw embedded Soy! program must be proeeed Px 2, : by a Spectar processor prtor to compilation . n the preprocessor weplaces embedded SHLeuests With host-lanquege declayattons and procedure cans that allow yun-time executienat the database accesses - \ EXEC SOL! statement fs used to tdentety embedded Ss@i Stataments. exec SQL Stalement -| 7 ‘ Staterment ~p; END~ exec Before executing any SQL statements, the pregram aust first connect to the catabse . This ia done using Exec S@L Commect to sower User USex -MOn@ END-EXEC Reve Bevvex identifies the Sewes to whee a coonsctitry ts to be estabuished . User-name vopors to the User NARMS trraugh Which a Uses TS Comeacted. A dotabase moditicatton reoywest Lakes © torr Exec SQL < tmsert ,delele ov update > END ~ ExEc - Verfabies com be declaved in the heast-largume Ustnaq the reg Fotiacrng synto: EXEC SQL BEGIN DECLARE SECTION ExES S@i_ Ens pectARe SECTDN. bg Exec Sat BEGIN DECLARE SECTION char ¢_smame[20} lon, ¢_9tdy Shovt c_wattng; float ¢-age’, Exec S@L END DECLARE SECTION. Exceptions The SQt- 42 Shorndond Tecegniaes tu00 Speaatl Varriables for SEPOTtTOH ores - 1. SQUODE Q--S@L STATE SBQUCODE :~ “ne Tk ig defined: to return Somme MEgawe Vala When an error condition arises twttnout specttytng tonal over A particulat magative cnbeger dorky SQLETA TE asecciates predefined vans wet). BONOXAI cormmmon error comtierang Statemoms Embedding St _ ———_——_ statements Must be prefixed by Exec BL- tw a host language - QL when © mbedded Eg so Exec SRL E gatlort Valves (.¢-snaee, 1C.sid, Insert o £0 att" , a cag). The SQLstAre vartable sourd be checnad 1o5 Exec SQL WHENEVER: cE BP (8. Explain atout DB pynarte SQ meee Sele SQL Dynamic sQru isa progremmtng eanniqe tat ones Autry TUNE | could be used .to vorwte SQ YU jo wma yrarenic RL statement, TU the stocc) procedue SPL execute Sy! ag shaxn below’. . 5 Exec sp_execulesy! N guesy eftx No with the SP. execute sey EO LSE unicade Stet - Use pr dywmarmic -SQ@L as oO Steps to use Dynaric SQL: - 1. Declare two vortables, @ Vos! for reiderg 2 [ mame of ene table and @ vex to Fading the dynamic SQL * DEcLARE @Vorst NVARCHAR (AX) | @ vou: NvARCHAR( waa) 3 Q- Set the valuo of the @ vel Variable to *9ble rg: SET @Vaxl = Ni ‘table_rare!: 2 spz- B. Create tre dyno i Seaterbdhl Eo? EN@rtable MaaHS ser @var = Eni‘ serect # FROM ‘te alls SQL by 28g tne SELECT porranctor > A. Rum the spexeculesy! @ V5 E-g. DECLARE @tab RIVARCHAR( 128) ee RIVARCHAR( 200) 5 \ I Ser @wb=N Earplsee > 1 i ye FROM + @S; Ser @ a= n'serect * exec Sp_excculépyl@ St ', DBMS gang fo 9901 AoAhwounid GO ISP ] xoper FO QoRnowwate;y oesoa prook A QAO anaM [pron € Axo xerduscoo TSAI IE ee 8 DEAGusUTPA NW * exons Jarno aeis' peered aid 5 - “peg opssU.a | PITRGHUANS papereP- AUGu akraasd BI SONO 5 sere Ff aseuass ApOANTe© 6 \HOBAS ear dn PaaqUeELen (qUueLLND pequsvo j oaks | aroiforss | was wommemddy ‘peseq 3a 3 Fags ASPET ‘sqUSWasaNeSs yowomn fog xs29-Buo71 guoRaede Koa-o3- Ko youmesatord RSA20™ SBpaIMORA Saeaerea (wea sete oeiewy BONP eS ROLL Bnssarcd ousHounoper pitferentiate be Bussszod uc @ “ve dino guowssedo net gsen0y spo fe MRA Maw BQYORALOWAN EG wQ0d efrsed s809e70d wound 223) GOHOA{4eHO DASIAS7D ELEY. area @ Feature Number of records accessec| Number of users Dotatbase Size prcostly Merric thousends loo MB to GB high petforrran® » high avatiabitty Anomnsaction Abroughput CLAP amiltéons hundred s. loo GB to TB high Ftloxeotlity ouery through put , response ten, Explain about_OLAP operations Explatn ceo 0 % OLAP stands -for Online Analytical Processing OLAP provides a usger- frierAly SOVETOMMONE FOr moteractive data amnalyss - 3e OLAP cam be performed to data Worrehousss | dota monte Ustng the Muitidimen sional data wracto J %& Typical OLAP operations tmetude Roll -UP 4 oxtll-trsaugh x% %& pi-down a Ramkfng sie and die x pcvot % Drill-acoss Roli-up operation =~ — aL te aldo Kmoion gS Brill -UP eporattion Ik performs aggregation on a data cube, efthes by Climbing up 4 concept hterarchy fora a domensi os by demension redUctt™s - Dritl- down operatton- ee ie ate ts the TeVOTSO OF Roll -up eparawoy) TL mavigates form lee6 detaitad data to move detatlod data - -dovan can be realized by etther Stopping Dit! dove & corcept peevarchy +or A deepondon OF tNbead\UIN"™ adaittenal dimmerdiong . 8 MR Slee - awd -dice operattesy the Slice cperatiown perforrns a SeleCtton oD one dimension oF the guen Cube ,7e6ut bony 6D a Subeuke the dice operation defines a gubcuts by pespoeming 4 GelecttoH on toe Os WOT Ai'MOOSHS * pivot operation pel cheeses gE is a Visualization Operation that torates tho 2ew tnordey EO provide am aiternatt VO X% Drill- acreoS operation Lo the drtli-across executes ayusvins ENAVED wore thom ore fact table Drill — through epeTvakrom a the drill-trrougr operation aAOKAS US FH melatiora) SQb facdkLos tO arti through tne bottom levo} back-4M Toratcena) -tablag eta data cure down to tte ONIT-L ( Questions from previous Papers \) (1) (a) Diecuss about outer join With examples 6) bnite a short note on triggers 2) Explatn about get comparicon operators , ogPegote operators Lotth exampe - (Bye) Show tnat, t SRL, <>au és fdentical to Not In tb) Write the following quertes tm S@L using tre university Exnema * uy Create a mew course “cs-coi"” tttied w seckly Semiray” with o credits (i Create a section of this course In Autumn Dect OLEH Sec id of 1 itty Emre every Student to the computer sctence deparrersent tn the above sectton. (Wv) Deleke enrvoiments in the above section Where Eno Student's naune fs chavez. Konak boil] hexppess tf youTUD et deleting effaxt ys (VY) Delete the course CS-COl- this delete statement Without fie: (gections) of thts COUT . 4) pesertbe helo the theta-jotn operation cam) be extorre¢ Zo that tuples from the left, Fight or both relations TE MOt lost from the wreoutt ofa theta jar. se aTother actter (5) (a) The execution of a trigger can cau place a to be triggered - Most database Systoms Lam’ on how deep the nesting CAD HE > Expiatn hp they wight place such a lomit - a \b) Suppose there ove two welations + and s, Such that the foreign key B of ¥ Telerances the primey Key A ofS: pesertbe how the trigger arrechanie cam be used to tmplemant the on celele cascade optio® , loner a tuple t deleted from S. 16) (a) What is a view t SQL rHow 1S te defined % Explota with an example \b) What are aggregate fUNcHons 2 Lest the aggregate functton® supported by SQL. ch (a) Expiate about Nested queries With an excmple . (b) Write about lagical comnecttves With an ample 8) what ts a foto? Explain about Vortous sypes GPUs - Ww) Diffexentiate Nested tap joro , Hash spi ard Merge jouw, (lo) pieeingutsh between tntegrty constraints and triggers (Wy What io o foreign Key 2 What are the défferent WHS that SQL provides to handle foreign rey viplatrens ) (IQ) Consider a database Witn the following schema + Pexcon ( mame, age, gender’) —name 1S a Koy. me, pizzerta’) where (cneune ,piz2er iS : = ptz2a) where (name, pizza) ig arey ) Pea Freoy nent (7 Eats( mame, pizzeria , pi22a POO) vonena ( PI2zETA serves ( Say z oy, jortla SL euertas for tne folladng, peice gel coe oy feo) mere bony es Fea) under the age of IS i) Feed tre Tames of all fernales who eat etthoy amushrcom or Pepperoni pizza oF both (il, Feed the names of an ferneles who eat beth. woushreorn and pepperont pr2za . (i) fend all pizzeréas that Serve atleast one prz2a Frat Aroy eats less than 410-00

You might also like