Introduction toStructured QueryLanguage (SQL)Chapter8In this chapter»» Introduction“The most important motivation for theresearch work that resulted in the relationalmodel was the objective of providing a sharpand clear boundary between the logical andphysical aspects of database management.”– E. F. Codd»» Structured QueryLanguage (SQL)»» Data Types andConstraints in MySQL»» SQL for Data Definition»» SQL for DataManipulation»» SQL for Data Query»» Data Updation andDeletion8.1 IntroductionWe have learnt about Relational DatabaseManagement System (RDBMS) and purpose in theprevious chapter. There are many RDBMS suchas MySQL, Microsoft SQL Server, PostgreSQL,Oracle, etc. that allow us to create a databaseconsisting of relations and to link one or morerelations for efficient querying to store, retrieveand manipulate data on that database. In thischapter, we will learn how to create, populate andquery database using MySQL.2021-22Chap 8.indd 14319-Jul-19 3:45:57 PM

144Informatics Practices – Class XI8.2 Structured Query Language (SQL)One has to write application programs to access data incase of a file system. However, for database managementsystems there are special kind of programminglanguages called query language that can be used toaccess data from the database. The Structured QueryLanguage (SQL) is the most popular query languageused by major relational database management systemssuch as MySQL, ORACLE, SQL Server, etc.SQL is easy to learn as the statements comprise ofdescriptive English words and are not case sensitive.We can create and interact with a database using SQLin an efficient and easy way. The benefit with SQL isthat we don’t have to specify how to get the data fromthe database. Rather, we simply specify what is to beretrieved, and SQL does the rest. Although called a querylanguage, SQL can do much more besides querying.SQL provides statements for defining the structure ofthe data, manipulating data in the database, declareconstraints and retrieve data from the database invarious ways, depending on our requirements.In this chapter, we will learn how to create a databaseusing MySQL as the RDBMS software. We will create adatabase called StudentAttendance (Figure 7.5) that wehad identified in the previous chapter. We will also learnhow to populate database with data, manipulate data inthat and retrieve data from the database through SQLqueries.8.2.1 Installing MySQLActivity 8.1Explore LibreOfficeBase and compare itwith MySQLMySQL is an open source RDBMS software which canbe easily downloaded from the official website After installing MySQL,start MySQL service. The appearance of mysql prompt(Figure 8.1) means that MySQL is ready for us to enterSQL statements.Few rules to follow while writing SQL statements inMySQL: SQL is case insensitive. That means name and NAMEare same for SQL. Always end SQL statements with a semicolon (;). To enter multiline SQL statements, we don’t write‘;’ after the first line. We put enter to continue onnext line. The prompt mysql then changes to ‘- ’,2021-22Chap 8.indd 14419-Jul-19 3:45:57 PM

IntroductiontoStructured Query Language (SQL)145indicating that statement is continued to the nextline. After the last line, put ‘;’ and press enter.8.3 Data TypesandConstraintsinMySQLFigure 8.1: MySQL ShellWe know that a database consists of one or morerelations and each relation (table) is made up of attributes(column). Each attribute has a data type. We can alsospecify constraints for each attribute of a relation.8.3.1 Data type of AttributeData type indicates the type of data value that anattribute can have. The data type of an attribute decidesthe operations that can be performed on the data ofthat attribute. For example, arithmetic operations canbe performed on numeric data but not on characterdata. Commonly used data types in MySQL are numerictypes, date and time types, and string (character andbyte) types as shown in Table 8.1.Activity 8.2What are the otherdata types supported inMySQL? Are there othervariants of integer andfloat data type?Think and ReflectCan you think of anattribute for whichfixed length string issuitable?Table 8.1 Commonly used data types in MySQLData typeDescriptionCHAR(n)Specifies character type data of length n where n could be any value from 0 to255. CHAR is of fixed length, means, declaring CHAR (10) implies to reservespaces for 10 characters. If data does not have 10 characters (for example,‘city’ has four characters), MySQL fills the remaining 6 characters with spacespadded on the right.VARCHAR(n)Specifies character type data of length ‘n’ where n could be any value from 0to 65535. But unlike CHAR, VARCHAR is a variable-length data type. That is,declaring VARCHAR (30) means a maximum of 30 characters can be storedbut the actual allocated bytes will depend on the length of entered string. So‘city’ in VARCHAR (30) will occupy the space needed to store 4 characters only.2021-22Chap 8.indd 14519-Jul-19 3:45:57 PM

