C H A P Ter Structured Query 9 Language (SQL) - NCERT

Transcription

apterhC9Structured QueryLanguage (SQL)“Any unique image that you desireprobably already exists on the internet orin some database. The problem today is nolonger how to create the right image, but how tofind an already existing one. ”— Lev ManovichIn this Chapter»Introduction»Structured Query Language(SQL)»Data Types andConstraints in MySQL»SQL for Data Definition»SQL for DataManipulation»SQL for Data Query»Data Updation andDeletion»Functions in SQL»GROUP BY Clause in SQL»Operations on Relations»Using Two Relations in aQuery9.1 INTRODUCTIONWe have learnt about Relational DatabaseManagement Systems (RDBMS) and its purposein the previous chapter. There are manyRDBMS such as MySQL, Microsoft SQL Server,PostgreSQL, Oracle, etc. that allow us to createa database consisting of relations. These RDBMSalso allow us to store, retrieve and manipulatedata on that database through queries. In thischapter, we will learn how to create, populate andquery databases using MySQL.9.2 STRUCTURED QUERY LANGUAGE (SQL)One has to write application programs to accessdata in case of a file system. However, for databasemanagement systems there are special kinds oflanguages called query language that can be usedto access and manipulate data from the database.The Structured Query Language (SQL) is the mostpopular query language used by major relational2022-23Chpater-9.indd 13118-Jun-21 2:35:43 PM

database management systemsORACLE, SQL Server, etc.Activity 9.1Find and list othertypes of databasesother thanRDBMS.suchasMySQL,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 SQLeasily. Benefit of using SQL is that we do not have tospecify how to get the data from the database. Rather,we simply specify what is to be retrieved, and SQL doesthe rest. Although called a query language, SQL can domuch more, besides querying. SQL provides statementsfor defining the structure of the data, manipulating datain the database, declaring constraints and retrievingdata from the database in various ways, depending onour requirements.In this chapter, we will use the StudentAttendancediscussed in chapter 8 and create a database. Wewill also learn how to populate databases with data,manipulate data and retrieve data from a databasethrough SQL queries.9.2.1 Installing MySQLMySQL is an open source RDBMS software which canbe easily downloaded from the official website https://dev.mysql.com/downloads. After installing MySQL,start MySQL service. The appearance of mysql prompt(Figure 9.1) means that MySQL is ready to accept SQLstatements.Figure 9.1: MySQL ShellFollowing are some important points to be kept inmind while using SQL:COMPUTER SCIENCE - CLASS XII1322022-23Chpater-9.indd 13218-Jun-21 2:35:44 PM

SQL is case insensitive. For example, the columnnames ‘salary’ and ‘SALARY’ are the same for SQL. Always end SQL statements with a semicolon (;). To enter multiline SQL statements, we don’t write “;”after the first line. We press the Enter key to continueon the next line. The prompt mysql then changes to“- ”, indicating that statement is continued to thenext line. After the last line, put “;” and press enter.9.3 DATA TYPESANDCONSTRAINTSINMYSQLWe 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.Activity 9.29.3.1 Data type of AttributeData type of an attribute indicates the type of data valuethat an attribute can have. It also decides the operationsthat can be performed on the data of that attribute.For example, arithmetic operations can be performedon numeric data but not on character data. Commonlyused data types in MySQL are numeric types, date andtime types, and string types as shown in Table 9.1.What are the otherdata types supportedin MySQL? Are thereother variants ofinteger and floatdata type?Table 9.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 (e.g., ‘city’ hasfour characters), MySQL fills the remaining 6 characters with spaces paddedon the right.VARCHAR(n)Specifies character type data of length where n could be any value from 0 to65535. But unlike CHAR, VARCHAR(n) is a variable-length data type. That is,declaring VARCHAR (30) means a maximum of 30 characters can be stored butthe actual allocated bytes will depend on the length of entered string. So ‘city’in VARCHAR (30) will occupy space needed to store 4 characters only.INTINT specifies an integer value. Each INT value occupies 4 bytes of storage. Therange of unsigned values allowed in a 4 byte integer type are 0 to 4,294,967,295.For values 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'.STRUCTURED QUERY LANGUAGE (SQL)1332022-23Chpater-9.indd 13318-Jun-21 2:35:44 PM

