Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
42 views
My SQL DDL and DML Syntax and Query
Hello
Uploaded by
vivekkumar6207995548
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save my SQL ddl and dml syntax and query For Later
Download
Save
Save my SQL ddl and dml syntax and query For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
42 views
My SQL DDL and DML Syntax and Query
Hello
Uploaded by
vivekkumar6207995548
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save my SQL ddl and dml syntax and query For Later
Carousel Previous
Carousel Next
Save
Save my SQL ddl and dml syntax and query For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 27
Search
Fullscreen
languages, we do not need to speci ur UNTIKE-OT Pecify how the SQL operations are implemented. Thus, SQL becomes idea database language, so it is widel i i ly used. It efficiently manages large databases, provides f: operating on data and fac , provides fast responses to the queries ate: 'S an authentication mechanism that ensures the security of data. Based on their functionality, SQL operations i / are organised in two categorie: (Data Manipulation Language). Let us study about them. oo eeteae eames pane e SQL: most popular language for creating and manipulating relational databases 10.1.1 Data Definition Language (DDL) Data Definition Language (DDL) is used for describing database structure. It is used to create and delete databases and tables. The attributes of already existing tables can also be added, deleted or modified using DDL statements, also known as DDL commands. Some of the examples of DDL statements are CREATE TABLE, ALTER TABLE, 2nd DROP TABLE. In this chapter, we wi | discuss these in detail. —_ é DDL: used for defining database attributes, their types, and constraints on attribute values structured Query Language (SQL) = ME SE10.1.2 Data Manipulation Lang! a. it includes saver bol enable us ‘Data Manipulation Language (OMt) is use data in 5 tables, store and retrieve information from databe: statements such as INSERT, SELECT, ready stored ‘used for this purpose: taining th © ae totes ream of ves « be used later the data type indicates the domain 0.2 Dats Types the table. antributes of a table describe the data that willbe stored 7 values for an attribute. A data type may be of one of Fane several permissible types: Let us ea"? about some import data types. 10.2.1 Numeric fa rovide rh 4 be used to specify that an attribute can contain numeri™ data, SQL provides Txt Tenet ee ‘prox (p) numeric datatypes: Let us discuss about them INTEGER, SNALLINT, DECIMAL(L, D),and INT or INTEGER lor INTEGER is used for specifying 32-bit integers 1647, For example, f type INT are as follows: ‘The datatype INT ‘Te value that can be stored in the TATE{ 1 datatype cane sore in the data type ranges from ~2147483648 to 2147483 the attribute Sa lary of an employee ma of type INTEGER Some valid and invalid examples of -0 1234 1234567890 34567890 123.45 (digits to the right of the decimal point are truncated) Invalid 1, 23, 456 (punctuation characters not allowed) 29-01-22 (punctuation characters not allowed) ~2147483649 (beyond valid range) 2147483648 (beyond valid range) 98765432100. 1234 (beyond valid range) © 2 ox ran: 2g SMALLINT ‘The datatype SMALLIN is used to store small integers (typical Wy 16-bit SUALLINT data type ranges from ~32768 to 32767. integers). The value that can be so" 332 Touchpad Computer Science-XIlES ESE ADS SRG aS | For example, the attribute Of type SHMLLAINT ae a fone? tM APArIMent may be of ype LEER Some valid and invalid examples valid ° -0 1234 =32768 32767 123.45 (digits to the right of the decimal Invalid Point are truncated) 1,23, 496 (punctuation characters not allowed) =22. (punctuation characters not allowed) 32769 (beyond valid range) 768. (beyond valid range) 7654321.1234 (beyond valid range) \ ABECIMAL ( (L, D) ‘The data type DECIMAL (L, D) is used to denote a fixed-point decimal value. The arguments L and D denote the maximum number of digits and number of digits to the right ofthe decimal point, respectively, For example, attribute ‘ype DECIMAL (6, 2) indicates thatthe attribute values may le inthe interval (2999.99, 9999.99). When the value of an attribute of DECIMAL type lies outside its limits, the effect is system defined. For example, for the attribute type DECIMAL (6,2) , the value 1234.56789 may be rounded to 1234.57 or truncated to 1234.56. if an attribute of DECIMAL type is assigned a value whose integer part has more digits than the permitted, the system may {assign the maximum (or minimum) alowed value. For example, given the DECIMAL (6 ,2) specification, the number 712345 maybe stored as -9999.99, However, MySQL will rise an error and reject the outof-range values if strict ‘SQL mode is enabled. The value that can be stored in the DECIMAL data type ranges from ~3. 4028234662+38 to =1,1754943515-38, Some valid and invalid examples of type DECIMAL. (6,2) are: Valid 1234 se7e9 (rounded to 1234.57) -56789 (rounded to~1234.57) Possible Value (more than four digits in the integer part) 9999.99 12 (more than four digits in the integer part) 9999.99, 678.1 (more than four digits inthe integer part) 9999.99 5.1234 (more than four digits inthe integer part) =9999.99 5678.12 (more than four digits in the integer part) -9999.99, DECIMAL (LD): Fixed point decimal, with total I digits and D digits ater decimal. 2 structured Query Language (SAU)FLOAT (p) ‘The data type FLOAT (p) denotes the float Ti the range 0% 23, denotes a single-precsion (by 1053, W denotes a double-precision (8-byte) floating-point val ‘mentioned below: tes precision. Ifthe value of sat nmpers Te argument p denotes peecson Whe valveot p ra engpovle. Wate vabe ofp 6 in henge hoa pene valid ames of TYPE FLORT (8) arg 123456789 (rounded to 1234.57) 3456789 (rounded to 1234 Ce 10.2.2 Character To store string type data, SQL pr about them. vides CHAR(L) or CHARACTER(L) and VARCHAR (L) datatypes. Let us learn CHAR(L) or CHARACTER(L) The datatype CHAR (z) denotes fixed Length character strings. The argument Z denotes the length ofthe Stang and he dndsed Specs are Filed with blanks For ample, We dedare Bmp_Name of an employee tobe of tYPe CHARIS), then the name string "SMITA KALA’ willbe expanded to "SMITA ALA. Ifthe length ofa string of tye CHAR not Spectod, the default length i 1. f the length ofa string s more than the specified length the taiing characters willbe Teincated, The CHAR data type can store any value from 0 to 255. Next, we give some valid and invalid examples of type CHAR (10) ‘CHAR(10) No of bytes required ‘IIIT Delhit 10 ‘IIT Delhi * 10 ‘ur ' 10 noose 10 *29-01-2022" 10 ‘TTT Kharag" 10 tvalid 110016 not 2 string 29-01-2022 nota string © corns: hesiergh chr sig ten ‘VARCHAR (L) “ie datatype VARCHAR () i used fr specyng variable-length character strings where I. specifies the maximo? length. Unike CHAR, VARCHAR must include a positive integer specifying the maxi Fre se rerjoes not use 2 default value. For example, declaring Emp. Name to be'af type VARCHAR (25) wil we byte more than the length f the string being stored. Thus, the string "IT will equire four bytes of memo"! 334 Touchpad Computer Srience-X!![A string longer than Hf any truncated charact 65,535. Some valid and inva will raise an error T 1 invalid examples of ty ¥-The VARC De VARCHAR (10) are vate VARCHAR (20) sting ny ge Invali : 110036 nota ing 10.2.3 DATE ‘The data fype DATE denotes a date. The standard dat 1 standard date format is YYYY-MM-DD. However, SOL aso permits ot formats like DD_M_YYY¥ for storing and retrieving dates. a en Time: The datatype TIME denotes time, It supports various 85, mat m/e formats such as RMI: $8, HEL 10,3-SQL Statements and Functions “Fis section will discuss several SQL statements and functions for defining and manipulating data, Each SOL statement terminates with a semicolon. \_10.3.1 CREATE DATABASE Statement Creating a database is the first step in database management. CREATE DATABASE statement creates The syntax for the CREATE DATABASE. statement is as follows: 5 2 database. ATABASE database_name; cumate = ma Cinihe shove deseripton of CREATE DATABASE statement, CREATE isan SQL. eyword and databas the name of the database to be specified by the user. _pane is statements, we shall write the SQL keywords in courier font uppercase le @ ie essing ne sa ‘inad names and user inputsin courier font but not boldface We will write the user-def structured Query Language (SQt) 335s chapter) using the CREATE, DA Now, we are ready terest the COMPROTdatabate (described previous crane”) ABASE CREATE DATABASE COMPANY he SHOW DATABASES statement 1d so far, wo use the ‘TS display the list of databases that have been creates SHOW DATABASES; Before we perform any operations on a database, it has to be open 4 for use. SQL statement USE
serves this purpose: USE gatabs To select the database COMPANY for creating and manipulating tables inh statement \e COMPANY. database, we execute the USE CoMPaN’ 10.3.2 CREATE TABLE Statement Next, letuscreatetablescorrespondingtoditferententities(EMPLOYEE, DEPAR’ ). The syntax for the CREATE TABLE statement is: 1 data type [constraint] [) attribute? daca type [constraint]] [, ateriboteN data type [constraint] table_constraints] ) In the description of an SL statement, a pair of square brackets ({}) denotes optional parts. Thus, a CREATE TABLE statement may include any number of attributes or constraints. Note that the attributes and constraints are specifed within parenthesis separated by commas. Next, we give an example of a statement that creates an EMPLOYEE table with the following attributes: iName, Gender, Address, City, Pin, DOB, Salary and DeptNo. Also note that attribute is the primary key of the table EMPLOYEE. When the primary key comprises a single attribute, often we use the keyword PRIMARY KEY, following the type of the attribute to denote that itis the primary key of the table as shown below inthe CREATE TABLE statement: AREATE TABLE EMPLOYEE ( rp INT PRIMARY KEY, lane VARCHAR(20) NOT NULL, lane VARCHAR (20) NOT NULL, Gender CHAR(1) NOP NULL, Address VARCHAR (50), "336 Touchpad Computer Science-Xi!city VARCHAR (20) , ode CHAR(<), pos DATE, salary INT NOT NULL, SMALLINT ): #EMPLOYEE ‘The primary key can also be specified atte a fs have been defined, as shown in the CREATE TABLE can al ecified after all attribute ; ‘ ave been defined, " 235 shown i REATE TABLE =i 7 > INT NOT NULL UNTQUE, ame VARCHAR(20) NOT NULL, inline VARCHAR (20) NOT NULL, CHAR(1) NOT NULL, addvess VARCHAR (50) , VARCHAR (20) CHAR (6) , 2 DATE salary INT NOT NULL, <_No SMALLINT, PRIMARY KEY (ID) ); #EMPLOYEE [As ID is the primary key for the table EMPLOYEE, no two employees can have the same ID, ie, TD must be -MPLOYEE table. Further, as TD identifies an employee uniquely this attribute cannot be NULL. So, unique across the = column constraints UNZQUE and NOT NULL are automaticaly applied to the attribute 2D. EATE TABLE: used to specty © ese cee astribute types Primary key Constraints: NOT NULL, foreign key, values allowed ary key, collectively known as composite key. In such case, the a have been defined, as shown in the example below: primary key i defined after the attributes ofthe table RENEE, TABLE WORKS_OW ( eco} No SMALLINT NOT NULL, ta INT NOT NULL, rs SMALLINT, prrvary KEY (Pro}_Noy Ep 7@)_ db: The statement given above creates the WORK ey consisting of attributes ON table that has a composite primary Key consisting p_Id. structured Query Language Sat) 337 Yo and 5yphen) lowed by = ot that extends soning of 2 commen sca begin wth-(OUbIe ao ends tothe end ofthe ne nd of ine ‘while writing SL statements the ‘The primary key canbe defined as com CONSTRAINT ey PRIMARY REY (TO) None PRIMARY REY (2°! ead jd in the primary Key In general avery CREATE TABLE FHELOYER ( 1b INT NOT MULL UNIQUE, @ 2 Co ser eo, Nome VARCHAR (20) NOT NULL, fender CHAR(1) NOT NULL, Addrese VARCHAR (50) yy VARCHAR (20) code CHAR (S) y Ter NOT NULL, Dept_No- SMALLINT, CONSTRAINT PPIOYES_Key PRIMARY KEY ( ye bexovs eae ne EMPLOYEE. Key 4 the name ofthe primary key constraint on ZDatibue, A named constraint maybe trodiied or dropped later by refering tots name Next, we discuss some more SQL constraints <_263.3 DEFAULT Constraint ‘Adefault value for an attribute may be specified using the DEE fave a salary of 10000, jt would be wise to serTas the default JeAULI constraint. For example, if most of the employees Talay for an employee as TOTOWS etary ENT NOT NULL DEFAULT 10000 ‘The revised GRERTE TABLE statement for the table EMPLOYEE would appear as follows: CREATE TABLE EMPLOYEE ( 1D INT PRIMARY KEY, VARCHAR (20) NOT NULL, VARCHAR (20) NOT NULL, Gender CHAR(1) NOT NULL, Address VARCHAR(S0) , y VARCHAR (20) , code CHAR(S), pos DATE, ry INT NOT NULL DEFAULT 10000, bept_No SMALLINT ); #EMPLOYEE While inserting a tuple into the table EMPLOYEE, ifthe user does not provide any value for the atribute Salary’ 10. The default value of the character type must be enclosed within single quotes & ren ht will be set a8 1000 Eoyble-quates 358 Touchpad Computer Science-X\ 303.4 CHECK Constraint Th CHECK onan et he alg that an attr vatesof Gonder 10H", 15", aug re ate ante. or ample, woud be enon may Be CTUdES a5 part of the tate oa, would be reasonable to limit the an ent specieg = and other & CHECK constraint TsCheve his CHECK (Gender ~ *" OR °F R Gende: \erevised CREATE TABLE states : ia PABLE statement forthe table = So LOCEE woud appear flows INT PRIVARY HEY, ye VARCHAR(26) Wor WoL, woe VARERAR(20) WoT WL, tes CHAR) WOR ox, eR(Gender = FH? OR Gonder = vgs one VARCHAR (50) , 5 eG» for) VARCHAR (20) , : Go HARE) ve BATE, siony INT NOP MULL BEFAULE 10000, wes io SMALLZE yy ABIELOvEE ‘The CHECK constraint may also be used to specify that an attribute would take one ofthe several specified values or numeric value in a specified range. For example, the constrain to perform a check on valid values of Gender may algo be writen as follows: CHECK(Gender IN ('M", TFT, 0") rater ramiple, Salary may be restricted to lie between 8000 and 100000 as follows: CHECK (Salary BETWEEN 8000 AND 100000 “Trerratvely, CHECK constraints may be may be described separately asa table-evel constraints afterall attributes 2re described, for example: CREATE TABLE EMPLOYEE ( INT PRIMARY KEY, VARCHAR (20) NOT NULL, VARCHAR (20) NOT NULL, (CHAR (1) NOT NULL, VARCHAR (50) , City VARCHAR (20) , B CHAR (6), 0oE DATE, Selary INT NOT NULL, : Dept_tio SMALLINT, é CHECK (Gender = 'M' OR Gender = 'F'_ OR Gender='0') £ ‘Salary BETWEEN 6000 AND 100000) ¢ =e : > structured Query Language (SQ)(40;3.5 DESCRIBE TABLE Statement The SOL statement DESCRIBE (or DESC in short DESCRIBE stat DESCRIBE DESC tabie Of cating the statement DESCRIBE the sructure of 3d Execution of the above statement will produce the output shown in Table 10.1 Table 10 Structure of = \_ 103.6 SHOW TABLES Statement ables, we ean use the following SQL statement to show the ist of tables c SHOW TABLES: Gr Giacuting the above staternent, SAL wil display the list of tables, 2s shown in Table 10.2; Table 10:2: Result of 5 et INSERT Statement ‘once the database tables ae created, we can store the datain the database. Storing the available data inthe database is also called loading the database or populating the database. The SOL statement INSERT is used for this pure The syntax for a simple INSERT? statement is as follows: “UAtsert_m70 jiows us to insert a tuple by specifying table name and comma-separated attribute values with parenthesis. The values of type CHAR, VARCHAR, and DATE are enclosed within single-quotes or dovble-qu ‘The order of values in the INSERT statement should correspond to the order of attributes. ifthe value ofan abut is not known, we use the NULL value, However, values ofthe primary key attributes cannot be NULL.Now let Us insert into the EMPLOYEE tabje pradesh as follows: ~ PNSERT INTO ENPLOY wastes (10003, * 100000, 2) 2 tuple for Ra: a ‘3 Reddy whose 1D is 10002 and lives in Andhra Raj", "Reddy", WestGodavaris, + Godavari", 'AndheaPradsh', 534297, +13 @ 8eRF TO Eves VRLUES (10001, "Ras", *Reddy", su", » STRTO_PATE ("Sune 13 1980", may 4a Brovided in YYVY-44N4-D0 format f you prefer, EE, ohn Sey shodhca Pradesh? + $34i97, ‘Alternatively, SQL allows us to specify the attributes whose values are kr ee punorae chicreetey a eaten mieatary, tae Pane, Gna, exer. Note hat there shoud be one to one correspondence between the atibte names andthervauen \ANGERT INTO ENPLOYEE (Salary, Ialane, Rane, Gender, 10) * VALUES (100000, "Reddy", YRajy "Ht, TO00Iy; General syntax for the above statement is given below! INSERT INTO table_name (Attributel, attribute2 “ques (valuet, value2, ..., v , | Attributes) 7) valuen) ; i — et, suppose the values of ateFIBUtes Address, city, Pin. forzaj Reddy whose ID Is ENPLOYE INSERT INTO EMPLOYEE .de, DOB and Dept_No are not known 10001. The following INSERT statement inserts such a tuple into the table VADUES (10001, ‘Raj', ‘Reddy’, 'M", NULL, NULL, NULL, NULL, 100000, NULL); Write SOL statements to insert more rows into EMPLOYEE table so that it appear, a5 shown in Table 10.3 ‘oble 10.3 Showing the EMPLOY! table : Tue ioa-cwntovtbleaterimertnesonetunes | ere ingrted inthe table Howevet, in table 10.3, we have shown the tuples inthe ordecin which they were STEN ETI Sa eel henas does not ensure ary specific order of the tuples. PaCS Secuence does not impact the database operations structured Query Language (Sal) 342\20:3.8 UPDATE-SET Statement nosbeenrevisedrecentiy SL provides 2nUPDATe y sehaving 1D value es te statement sas follows: Suppose the salaryof an employee having ve The syntax ofthe update st iows for making changes inthe tuples already stored in 2 t2) UPDRTE sera “value aaa ee eee ee rope inthe EMPLO’EE table having an TD ecal to 10003 ange The following UPDATE statement finds a tuple in the 7 value ofits attribute to UPDATE =P: SET = WHERE 10 employee whose 1 ‘On executing the above statemcht, SAL wil update the EMPLOYEE tuple forthe employee whose ID's 10003, shown in Table 10.4 Table 104 Result of UPDATE statement on = 10002) to the department having Dept No 1. The folowing Next, suppose we want to assign a manager (1 UPDATE statement finds a tuple in the DEPARTMENT table having Dept_No 1 and sets the value ofits attribute t UPDATE ser ‘0002 WHERE Table 105: Result of \J059 DELETE Statement ELETE Statement _ To delete one or more tuples (satistyng a particular criterion froma table, we use the DELETE statement. Theat ofthe delete statement is as follows: DELETE FROM [WHERE criterion-for For example, to delete the record ofthe emplayee from the ve flowing St statement lovee from the EMPLOYEE table whose XD is 10007, we exectt DELETE FROM Fi1PLOvEE WHERE 10 = 10007; electing-specifi tuple]: 342 Touchpad Computer Science-xitLet us now execute the statement that shoves th employee having 10 10007 ha urtent state ofthe hasbeen dled ac shooe gel etal fom which he tuple coresondingo the Table 10.6: Result of Deere tatement on EMPLOYEE table ‘The execution of the following sta DELETE FROM EMPLOYEE; However, the table EMPLOYE went will delete all rows ofthe table EMPLOYEE, remains part ofthe database and can be populated again {205.10 DROP TABLE Statement The DROP TABLE statement deletes an esting table na database. The sytaxof the DROP TABLE me statements as DROP TABLE table-name; For example to drop the table EMPLOYEE from the database COMPANY, we can use the folowing SOL statement DROP TABLE EMPLOYEE? © 007 zante: toremore ate nd \ 10.3111 ALTER TABLE Statement ALTER ‘TABLE statement allows us to add, change, and delete attributes ofa table. t can also be sed to create and rernove SOL constraints from TabTes SQL constraints from ta sonny? 3 © saree sanse: tm ns deters Add Attributes To add attributes to an existing table; ALTER TABLE-ADD statement is 3s follows: ame ADD attribute data_type [constraint]; Sgt 4 ALTER TABLE tabl Far ecamgle To add-a new atirbute PHone i he EMPLOYEE table, the SOL satemens 23s follows: ALTER TABLE EMPLOYEE {0D Phone DECIMAL (20,0); DP Ehone PEC ADD keyword, The syntax ofthe we use the ALTER TABLE statement with the 33 structured Query Language (SO)inthe EMPLOYEE table willbe assigned yy, cady exist vas ‘On executing the above statement, the tuples that already 7 for Phone atribut, as shown in Tale 10.7: Table 10.7, Phone attribute fs added to the table EMPLOYEE we can execute several ALTER TABLE statements. Alternatively we ay Te add more than one aiuto 2 abe, several “Thelude several attributes in a single RETER TABLE statement using the following syntax: ORTER TABLE “abe AD {attribuve! datatype [constraint] ‘esbute? data type (coneteaint] data_type [constraint]); ‘example, execution ofthe following SQL statement will add two attributes Mobi le and Email tothe table: {_-ALTER TABLE ExPLOYEE ADD ( DECIMAL (10,0) DEFAULT VARCHAR (50) NOT NULL) ; ‘We can examine the change In the EMPLOYEE table on the execution of above SOL statement by executing the following DESC statement: bese Suer0¥ Execution of the above statement will produce the output as shown in Table 10.8 Table 108: Structure of ENP: \ Modify Attributes Ted the defition of erbues fs aaa; we wth a yeost! a statement with the! — eyo The syntax ofthe ALTER TABLR-MODIEY statement ses aren, TABLE statement with he WS” nane MODIFY attribul table ater adding Mobile and Email Attributes es datatype [constraint] 344 Touchpad Computer Science-XilFor example, to modify the defini following SQL statement 0” of an existing atibute Dept E_No inte aieeh okses each \e EMPLOYEE table, we can execute the ee ote ay? Aes Se ee a OP BEG statement as follows ‘ DESC EMPL Tab leon the execu ante execution of above SOL statement by executing 8 DESC Omevecuting the above statement, we get the result as shown in ble 10.9 ", We Get the resus able Table 10: structure of uPLo¥ ble ater modiying Drop Attributes Tete an abate om 2 ate eu the ALTER TABLE seme wh he DROP ewer The yeh he ALTER TABLE table_nane DROP attribute; Fer example, 0 drop thé attributes Phone, Mobile, and Email from the EMPLOYEE table, we can execute the following SQLatements: ALTER TABLE yROP Phone; SETER TABLE EMPLOYEE DROP Mobile ALTER TABLE DROP Email; As before, we describe the modified table EM?! DESC =NELO (On executing the above statement, we get the result as shown in Table 10.10; ‘able 10.10; structure of 2HPLOYEE table after dropping the Phone, Mobile, and Email tributes Sng PATER GABLE” sateien we canal ad and/or rerove te primary Ky consis Th riay the pimay ey cess Te cOmstraInt tar BE enforced on rribute using the following ALTER TABLE statemer nan STE MATER TABLE EMPLOYEE BoD PRIMARYREY)7 ae meee 3S structured Query Language (SOU)from an atribute, the following ALTER TABLE statement can be used: em re Rename Attributes ~ To rename an attribute of an existing table, we use the ALTER TABLE statement with the RENAME, COLUMN keywor, TResyilaxofthe ALTER TABLE RENAME COLUMN statemehtis follows: — FF = SALTER TABLE 775” RENAME” COLOR Forel ROGHY Te Teton fon ing abate PIT TOTT-MMEETPTOVEE. table, to PinCode, we
= valuel AND attributed <= value2) Jo display 2D, Fame, and Salary of those employees Whose salary is between 85000 to 100000, both inclusive, we may GEE TRE TOMOWMEAE | SELECT ID, Fane, Salary FROM : WHERE 5. ‘Table 10.22 displays the output of the given query: ‘able 10.22: Employees having salary between 85000 and 100000 Note that Table 10.22 includes salary 85000 and 100000, specified for the BETWEEN operator. Thus, BETWEEN is inclusive operator as it includes the begin and end values ofthe specified range. 350 Touchpad Computer ScienceTo display the fist name, USE the following SQL sta last name, oon SELECT Pian ee (FROM EMPLOYEE “WHERE DOS BETWEEN + and date of birth o Ye et a 85 to 1990, we all employees born between the years 1685 to ces born = ean Execution of the above statement y will prod aa ce the outputs MM/LXYY format as follows: SELECT FWane, Name, DATE. FORMAT (DOB, ' FROM EWPLOYEE | HERE DOB BETWEEN '1985-01-01" AND *1990-12-31"; £() Seston tthe above state wi roses that shawn ae 024 a] m/3¥") AS DoB “able 10.24: Employees whase date of births between 3985-01-01" and 1990-12-31 Query: Display the first name, lastname, and date of birth of all employees, except those who were born between the years other than TSE5%0 1990, ‘To answer the above query, we use NOT operator before BETWEEN operator as follows: SELECT FWane, Lane, DOS FROM EMPLOYEE WHERE DOB NOT BETWEEN '1925~' Execution of the above statement will produce the output shown in Table 10.25: oi" AND '1990-12-31'; “able 10.25: Employees whose date of birth i outside the interval ["2985-01-01',"2990-12°9 arene stor provides an alternative 35h structured Query Language (SO)An SQL statement involving XN operator has the following syntax: SELECT FROM + wieRE B (ory Iw ‘For example, to display the first fame and the lastname of those e 2, oF S, we can use the Tolowing SL statement 7 _ SeLECT FROM, OMWERE Dept No IN Execution of the above SQL statement wil display the output shown in Table 10.26: Table 10.26: Employees who workin department number 2, 2, oF Next, to display those employees who work forthe departments other than department number 2,2, 5, weUuse WOT operator TmsUrstatement as follows! — a EName, Dept_No Table 10.27: Employees who do not workin department number L, 2, ar 5 ‘Query: Display the department names and their locations for the departments located in Mumbsi or Delhi ion IN (‘Mumbai', ‘Delhi') ; Executing the above statement will produce the output shown in Table 10.28: Table 10.28: Departments located in Mumbai or Delhi as 163.17 1S Operator Recall from the previous chapter that when the value of an attribute is not known, we use either the default vale (itspecitied) or the NULL value. We can check whether a value is NULL using 1S NULL or TS_N ———E— 7 352 Touchpad Computer Sclence-Xsing the following syntax seusct attributel, attri $F table_nan uted IS [NOT] NULL; the operator TS NULL returns TRUE ifthe specified attribute (at :ribute.) in the above description) has 9 NULL Value and FALSE otherwise. The operator IS NOT NULL returns TRUE if the specified attribute (act ributed in the above description) has @ non-NULL value and FALSE otherwise For example, to display the depart having a manager: SELECT Dept_Name, Mgr Id went name and the manager ID from the DEPARTMENT table for the departments WHERE Mgr_Id IS NOT NULL; Table 10.29: Dept Name, Mar_Td for the departments with a manager _10.3.18 LIKE Operator ‘The SQL LIKE operator uses wildcard operators ¢and _todefine a pattern. The percent (#) operator denotes zero, one, or more occurrences of arbitrary characters, The underscore [_} operator represents exactly one occurrence of “mn arbitrary character Tf required, we may use a combination of % and _ operators. The syntax for the LIKE operator isgiven below: rs ' SELECT attributel, attribute2, FROM table name WHERE attributed LIKE 'pattern'; For example, to display ID, first name, last name, and the salary of all employees whose first name starts with 'R', use the statement given below: : SELECT ID, Fame, LName, Salary FROM EMPLOYEE. nn lame LIKE 'F REI; Execution of the above query will produce the output shown in Table 10.30: 11D | Flame | Lame | Salary | 1 10001 | Raj | Reddy | 100000 1 1 10006 1 Rajie 1 Gad 1 60000 Table 10.30: Employees whose first name begins with 'R%" Note that there are two tuples having the first name that matches the pattern 'R%' (FName starting with R) ‘Query: Display IO, first name, last name, and the salary of employees whose first name starts with "R’ and salary in the sity thousanf'Tange, Le. a five-digit number beginning 6. SELECT ID, Flame, LName, Salary — Structured Query Language (SQL) 353,FROM EMPLOYEE, ———— WHERE FName LIKE ‘8%’ AND Salory LIKE '6 Execution of the above query will ins with ‘2% and have a salary inthe range of sixty thousand Table 10.31: Employees whose first name be} ‘ose first name contains two a's or two e's. name of all employees whi \ Query: Display the employee ID and fi SELECT 1D, Fame FROM. EMP WHERE Fame LIKE ‘Ya Execution of the above query will produce the o LOYEE ah! OR FName LIKE Jutput shown in Table 10.32: Table 10,32: Employees whose first name contains two a's or two és \ query: Display the first name, last name, and date of birth of all employees who were born in 1980. SELECT fName, tName, DOB FROM EMPLOYEE WHERE DOB LIKE '1980 OR SELECT FName, LName, DOB FROM EMPLOYEE. WHERE DOB LIKE '19803'7 ue Execution of either of the above two queries, will produce the output as sho wn in Table 10.33: Tae) 1 Reddy | 1980-06-13 | ‘Table 10.33: Employees born in 1980 _ 10.3.19 Aggregate Functions GAL provides several functions where the selection criterion applies to an aggregate of tuples instead of a single tuple Let us learn about some of the aggregate functions. INT() Function “Ihe function COUNT () is used to display the count ofthe tuples satisfying a specified criterion, For example, to find ‘COUNT () function can be used as follows: the number of employees earning 75000 or more, ‘Aggregate Functions: apply to an aggregate of tuples instead of a single tuple. COUNT 7 Returns the number of tuples satisiying a specified condition, 354 Touchpad Computer Science-X!lSELECT COUNT (*) FROM EMPLOYEE WHERE Salary > 75000; Execution of the above query will. produce the output shown Table 10.34: Table 10.34: Count of employees earning 75000 or more To execute the above statement, the function COUNT () finds the number of tuples in the EMPLOYEE table whose salary attribute has value 75000 or more. Note that the above output would look much nicer if the SQL output column were named EmployeeCount instead of COUNT(*). For this purpose, SQL provides an AS clause which renames the output column. The following SQL statement achieves th © As: renames the output column for ease of eisplay/ referencing SELECT COUNT(*) AS Emp FROM EMPLOYEE WHERE Salary >= 75000; The above SQt statement introducesa nanre (EmployeeCount) for the output column. A name defined u: clause is known as an alias. Execution of the above statement will produce the output shown in Table 10.35: yeeCount, Table 10.35: Count of employees as EmployeeCount, SUM() Function ‘The Tuncton-SUM() 15 Uséd to compute the sum of attribute values (based on the selection criterion mentioned in WHERE clause, if specified). For example, to display the total salary of all employees, the following query may be used: 6 SUM (): returns sum of the attribute values satisfying condition(s) in WHERE clause ee ee SELECT SUM(Salary) AS Total Salary EMPLOYEE; Execution of the above statement will produce the output shown in Table 10.36: Table 10.36: Total salary of all employees _— Structured Query Language (SQL) 355.TEI I MAX() Function “Fhe MAX () functon * table, following SQL ‘ads the maximum of a set of values. FOr example, to display the maximum salary from the statement may be used Execution of the above statement will produce the output shown in Table 10.37: gst all employees um salary, it may be tempting to use the Table 10.37: Maximum salary amon’ For example, to find the employees’ first name and last name having 2 maxim following SQk statement SELECT Sn the execution of the above statement, displays only one row for an employee who has the maximum However salary, as shown in Table 10.38: ‘able 10.38: First name and last name of employee having 2 maximum salary Let us frst ind the maximum salary by executing the sub-query (often called a nested query): Nik, we look for the employees who have the maximum salary (found on the execution of the above query) as follows: Table 10.39: Employees getting maximum salary When # query encloses another query, the inner query is called a nested query. In the above example, the query is a9 example of a nested query: " MIN() Function The function MIN () yields the minimum value of the specified attribute. For exam it ple, to find the ar from the E: table, the SQL query will be: a einai Sore — 356 Touchpad Computer Science-x!! aExecution of the above query will produce the output as given in Table 10.40 Table 10.40: Least salary amongst all employees AVG() Function a : employees, The function AVG() yields the average value of the specified attribute. To find the average salary of ali employ the query will be: SELECT AVG (Sal AS Average Salary Execution of the above query will produce the output shown in Table 10.41: Table 10.41: Average salary of employees rounded to 4 decimal places Note that the results of applying the AVG () function will look more elegant if the average salary is shown up to two places of decimal. For this purpose, SQL provides a ROUND () function. Which rounds a number to a specified number of decimal places. In the following query, ROUND () is used to round the average salary in each department to two decimal places: SELECT ROUND (AVG (Salar FROM EMPLOYEE; y),2) AS Average Salary aes Execution of the above query will Produce the output shown in Table 10.42: Table 10.42: Average salary of employees rounded to two decimal places
You might also like
Document 5
PDF
No ratings yet
Document 5
18 pages
Relational Database 2
PDF
No ratings yet
Relational Database 2
196 pages
DBMS
PDF
No ratings yet
DBMS
48 pages
DBMS Manual (P) 2023-24
PDF
No ratings yet
DBMS Manual (P) 2023-24
151 pages
Cs
PDF
No ratings yet
Cs
20 pages
Debremarkos University Burie Campas: Department of Computer Sience Database Lab Mannul
PDF
No ratings yet
Debremarkos University Burie Campas: Department of Computer Sience Database Lab Mannul
21 pages
Unit 4
PDF
No ratings yet
Unit 4
34 pages
Dbms Module SQL
PDF
No ratings yet
Dbms Module SQL
79 pages
SQL DBMS Presentation For Mathematical Students (2nd Sem)
PDF
No ratings yet
SQL DBMS Presentation For Mathematical Students (2nd Sem)
101 pages
Unit-2 Basics of SQL
PDF
No ratings yet
Unit-2 Basics of SQL
25 pages
SQL Server Material1
PDF
No ratings yet
SQL Server Material1
62 pages
Unit I: Introduction To Mysql
PDF
100% (1)
Unit I: Introduction To Mysql
39 pages
Aayushi Roy Ism File
PDF
No ratings yet
Aayushi Roy Ism File
29 pages
PracticalHandBook SQL
PDF
100% (1)
PracticalHandBook SQL
59 pages
SQL Notes
PDF
No ratings yet
SQL Notes
18 pages
MySQL-2
PDF
No ratings yet
MySQL-2
25 pages
CS8481 DBMS RECORD FINAL Modfied
PDF
No ratings yet
CS8481 DBMS RECORD FINAL Modfied
123 pages
DBMS Full Notes
PDF
No ratings yet
DBMS Full Notes
80 pages
Unit1 Dbms
PDF
No ratings yet
Unit1 Dbms
34 pages
Adbms 2
PDF
No ratings yet
Adbms 2
32 pages
SQL Notes ?
PDF
No ratings yet
SQL Notes ?
10 pages
Rdbms File Dabba
PDF
No ratings yet
Rdbms File Dabba
45 pages
Mysql Commands Notes
PDF
100% (1)
Mysql Commands Notes
23 pages
Mysql Commands Notes
PDF
No ratings yet
Mysql Commands Notes
23 pages
CS8481 - Database Management Systems Lab Manualsairam
PDF
No ratings yet
CS8481 - Database Management Systems Lab Manualsairam
160 pages
Chapter 5
PDF
No ratings yet
Chapter 5
58 pages
Basic Operations With MySQL - Part 1
PDF
No ratings yet
Basic Operations With MySQL - Part 1
15 pages
DBDev 02 (4) 2
PDF
No ratings yet
DBDev 02 (4) 2
90 pages
SQL Itp2
PDF
No ratings yet
SQL Itp2
110 pages
Practical DBMS
PDF
100% (2)
Practical DBMS
38 pages
unit 2
PDF
No ratings yet
unit 2
96 pages
Oracle Reviewer
PDF
No ratings yet
Oracle Reviewer
24 pages
Database: TAB 1073 - SPDB
PDF
No ratings yet
Database: TAB 1073 - SPDB
52 pages
Database and SQL Complete
PDF
No ratings yet
Database and SQL Complete
84 pages
Oracle 10g Lab Simple
PDF
No ratings yet
Oracle 10g Lab Simple
93 pages
Module 3
PDF
No ratings yet
Module 3
49 pages
l5 Sod Database Development
PDF
No ratings yet
l5 Sod Database Development
85 pages
Dbms Lab - Print
PDF
No ratings yet
Dbms Lab - Print
124 pages
Dbms Module-3 Csbs
PDF
No ratings yet
Dbms Module-3 Csbs
65 pages
mysql-data-types
PDF
No ratings yet
mysql-data-types
2 pages
SQL Cheat Sheet
PDF
0% (1)
SQL Cheat Sheet
16 pages
sql
PDF
No ratings yet
sql
21 pages
Database: TDB2073 - SPDB
PDF
No ratings yet
Database: TDB2073 - SPDB
52 pages
SQL Questions
PDF
No ratings yet
SQL Questions
16 pages
Rdbms File
PDF
No ratings yet
Rdbms File
46 pages
SQL Lecture 2
PDF
No ratings yet
SQL Lecture 2
41 pages
Structured Query Language
PDF
No ratings yet
Structured Query Language
39 pages
Structured Query Language
PDF
No ratings yet
Structured Query Language
33 pages
DBMS (Unit2)
PDF
No ratings yet
DBMS (Unit2)
14 pages
Structured Query Language
PDF
No ratings yet
Structured Query Language
16 pages
2.4_sql
PDF
No ratings yet
2.4_sql
15 pages
CS121 Lec 04
PDF
No ratings yet
CS121 Lec 04
44 pages
Lab Session 1-3
PDF
No ratings yet
Lab Session 1-3
13 pages
MODULE NO -4 DBMS
PDF
No ratings yet
MODULE NO -4 DBMS
163 pages
Module 3 Part B
PDF
No ratings yet
Module 3 Part B
19 pages
D.B.M.S Assignment-2
PDF
No ratings yet
D.B.M.S Assignment-2
31 pages
My SQL Instagram
PDF
No ratings yet
My SQL Instagram
9 pages
Mysql Is An: Open-Source Relational Database Management System
PDF
No ratings yet
Mysql Is An: Open-Source Relational Database Management System
22 pages
Optical Instruments Recovered
PDF
No ratings yet
Optical Instruments Recovered
2 pages
12A Class Test No.17 (19.11.24) (1-20)
PDF
No ratings yet
12A Class Test No.17 (19.11.24) (1-20)
10 pages
Networking Based Long Question
PDF
No ratings yet
Networking Based Long Question
10 pages
D and F Block Elements
PDF
No ratings yet
D and F Block Elements
6 pages
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
Document 5
PDF
Document 5
Relational Database 2
PDF
Relational Database 2
DBMS
PDF
DBMS
DBMS Manual (P) 2023-24
PDF
DBMS Manual (P) 2023-24
Cs
PDF
Cs
Debremarkos University Burie Campas: Department of Computer Sience Database Lab Mannul
PDF
Debremarkos University Burie Campas: Department of Computer Sience Database Lab Mannul
Unit 4
PDF
Unit 4
Dbms Module SQL
PDF
Dbms Module SQL
SQL DBMS Presentation For Mathematical Students (2nd Sem)
PDF
SQL DBMS Presentation For Mathematical Students (2nd Sem)
Unit-2 Basics of SQL
PDF
Unit-2 Basics of SQL
SQL Server Material1
PDF
SQL Server Material1
Unit I: Introduction To Mysql
PDF
Unit I: Introduction To Mysql
Aayushi Roy Ism File
PDF
Aayushi Roy Ism File
PracticalHandBook SQL
PDF
PracticalHandBook SQL
SQL Notes
PDF
SQL Notes
MySQL-2
PDF
MySQL-2
CS8481 DBMS RECORD FINAL Modfied
PDF
CS8481 DBMS RECORD FINAL Modfied
DBMS Full Notes
PDF
DBMS Full Notes
Unit1 Dbms
PDF
Unit1 Dbms
Adbms 2
PDF
Adbms 2
SQL Notes ?
PDF
SQL Notes ?
Rdbms File Dabba
PDF
Rdbms File Dabba
Mysql Commands Notes
PDF
Mysql Commands Notes
Mysql Commands Notes
PDF
Mysql Commands Notes
CS8481 - Database Management Systems Lab Manualsairam
PDF
CS8481 - Database Management Systems Lab Manualsairam
Chapter 5
PDF
Chapter 5
Basic Operations With MySQL - Part 1
PDF
Basic Operations With MySQL - Part 1
DBDev 02 (4) 2
PDF
DBDev 02 (4) 2
SQL Itp2
PDF
SQL Itp2
Practical DBMS
PDF
Practical DBMS
unit 2
PDF
unit 2
Oracle Reviewer
PDF
Oracle Reviewer
Database: TAB 1073 - SPDB
PDF
Database: TAB 1073 - SPDB
Database and SQL Complete
PDF
Database and SQL Complete
Oracle 10g Lab Simple
PDF
Oracle 10g Lab Simple
Module 3
PDF
Module 3
l5 Sod Database Development
PDF
l5 Sod Database Development
Dbms Lab - Print
PDF
Dbms Lab - Print
Dbms Module-3 Csbs
PDF
Dbms Module-3 Csbs
mysql-data-types
PDF
mysql-data-types
SQL Cheat Sheet
PDF
SQL Cheat Sheet
sql
PDF
sql
Database: TDB2073 - SPDB
PDF
Database: TDB2073 - SPDB
SQL Questions
PDF
SQL Questions
Rdbms File
PDF
Rdbms File
SQL Lecture 2
PDF
SQL Lecture 2
Structured Query Language
PDF
Structured Query Language
Structured Query Language
PDF
Structured Query Language
DBMS (Unit2)
PDF
DBMS (Unit2)
Structured Query Language
PDF
Structured Query Language
2.4_sql
PDF
2.4_sql
CS121 Lec 04
PDF
CS121 Lec 04
Lab Session 1-3
PDF
Lab Session 1-3
MODULE NO -4 DBMS
PDF
MODULE NO -4 DBMS
Module 3 Part B
PDF
Module 3 Part B
D.B.M.S Assignment-2
PDF
D.B.M.S Assignment-2
My SQL Instagram
PDF
My SQL Instagram
Mysql Is An: Open-Source Relational Database Management System
PDF
Mysql Is An: Open-Source Relational Database Management System
Optical Instruments Recovered
PDF
Optical Instruments Recovered
12A Class Test No.17 (19.11.24) (1-20)
PDF
12A Class Test No.17 (19.11.24) (1-20)
Networking Based Long Question
PDF
Networking Based Long Question
D and F Block Elements
PDF
D and F Block Elements