146Informatics Practices – Class XIINTINT specifies an integer value. Each INT value occupies 4 bytes of storage. Therange of values allowed in integer type are -2147483648 to 2147483647. Forvalues larger than that, we have to use BIGINT, which occupies 8 bytes.FLOATHolds numbers with decimal points. Each FLOAT value occupies 4 bytes.DATEThe DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is the 4 digityear, MM is the 2 digit month and DD is the 2 digit date. The supported rangeis '1000-01-01' to '9999-12-31'.Think and ReflectWhich two constraintswhen applied togetherwill produce a PrimaryKey constraint?8.3.2 ConstraintsConstraints are certain types of restrictions on the datavalues that an attribute can have. They are used toensure the accuracy and reliability of data. However, itis not mandatory to define constraint for each attributeof a table. Table 8.2 lists various SQL constraints.Table 8.2 Commonly used SQL ConstraintsConstraintDescriptionNOT NULLEnsures that a column cannot have NULL values where NULL means missing/unknown/not applicable value.UNIQUEDEFAULTEnsures that all the values in a column are distinct/unique.A default value specified for the column if no value is provided.PRIMARY KEYThe column which can uniquely identify each row or record in a table.FOREIGN KEYThe column which refers to value of an attribute defined as primary key in anothertable.8.4 SQLforData DefinitionSQL provides commands for defining the relationschemas, modifying relation schemas and deletingrelations. These are called Data Definition Language(DDL) through which the set of relations are specified,including their schema, data type for each attribute, theconstraints as well as the security and access relatedauthorisations.Data definition starts with the create statement. Thisstatement is used to create a database and its tables(relations). Before creating a database, we should beclear about the number of tables in the database, thecolumns (attributes) in each table along with the datatype of each column. This is how we decide the relationschema.8.4.1 CREATE DatabaseTo create a database, we use the CREATEstatement as shown in the following syntax:DATABASECREATE DATABASE databasename;2021-22Chap 8.indd 14619-Jul-19 3:45:57 PM

IntroductiontoStructured Query Language (SQL)147To create a database called StudentAttendance, wewill type following command at mysql prompt.mysql CREATE DATABASE StudentAttendance;Query OK, 1 row affected (0.02 sec)Note: In LINUX environment, names for database and tablesare case-sensitive whereas in WINDOWS, there is no suchdifferentiation. However, as a good practice, it is suggested to writedatabase or table name in the same letter cases that were used atthe time of their creation.ShowA DBMS can manage multiple databases on onecomputer. Therefore, we need to select the databasethat we want to use. Once the database is selected, wecan proceed with creating tables or querying data. Writethe following SQL statement for using the database:mysql USE StudentAttendance;Database changedActivity 8.3Initially, the created database is empty. It can bechecked by using the Show tables command that listsnames of all the tables within a database.mysql SHOW TABLES;Empty set (0.06 sec)Type the statementshow database;. Doesit show the name ofStudentAttendancedatabase?8.4.2 CREATE TableAfter creating database StudentAttendance, we needto define relations (create tables) in this database andspecify attributes for each relation along with data typesfor each attribute. This is done using the CREATE TABLEstatement.Syntax:CREATE TABLE tablename(attributename1 datatype constraint,attributename2 datatype constraint,:attributenameN datatype constraint);It is important to observe the following points withrespect to the Create Table statement: N is the degree of the relation, means there are Ncolumns in the table. Attribute name specifies the name of the column inthe table. Datatype specifies the type of data that an attributecan hold. Constraint indicates the restrictions imposed on thevalues of an attribute. By default, each attribute cantake NULL values except for the primary key.2021-22Chap 8.indd 14719-Jul-19 3:45:57 PM