Which twoconstraints whenapplied together willproduce a PrimaryKey constraint?9.3.2 ConstraintsConstraints are the certain types of restrictions on thedata values that an attribute can have. Table 9.2 listssome of the commonly used constraints in SQL. Theyare used to ensure correctness of data. However, it isnot mandatory to define constraints for each attributeof a table.Table 9.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/uniqueA default value specified for the column if no value is providedPRIMARY KEYThe column which can uniquely identify each row/record in a table.FOREIGN KEYThe column which refers to value of an attribute defined as primary key in anothertable9.4 SQLFORDATA DEFINITIONIn order to be able to store data we need to first definethe relation schema. Defining a schema includes creatinga relation and giving name to a relation, identifying theattributes in a relation, deciding upon the datatype foreach attribute and also specify the constraints as perthe requirements. Sometimes, we may require to makechanges to the relation schema also. SQL allows us towrite statements for defining, modifying and deletingrelation schemas. These are part of Data DefinitionLanguage (DDL).We have already learned that the data are stored inrelations or tables in a database. Hence, we can saythat a database is a collection of tables. The Createstatement is used to create a database and its tables(relations). Before creating a database, we should beclear about the number of tables the database will have,the columns (attributes) in each table along with thedata type of each column, and its constraint, if any.9.4.1 CREATE DatabaseTo create a database, we use the CREATE DATABASEstatement as shown in the following syntax:CREATE DATABASE databasename;To create a database called StudentAttendance, wewill type following command at mysql prompt.COMPUTER SCIENCE - CLASS XII1342022-23Chpater-9.indd 13418-Jun-21 2:35:44 PM

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/table name in the same letter cases that were used at thetime of their creation.A DBMS can manage multiple databases on onecomputer. Therefore, we need to select the databasethat we want to use. To know the names of existingdatabases, we use the statement SHOW DATABASES.From the listed databases, we can select the database tobe used. Once the database is selected, we can proceedwith creating tables or querying data.In order to use the StudentAttendance database, thefollowing SQL statement is required.Activity 9.3Type the statementshow database; Doesit show the name ofStudentAttendancedatabase?mysql USE StudentAttendance;Database changedInitially, the created database is empty. It can bechecked by using the show tables statement that listsnames of all the tables within a database.mysql SHOW TABLES;Empty set (0.06 sec)9.4.2 CREATE TableAfter creating a database StudentAttendance, we need todefine relations in this database and specify attributesfor each relation along with data type and constraint (ifany) for each attribute. This is done using the CREATETABLE statement.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: The number of columns in a table defines the degreeof that relation, which is denoted by N. Attribute name specifies the name of the column inthe table. Datatype specifies the type of data that an attributecan hold.STRUCTURED QUERY LANGUAGE (SQL)1352022-23Chpater-9.indd 13518-Jun-21 2:35:44 PM

Constraint indicates the restrictions imposed on thevalues of an attribute. By default, each attribute cantake NULL values except for the primary key.Let us identify data types of the attributes of tableSTUDENT along with their constraints (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 a student name(SName) can differ. Assuming maximum characters ina name as 20, we use VARCHAR(20) for the SNamecolumn. Data type for the attribute SDateofBirth isDATE and supposing the school uses guardian’s 12digit Aadhaar number as GUID, we can declare GUID asCHAR (12) since Aadhaar number is of fixed length andwe are not going to perform any mathematical operationon GUID.Table 9.3, 9.4 and 9.5 shows the chosen data type andconstraint for each attribute of the relations STUDENT,GUARDIAN and ATTENDANCE, respectively.Table 9.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 9.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 9.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 key.COMPUTER SCIENCE - CLASS XII1362022-23Chpater-9.indd 13618-Jun-21 2:35:45 PM

Once data types and constraints are identified, let uscreate tables without specifying constraints along withthe attribute name for simplification. We will learn toincorporate constraints on attributes in Section 9.4.4.Example 9.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)Which datatype outof Char and Varcharwill you prefer forstoring contactnumber(mobilenumber)? Discuss.Note: “,” is used to separate two attributes and each statementterminates with a semi-colon (;). The arrow (- ) is an interactivecontinuation prompt. If we enter an unfinished statement, the SQLshell will wait for us to enter the rest of the statement.9.4.3 Describe TableWe can view the structure of an already created tableusing the DESCRIBE statement or DESC statement.Syntax:DESCRIBE tablename;mysql DESCRIBE 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)We can use the SHOW TABLES statement to see thetables in the StudentAttendance database. So far, wehave only the STUDENT table.mysql SHOW TABLES; ------------------------------ Tables in studentattendance ------------------------------ student ------------------------------ 1 row in set (0.00 sec)9.4.4 ALTER TableActivity 9.4Create the other tworelations GUARDIANand ATTENDANCE asper data types givenin Table 9.4 and 9.5respectively, andview their structures.Do not add anyconstraint inthese twotables.After creating a table, we may realise that we need toadd/remove an attribute or to modify the datatype ofan existing attribute or to add constraint in attribute. InSTRUCTURED QUERY LANGUAGE (SQL)1372022-23Chpater-9.indd 13718-Jun-21 2:35:45 PM