Informatics Practices – Class XI148Let us identify data types of the attributes of tableSTUDENT along with their constraint, if any. Assumingmaximum students in a class to be 100 and values ofroll number in a sequence from 1 to 100, we know that3 digits are sufficient to store values for the attributeRollNumber. Hence, data type INT is appropriate for thisattribute. Total number of characters in student names(SName) can differ. Assuming maximum characters ina name as 20, we use VARCHAR(20) for SName column.Data type for the attribute SDateofBirth is DATE andsupposing the school uses guardian’s 12 digit Aadhaarnumber as GUID, we can declare GUID as CHAR (12)since Aadhaar number is of fixed length and we are notgoing to perform any mathematical operation on GUID.Table 8.3, 8.4 and 8.5 show the chosen data type andconstraint for each attribute of the relations STUDENT,GUARDIAN and ATTENDANCE, respectively.Table 8.3 Data types and constraints for the attributes of relation STUDENTAttribute NameData expected to be storedData typeConstraintRollNumberNumeric value consisting of maximum 3 digitsINTPRIMARY KEYSNameVariant length string of maximum 20 charactersVARCHAR(20)NOT NULLDATENOT NULLCHAR (12)FOREIGN KEYSDateofBirthGUIDDate valueNumeric value consisting of 12 digitsTable 8.4 Data types and constraints for the attributes of relation GUARDIANAttribute NameData expected to be storedData typeConstraintGUIDNumeric value consisting of 12 digit AadhaarnumberCHAR (12)PRIMARY KEYVARCHAR(20)NOT NULLCHAR(10)NULL UNIQUEVARCHAR(30)NOT NULLGNameVariant lengthcharactersGPhoneNumeric value consisting of 10 digitsGAddressstringofmaximumVariant length string of size 30 characters20Table 8.5 Data types and constraints for the attributes of relation ATTENDANCE.Attribute NameAttendanceDateRollNumberAttendanceStatusData expected to be storedDate valueNumeric value consisting of maximum 3digits‘P’ for present and ‘A’ for absentData typeConstraintDATEPRIMARY KEY*INTPRIMARY KEY*FOREIGN KEYCHAR(1)NOT NULL*means part of composite primary keyOnce data types and constraints are identified, let uscreate tables without specifying constraint along withthe attribute name for simplification. We will learn toincorporate constraints on attributes in Section 8.indd 14819-Jul-19 3:45:57 PM

IntroductiontoStructured Query Language (SQL)Example 8.1 Create table STUDENT.mysql CREATE TABLE STUDENT(- RollNumber INT,- SName VARCHAR(20),- SDateofBirth DATE,- GUID CHAR(12),- PRIMARY KEY (RollNumber));Query OK, 0 rows affected (0.91 sec)149Think and ReflectCan we have a CHARor VARCHAR data typefor contact number(mobile, landline)?Note: ‘,’ is used to separate two attributes and each statementterminates with a semi-colon (;). The symbol ‘- ’ indicates linecontinuation as SQL statement may not complete in a single line.8.4.3 DESCRIBE TableWe can view the structure of an already created tableusing the describe statement.Syntax:DESCRIBE tablename;MySQL also supports the short form DESC of DESCRIBEto get description of table. To retrieve details about thestructure of relation STUDENT, we can write DESC orDESCRIBE followed by table name:Activity 8.4Create the other tworelations GUARDIANand ATTENDANCEas per data typesgiven in Table 8.4 and8.5, and view theirstructures. Don't addany constraint in thetwo tables.mysql DESC STUDENT; -------------- ------------- ------ ----- --------- ------- Field Type Null Key Default Extra -------------- ------------- ------ ----- --------- ------- RollNumber int NO PRI NULL SName varchar(20) YES NULL SDateofBirth date YES NULL GUID char(12) YES NULL -------------- ------------- ------ ----- --------- ------- 4 rows in set (0.06 sec)The show table command will now return the tableSTUDENT:mysql SHOW TABLES; ------------------------------ Tables in studentattendance ------------------------------ student ------------------------------ 1 row in set (0.00 sec)8.4.4 ALTER TableAfter creating a table we may realize that we need toadd/remove an attribute or to modify the datatype of anexisting attribute or to add constraint in attribute. In allsuch cases, we need to change or alter the structure ofthe table by using the alter statement.Syntax:ALTER TABLE tablename ADD/Modify/DROP attribute1,attribute2,.2021-22Chap 8.indd 14919-Jul-19 3:45:57 PM

150Informatics Practices – Class XI(A) Add primary key to a relationLet us now alter the tables created in Activity 8.4. Thebelow MySQL statement adds a primary key to theGUARDIAN relation:mysql ALTER TABLE GUARDIAN ADD PRIMARY KEY (GUID);Query OK, 0 rows affected (1.14 sec)Records: 0 Duplicates: 0 Warnings: 0Now let us add primary key to the ATTENDANCErelation. The primary key of this relation is a compositekey made up of two attributes — AttendanceDate andRollNumber.mysql ALTER TABLE ATTENDANCE- ADD PRIMARY KEY(AttendanceDate,- RollNumber);Query OK, 0 rows affected (0.52 sec)Records: 0 Duplicates: 0 Warnings: 0(B) Add foreign key to a relationOnce primary keys are added the next step is to addforeign keys to the relation (if any). A relation may havemultiple foreign keys and each foreign key is defined ona single attribute. Following points need to be observedwhile adding foreign key to a relation: The referenced relation must be already created. The referenced attribute must be a part of primarykey of the referenced relation. Data types and size of referenced and referencingattributes must be same.Syntax:ALTER TABLE table name ADD FOREIGN KEY(attributename) REFERENCES referenced table name(attribute name);Think and ReflectName foreign keys intable ATTENDANCEand STUDENT. Is thereany foreign key in tableGUARDIAN.Let us now add foreign key to the table STUDENT.Table 8.3 shows that attribute GUID (the referencingattribute) is a foreign key and it refers to attribute GUID(the referenced attribute) of table GUARDIAN (Table 8.4).Hence, STUDENT is the referencing table and GUARDIANis the referenced table.mysql ALTER TABLE STUDENT- ADD FOREIGN KEY(GUID) REFERENCES- GUARDIAN(GUID);Query OK, 0 rows affected (0.75 sec)Records: 0 Duplicates: 0 Warnings: 0(C) Add constraint UNIQUE to an existing attributeIn GUARDIAN table, attribute GPhone has a constraintUNIQUE which means no two values in that columnshould be same.Syntax:2021-22Chap 8.indd 15019-Jul-19 3:45:57 PM

IntroductiontoStructured Query Language (SQL)151ALTER TABLE table name ADD UNIQUE (attributename);Let us now add the constraint UNIQUE with attributeGPhone of the table GUARDIAN as shown at table 8.4.mysql ALTER TABLE GUARDIAN- ADD UNIQUE(GPhone);Query OK, 0 rows affected (0.44 sec)Records: 0 Duplicates: 0 Warnings: 0(D) Add an attribute to an existing tableSometimes, we may need to add an additional attributein a table. It can be done using the syntax given below:Activity 8.5Add foreign key inthe ATTENDANCEtable (use fig. 8.1 toidentify referencing andreferenced tables).ALTER TABLE table name ADD attribute name DATATYPE;Suppose the principal of the school has decided toaward scholarship to some needy students for whichincome of the guardian must be known. But school hasnot maintained income attribute with table GUARDIANso far. Therefore, the database designer now needs toadd a new attribute income of data type INT in the tableGUARDIAN.mysql ALTER TABLE GUARDIAN- ADD income INT;Query OK, 0 rows affected (0.47 sec)Records: 0 Duplicates: 0 Warnings: 0(E) Modify datatype of an attributeWe can modify data types of the existing attributes of atable using the following ALTER statement.Syntax:ALTER TABLE table name MODIFY attribute DATATYPE;Think and ReflectWhat are the minimumand maximum incomevalues that can beentered in the incomeattribute given the datatype is INT?Suppose we need to change the size of attributeGAddress from VARCHAR(30) to VARCHAR(40) of theGUARDIAN table. The MySQL statement will be:mysql ALTER TABLE GUARDIAN- MODIFY GAddress VARCHAR(40);Query OK, 0 rows affected (0.11 sec)Records: 0 Duplicates: 0 Warnings: 0(F) Modify constraint of an attributeWhen we create a table, by default each attribute takesNULL value except for the attribute defined as primarykey. We can change an attribute’s constraint from NULLto NOT NULL using alter statement.Syntax:ALTER TABLE table name MODIFY attribute DATATYPENOT NULL;Note: We have to specify the data type of the attribute along withconstraint NOT NULL while using MODIFY.2021-22Chap 8.indd 15119-Jul-19 3:45:57 PM