all such cases, we need to change or alter the structure(schema) of the table by using the alter statement.(A) Add primary key to a relationLet us now alter the tables created in Activity 9.4. Thefollowing 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 the primary key to the ATTENDANCErelation. The primary key of this relation is a compositekey made up of two attributes - AttendanceDate andRollNumber.Activity 9.5Add foreign key in theATTENDANCE table(use Figure 9.1) toidentify referencingand referencedtables).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). Following points needto be observed while adding foreign key to a relation: The referenced relation must be already created. The referenced attribute(s) must be part of theprimary key of the referenced relation. Data types and size of referenced and referencingattributes must be the same.Syntax:ALTER TABLE table name ADD FOREIGN KEY(attributename) REFERENCES referenced table name(attribute name);Name foreign keys intable ATTENDANCEand STUDENT. Isthere any foreign keyin table GUARDIAN.Let us now add foreign key to the table STUDENT.Table 9.3 shows that attribute GUID (the referencingattribute) is a foreign key and it refers to attribute GUID(the referenced attribute) of table GUARDIAN. Hence,STUDENT is the referencing table and GUARDIAN is thereferenced table as shown in Figure 8.4 in the previouschapter.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, the attribute GPhone has aconstraint UNIQUE which means no two values in thatcolumn should be the same.COMPUTER SCIENCE - CLASS XII1382022-23Chpater-9.indd 13818-Jun-21 2:35:45 PM

Syntax:ALTER TABLE table name ADD UNIQUE (attributename);NOTESLet us now add the constraint UNIQUE with theattribute GPhone of the table GUARDIAN as shown attable 9.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 ADD attributestatement as shown in the following Syntax:ALTER TABLE table name ADD attributename DATATYPE;Suppose, the principal of the school has decided toaward scholarship to some needy students for whichincome of the guardian must be known. But, the schoolhas not maintained the income attribute with tableGUARDIAN so far. Therefore, the database designernow needs to add a new attribute Income of data typeINT in the table GUARDIAN.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 change data types of the existing attributes of atable using the following ALTER statement.Syntax:ALTER TABLE table name MODIFY attribute DATATYPE;Suppose we need to change the size of the 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 an alter statement.STRUCTURED QUERY LANGUAGE (SQL)1392022-23Chpater-9.indd 13918-Jun-21 2:35:45 PM

Syntax:What are theminimum andmaximum incomevalues that can beentered in the incomeattribute given thedata type is INT?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.To associate NOT NULL constraint with attributeSName of table STUDENT (table 9.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, write the following statement:mysql ALTER TABLE STUDENT- MODIFY SDateofBirth DATE DEFAULT ‘2000-0515’;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 following syntax:ALTER TABLE table name DROP attribute;To remove the attribute income from tableGUARDIAN (Table 9.4), 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 tableSometime there may be a requirement to remove primarykey constraint from the table. In that case, Alter tablecommand can be used in the following way:Syntax:ALTER TABLE table name DROP PRIMARY KEY;To remove primary key of table GUARDIAN (Figure9.4), 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: 0COMPUTER SCIENCE - CLASS XII1402022-23Chpater-9.indd 14018-Jun-21 2:35:45 PM

Note: We have dropped the primary key from the GUARDIAN table,but each table should have a primary key to maintain uniqueness.Hence, we have to use the ADD statement with the Alter Tablecommand to specify the primary key for the GUARDIAN table asshown in earlier examples.NOTES9.4.5 DROP StatementSometimes a table in a database or the database itselfneeds to be removed. We can use a DROP statementto remove 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;Note: Using the DROP statement to remove a database willultimately remove all the tables within it.9.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. Also, table records can be deleted or updated usingDELETE and UPDATE statements. These SQL statementsare part of Data Manipulation Language (DML).Data Manipulation using a database means eitherinsertion of new data, removal of existing data ormodification of existing data in the database9.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 the insert statementif there are exactly the same numbers of values in theINSERT statement as the total number of attributes inthe table.Caution: While populating records in a table with foreignkey, ensure that records in referenced tables are alreadypopulated.STRUCTURED QUERY LANGUAGE (SQL)1412022-23Chpater-9.indd 14118-Jun-21 2:35:45 PM

Let us insert some records in the StudentAttendancedatabase. We shall insert records in the GUARDIANtable first as it does not have any foreign key. A setof sample records for GUARDIAN table is shown in thegiven table (Table 9.6).Table 9.6 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 following insert statement adds the first recordin the table: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 * fromtable name to view the inserted records. The SELECTstatement will be explained in the 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)Activity 9.6Write SQL statementsto insert the remaining3 rows of table9.6 in tableGUARDIAN.If we want to insert values only for some of theattributes in a table (supposing other attributes havingNULL or any other default value), then we shall specifythe attribute names in which the values are to be insertedusing the following syntax of INSERT INTO statement.Syntax:INSERT INTO tablename (column1, column2, .)VALUES (value1, value2, .);To insert the fourth record of Table 9.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 statement.COMPUTER SCIENCE - CLASS XII1422022-23Chpater-9.indd 14218-Jun-21 2:35:45 PM