152Informatics Practices – Class XINotesTo associate NOT NULL constraint with attributeSName of table STUDENT (table 8.3), we write thefollowing MySQL statement:mysql ALTER TABLE STUDENT- MODIFY SName VARCHAR(20) NOT NULL;Query OK, 0 rows affected (0.47 sec)Records: 0 Duplicates: 0 Warnings: 0(G) Add default value to an attributeIf we want to specify default value for an attribute, thenuse the following syntax:ALTER TABLE table name MODIFY attribute DATATYPEDEFAULT default value;To set default value of SDateofBirth of STUDENT to15th May 2000, we write the following statement:mysql ALTER TABLE STUDENT- MODIFY SDateofBirth DATE DEFAULT- 2000-05-15;Query OK, 0 rows affected (0.08 sec)Records: 0 Duplicates: 0 Warnings: 0Note: We have to specify the data type of the attribute along withDEFAULT while using MODIFY.(H) Remove an attributeUsing ALTER, we can remove attributes from a table, asshown in the below syntax:ALTER TABLE table name DROP attribute;To remove the attribute income from the tableGUARDIAN (8.4), we can write the following MySQLstatement:mysql ALTER TABLE GUARDIAN DROP income;Query OK, 0 rows affected (0.42 sec)Records: 0 Duplicates: 0 Warnings: 0(I) Remove primary key from the tableWhile creating a table, we may have specified incorrectprimary key. In such case, we need to drop the existingprimary key of the table and add a new primary key.Syntax:ALTER TABLE table name DROP PRIMARY KEY;To remove primary key of table GUARDIAN (Table 8.4),we write the following MySQL statement:mysql ALTER TABLE GUARDIAN DROP PRIMARY KEY;Query OK, 0 rows affected (0.72 sec)Records: 0 Duplicates: 0 Warnings: 0Note: We have dropped primary key from GUARDIAN table, buteach table should have a primary key to maintain uniqueness.Hence, we have to use ADD command to specify primary key forthe GUARDIAN table as shown in earlier examples.2021-22Chap 8.indd 15219-Jul-19 3:45:57 PM

IntroductiontoStructured Query Language (SQL)153Notes8.4.5 DROP StatementSometimes a table in a database or the database itselfneeds to be removed. We can use DROP statement toremove a database or a table permanently from thesystem. However, one should be very cautious whileusing this statement as it cannot be undone.Syntax to drop a table:DROP TABLE table name;Syntax to drop a database:DROP DATABASE database name;Cautions:1) Using the Drop statement to remove a database willultimately remove all the tables within it.2) DROP statement will remove the tables or databasecreated by you. Hence you may apply DROP statement atthe end of the chapter.8.5 SQLforData ManipulationIn the previous section, we created the databaseStudentAttendance having three relations STUDENT,GUARDIAN and ATTENDANCE. When we create a table,only its structure is created but the table has no data.To populate records in the table, INSERT statement isused. Similarly, table records can be deleted or updatedusing SQL data manipulation statements.Data Manipulation using a database means eitherretrieval (access) of existing data, insertion of new data,removal of existing data or modification of existing datain the database.8.5.1 INSERTION of RecordsINSERT INTO statement is used to insert new records ina table. Its syntax is:INSERT INTO tablenameVALUES(value 1, value 2,.);Here, value 1 corresponds to attribute 1, value 2corresponds to attribute 2 and so on. Note that we neednot to specify attribute names in insert statement ifthere are exactly same number of values in the INSERTstatement as the total number of attributes in the table.Caution: While populating records in a table with foreignkey, ensure that records in referenced tables are alreadypopulated.2021-22Chap 8.indd 15319-Jul-19 3:45:58 PM

154Informatics Practices – Class XILet us insert some records in the StudentAttendancedatabase. We shall insert records in the GUARDIANtable first as it does not have any foreign key. We aregoing to insert the records given in Table 8.6.Table 8.6 Records to be inserted into the GUARDIAN tableGUIDGNameGPhoneGAddress444444444444Amit Ahuja5711492685G-35, Ashok Vihar, Delhi111111111111Baichung Bhutia7110047139Flat no. 5, Darjeeling Appt., Shimla101010101010Himanshu Shah981818485526/77, West Patel Nagar, Ahmedabad333333333333Danny Dsouza466444444666Sujata P.S -13, Ashok Village, Daman7802983674HNO-13, B- block, Preet Vihar, MaduraiThe below statement inserts the first record in thetable.mysql INSERT INTO GUARDIAN- VALUES (444444444444, 'Amit Ahuja',- 5711492685, 'G-35,Ashok vihar, Delhi' );Query OK, 1 row affected (0.01 sec)We can use the SQL statement SELECT * from tablename to view the inserted records. The SELECT statementwill be explained in next section.mysql SELECT * from GUARDIAN; -------------- ----------------- ------------ ------------------------------- GUID GName Gphone GAddress -------------- ----------------- ------------ ------------------------------- 444444444444 Amit Ahuja 5711492685 G-35, Ashok vihar, Delhi -------------- ----------------- ------------ ------------------------------- 1 row in set (0.00 sec)If we want to provide values only for some of theattributes in a table (supposing other attributes havingNULL or any other default value), then we shall specifythe attribute name alongside each data value as shownin the following syntax of INSERT INTO statement.Syntax:INSERT INTO tablename (column1, column2, .)VALUES (value1, value2, .);Activity 8.6Write SQL statementsto insert the remaining3 rows of table 8.6 intable GUARDIAN.To insert the fourth record of Table 8.6 where GPhoneis not given, we need to insert values in the other threefields (GPhone was set to NULL by default at the timeof table creation). In this case, we have to specify thenames of attributes in which we want to insert values.The values must be given in the same order in whichattributes are written in INSERT command.mysql INSERT INTO GUARDIAN(GUID, GName, GAddress)- VALUES (333333333333, 'Danny Dsouza',2021-22Chap 8.indd 15419-Jul-19 3:45:58 PM

IntroductiontoStructured Query Language (SQL)155- 'S -13, Ashok Village, Daman' );Query OK, 1 row affected (0.03 sec)Note: Text and date values must be enclosed in ‘ ’ (single quotes).mysql SELECT * from GUARDIAN; -------------- -------------- ------------ ---------------------------------- GUID GName Gphone GAddress -------------- -------------- ------------ ---------------------------------- 333333333333 Danny Dsouza NULL S -13, Ashok Village, Daman 444444444444 Amit Ahuja 5711492685 G-35, Ashok vihar, Delhi -------------- -------------- ------------ ---------------------------------- 2 rows in set (0.00 sec)Let us now insert the records given in Table 8.7 intothe STUDENT table.Table 8.7 Records to be inserted into the STUDENT tableRollNumberSNameSDateofBirthGUID1Atharv Ahuja2003-05-154444444444442Daizy Bhutia2002-02-281111111111113Taleem Shah2002-02-284John Dsouza2003-08-183333333333335Ali Shah2003-07-051010101010106Manika P.2002-03-10466444444666To insert the first record of Table 8.7, we write thefollowing MySQL statementmysql INSERT INTO STUDENT- VALUES(1,'Atharv Ahuja','2003-05-15',- 444444444444);Query OK, 1 row affected (0.11 sec)ORmysql INSERT INTO STUDENT (RollNumber, SName,- SDateofBirth, GUID)- VALUES (1,'Atharv Ahuja','2003-05-15',- 444444444444);Query OK, 1 row affected (0.02 sec)mysql SELECT * from STUDENT; ------------ -------------- -------------- -------------- RollNumber SName SDateofBirth GUID ------------ -------------- -------------- -------------- 1 Atharv Ahuja 2003-05-15 444444444444 ------------ -------------- -------------- -------------- 1 row in set (0.00 sec)Let us now insert the third record of Table 8.7 whereGUID is NULL. Recall that GUID is foreign key of thistable and thus can take NULL value. Hence, we can putNULL value for GUID and insert the record by using thefollowing statement:Recall that Date isstored in “YYYY-MMDD” format.2021-22Chap 8.indd 15519-Jul-19 3:45:58 PM