mysql INSERT INTO GUARDIAN(GUID, GName, GAddress)- VALUES (333333333333, 'Danny Dsouza',- '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 9.7 intothe STUDENT table.Table 9.7 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 9.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)Activity 9.7Write SQL statementsto insert theremaining 4 rowsof table 9.7 intable STUDENT.Recall that Date is stored in ‘YYYY-MM-DD’ format.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 9.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:STRUCTURED QUERY LANGUAGE (SQL)1432022-23Chpater-9.indd 14318-Jun-21 2:35:45 PM

mysql 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) Which of the twoinsert statementshould be usedwhen the order ofdata to be insertedare not known? Can we insert tworecords with thesame roll number?We had to write NULL in the above insert statementbecause we are not mentioning the column names.Otherwise, we should mention the names of attributesalong with the values if we need to insert data only forcertain attributes, as shown in the following query:mysql INSERT INTO STUDENT (RollNumber, SName,- SDateofBirth) VALUES (3, 'Taleem Shah','2002-0228');Query OK, 1 row affected (0.05 sec)9.6 SQLFORDATA QUERYSo far we have learnt how to create a database and howto store and manipulate data in them. We are interestedin storing data in a database as it is easier to retrievedata in future from databases in whatever way we want.SQL provides efficient mechanisms to retrieve datastored in multiple tables in MySQL database (or anyother RDBMS). The SQL statement SELECT is used toretrieve data from the tables in a database and is alsocalled a query statement.9.6.1 SELECT StatementThe SQL statement SELECT is used to retrieve datafrom the tables in a database and the output is alsodisplayed in tabular form.Syntax:SELECT attribute1, attribute2, .FROM table nameWHERE condition;Here, 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).COMPUTER SCIENCE - CLASS XII1442022-23Chpater-9.indd 14418-Jun-21 2:35:45 PM

To select all the data available in a table, we use thefollowing select statement:SELECT * FROM table name;Example 9.2 The following query retrieves the name anddate of birth of student with roll number 1: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 list fewexamples from yourdaily life wherestoring the data inthe database andquerying the samecan be helpful.9.6.2 QUERYING using Database OFFICEOrganisations maintain databases to store data in theform of tables. Let us consider the database OFFICEof an organisation that has many related tables likeEMPLOYEE, DEPARTMENT and so on. Every EMPLOYEEin the database is assigned to a DEPARTMENT andhis/her Department number (DeptId) is stored as aforeign key in the table EMPLOYEE. Let us consider therelation ‘EMPLOYEE’ as shown in Table 9.8 and applythe SELECT statement to retrieve data:Table 9.8 Records to be inserted into the EMPLOYEE bha42000D04110Tanya50000467D05(A) Retrieve selected columnsThe following query selects employee numbers of all theemployees:mysql SELECT EmpNo FROM ------- EmpNo ------- 101 102 EMPLOYEE;STRUCTURED QUERY LANGUAGE (SQL)1452022-23Chpater-9.indd 14518-Jun-21 2:35:45 PM

NOTES 103 104 105 106 107 108 109 110 ------- 10 rows in set (0.41 sec)The following query selects the employee numberand employee name of all the employees, we write:mysql SELECT EmpNo, Ename FROM ------- ---------- EmpNo Ename ------- ---------- 101 Aaliya 102 Kritika 103 Shabbir 104 Gurpreet 105 Joseph 106 Sanya 107 Vergese 108 Nachaobi 109 Daribha 110 Tanya ------- ---------- 10 rows in set (0.00 sec)EMPLOYEE;(B) Renaming of columnsIn case we wa

STRUCTURED QUERY LANGUAGE (SQL) 133 SQL is case insensitive. For example, the column names 'salary' and 'SALARY' are the same for SQL. Always end SQL statements with a semicolon (;). To enter multiline SQL statements, we don't write ";" after the first line. We press the Enter key to continue on the next line.