156Informatics Practices – Class XImysql INSERT INTO STUDENT- VALUES(3, 'Taleem Shah','2002-02-28',- NULL);Query OK, 1 row affected (0.05 sec)mysql SELECT * from STUDENT; ------------ -------------- -------------- -------------- RollNumber SName SDateofBirth GUID ------------ -------------- -------------- -------------- 1 Atharv Ahuja 2003-05-15 444444444444 3 Taleem Shah 2002-02-28 NULL ------------ -------------- -------------- -------------- 2 rows in set (0.00 sec)We had to write NULL in the above MySQL statementbecause when not giving the column names, we needto give values for all the columns. Otherwise, we haveto give names of attributes along with the values if weneed to insert data only for certain attributes, as shownin the next query:Activity 8.7Write SQL statementsto insert the remaining4 rows of table 8.7 intable STUDENT.mysql INSERT INTO STUDENT (RollNumber, SName,- SDateofBirth) VALUES (3, 'Taleem Shah','- 2002-02-28');Query OK, 1 row affected (0.05 sec)In the above statement we are informing DBMSto insert the corresponding values for the mentionedcolumns and GUID would be assigned NULL value.mysql SELECT * from STUDENT; ------------ -------------- -------------- -------------- RollNumber SName SDateofBirth GUID ------------ -------------- -------------- -------------- 1 Atharv Ahuja 2003-05-15 444444444444 3 Taleem Shah 2002-02-28 NULL ------------ -------------- -------------- -------------- 2 rows in set (0.00 sec)Think and Reflect Which of the abovesyntax should beused when we arenot sure of the order(with respect to thecolumn) in whichthe values are to beinserted in the table? Can we insert tworecords with thesame roll number?8.6 SQLforData QuerySo far we have learnt how to create database as wellas to store and manipulate data. We are interested tostore data in a database as it is easier to retrieve datain future from databases in whatever way we want.The Structured Query Language (SQL) has efficientmechanisms to retrieve data stored in multiple tablesin a MySQL database (or any other RDBMS). Theuser enters the SQL commands called queries wherethe specific requirements for data to be retrieved areprovided. The SQL statement SELECT is used to retrievedata from the tables in a database and is also calledquery statement.2021-22Chap 8.indd 15619-Jul-19 3:45:58 PM

IntroductiontoStructured Query Language (SQL)1578.6.1 SELECT StatementThe SQL statement SELECT is used to retrieve data fromthe tables in a database and the output is also displayedin tabular form.Syntax:SELECT attribute1, attribute2, .FROM table nameWHERE conditionHere, attribute1, attribute2, . are the column namesof the table table name from which we want to retrievedata. The FROM clause is always written with SELECTclause as it specifies the name of the table from whichdata is to be retrieved. The WHERE clause is optional andis used to retrieve data that meet specified condition(s).Example 8.2 To display the name and date of birth of studentwith roll number 2, we write the following query:mysql SELECT SName, SDateofBirth- FROM STUDENT- WHERE RollNumber 1; -------------- -------------- SName SDateofBirth -------------- -------------- Atharv Ahuja 2003-05-15 -------------- -------------- 1 row in set (0.03 sec)Think and Reflect8.6.2 QUERYING using Database OFFICEDifferent organisations maintain databases tostore data in the form of tables. Let us consider thedatabase OFFICE of an organisation that has manyrelated tables like EMPLOYEE, DEPARTMENT andso on. Every EMPLOYEE in the database is assignedto a DEPARTMENT and his/her Department number(DeptId) is stored as a foreign key in the table EMPLOYEE.Let us consider some data for the table ‘EMPLOYEE’ asshown in Table 8.8 and apply the SELECT statement toretrieve data:Can you think ofexamples from dailylife where storingand querying datain a database can behelpful?Table 8.8 Gurpreet19000565D04105Joseph34000875D032021-22Chap 8.indd 15719-Jul-19 3:45:58 PM

158Informatics Practices – Class (A) Retrieve selected colum

access data from the database. The Structured Query Language (SQL) is the most popular query language used by major relational database management systems such as MySQL, ORACLE, SQL Server, etc. SQL is easy to learn as the statements comprise of . descriptive English words and are not case