Tuesday, May 21, 2019
Informatic Practile Grade 11 Cbse .
A Text Book on information science PRACTICES CLASS XI Shiksha Kendra, 2, conjunction Centre, Preet Vihar, Delhi-110 092 India A text book on Informatics Practices, Class XI. PRICE Rs. FIRST EDITION 2010 CBSE, India COPIES This book or part thereof may not be reproduced by any person or agency in any manner. PUBLISHED BY The Secretary, Central Board of Secondary Education, Shiksha Kendra, 2, Community Centre, Preet Vihar, Delhi-110092 DESIGN, LAYOUT Multi Graphics, 5745/81, Reghar Pura, Karol Bagh, impudently Delhi-110005, Phvirtuoso 25783846 PRINTED BY ii ForewordInformation and Communication Technology has permeated in every walk of life affecting the technology fields such(prenominal) as launching satellites, managing businesses across the globe and also enabling social net playacting. The convergence of computer, communication and content technologies, being known as ICT, encounter attracted t coating of academia, business, government and communities to use it for innov ative profi defer propositions. Year by year it is becoming simpler to use devices such as desktop, palm top, iPod, etc. 21st hundred is characterized with the emergence of knowledge establish society wherein ICT plays a pivotal role.In its vision, the National Policy on ICT in School Education by MHRD, Govt. of India, states The ICT policy in School Education aims at preparing youth to participate creatively in the establishment, sustenance and g gradeth of a knowledge society leading to each around socio economic burstment of the nation and global competitiveness. The policy envisages three stages of ICT implementations at school level ICT literacy and Competency Enhancement, ICT enabled teachinglearning, and introduction of ICT related nonappointive subjects at Senior Secondary level.With this backdrop a major paradigm shift is imperative in imparting ICT-enabled instructions, collaborative learning, multidisciplinary problem-solving and promoting critical thinking skills as envisaged in the National curriculum framework 2005. Foundation of these skills is laid at school level. Armed with such skills it is expected that a student will translate knowledge into easy to use systems to the ultimate benefit of the society at large.Syllabus of Informatics Practices has been revisited accordingly with a focus on generic concepts with macrocosm specific practical experiments and projects to ensure conceptual knowledge with practical skills. The societal impact of ICT nominate been discussed. A naked Unit on IT Applications has been added to enhance misgiving of the preceding(prenominal) tools and techniques to solve real life problems by designing both front end and back end with proper information connectivity. Introduction of propagate Standards and Open Source to promote Vendor Neutrality of tools.Creativity and Collaborative Learning/Programming is also an added feature. Specific entirelyy, a Unit on Ne 2rking and Open Standards is introduced in pl ace of Business Computing. For IDE based programming, Java is introduced in place of VB. Relational Database trouble System is dealt with using My SQL in place of SQL & PL/SQL using Oracle. The CBSE had been recommending different books in the past. With a total overhauling of the course on Informatics Practices it has ventured to bring out a comprehensive text book for all units for the startle time.I am happy to release Part-1 of Informatics Practices for Class XI. I would like to express my deep appreciation to the text book development team for their contribution and to the convener of the team, Prof. Om Vikas who competently steered this activity. Appreciation is also due to Mrs. C Gurumurthy, Director (Academic) and Dr. (Smt) Srijata Das, Education Officer, for planning, coordinating and executing this initiative and bringing out this publication. It is hoped that all students and teachers will benefit by making best use of this publication.Their feedback will be highly appreciated for further improvement. VINEET JOSHI CHAIRMAN H l d d H d d x , H d H l lt l h d T d x l x d d l L d l td d d t p D l H l d h L l d h l d , d, l D d d h x d h , d l p d h 100 ASkills100 GK100) JOptionPane. showMessageDialog(this,Re-Enter tag (Out of 100)) v if the label input by the drug user for any of the subjects argon greater than 100 Check or not an if they are then(prenominal) viewing the message Re-Enter attach (Out of 100). Since we puddle to march the error message if the tag of even one subject are out of limit so we have utilise the floozy which heart and soul OR.So in simple side it means if attach of English are 100 or tag of ASkills 100 or marks of GK 100, then reveal the error message. So the message will be displayed even if only one condition measures to true. if (ASkills=90 && GK=90 ) JOptionPane. showMessageDialog(this,** Selected for Achievers pillage **) jText bailiwick6. come inText(*) 158 information processing PRACTICES Chapt er-6 restrain Structures v if the marks of ASkills and GK are both = 90 or not. If they are then Check display the message ** Selected for Achievers Award ** and also display a * in the text field.Since we have to check that both the marks should be greater than 90 so we have use the && operator which in simple English means AND. So the condition will evaluate to true only if both the conditions are satisfied. Let us now write the code for the var. calculator application as shown in conjure up 6. 38 unavowed void jButton1ActionPer organize(java. awt. event. ActionEvent evt) // Variable Declaration and assignment operations int Total,English,ASkills,GK English=Integer. parseInt(jTextField1. getText()) ASkills=Integer. parseInt(jTextField2. getText()) GK=Integer. arseInt(jTextField3. getText()) //Validation of Entered Marks if (English100 ASkills100 GK100) JOptionPane. showMessageDialog (this,Re-Enter Marks (Out of 100)) else Total=English+ASkills+GK jTextField4. siteText(In teger. toString(Total)) jButton2. setEnabled(true) private void jButton2ActionPerformed(java. awt. event. ActionEvent evt) // Variable Declaration and assignment operations char Grade int ASkills,GK,Total ASkills=Integer. parseInt(jTextField2. getText()) GK=Integer. parseInt(jTextField3. getText()) Total=Integer. arseInt(jTextField1. getText()) information processing PRACTICES 159 Chapter-6 Control Structures //Decision for Achievers Award if (ASkills=90 && GK=90 ) JOptionPane. showMessageDialog (this,** Selected for Achievers Award **) jTextField6. setText(*) //Finding Grade if (Total=80) jTextField5. setText(A) else if (Total=70) jTextField5. setText(B) else if (Total=60) jTextField5. setText(C) else if (Total=50) jTextField5. setText(D) else jTextField5. setText(E) private void jButton3ActionPerformed(java. awt. event.ActionEvent evt) // To Exit from application System. exit(0) Figure 6. 38 Code for the Grade Calculator Application Since in this application we had to test for four-fold conditions in a if narration, so we had to join the conditions using some operators. Such conditions that are formed by joining simple conditions are called complex conditions and they are usually joined using the logical operators. crystal clear Operator A logical operator denotes a logical operation. Logical operators and relational operators are utilize together to form a complex condition. Logical operators are 160 informatics PRACTICES Chapter-6 Control Structures Operator && Use a10 && b10 bMySQL Command Line Client OR Goto the folder CProgram FilesMySQLMySQL Server 5. 1in as the drive having MySQL And Click on the file cabinet MySQL. EXE MySQL will prompt a message to provide password (it requires the same password which was entered during the installation) Enter Password**** meet to the MySQL monitor. Commands end with or g. Your MySQL connection id is 4 Server version (GPL) 5. 0. 51a-community-nt MySQL Community Edition Assuming C drive Type help o r h for help.Type c to trig the buffer. Mysql To exit from MySQL, type QUIT or EXIT MysqlQUIT The above steps ensure successful installation and configuration of MySQL informationbase server. Next time in the MySQL prompt, one female genital organ occasion and use informationbases, stool boards and execute SQL queries. Downloading MySQL Linux Environment Installation of the binary version of MySQL, release 4. 0. 20, to run on Linux is as follows Installation file for MySQL may be downloaded from the link information science PRACTICES 203 Chapter-8 Introduction to MySQL http//dev. mysql. com/downloads/mysql/5. 1. tmldownloads (Choose appropriate download link as per the desired operating system) Create MySQL User Account cd /usr/local groupadd mysql useradd -c MySQL Software Owner -g mysql mysql passwd mysql Changing password for user mysql. password all authentication tokens updated successfully. Installing Binary Version Unzip the files and change the directory to mysql cd mysql scripts/mysql_install_db user=mysql Preparing db dining turn off Preparing host defer Preparing user accede Preparing func circuit board The latest information about MySQL is available on the web at http//www. ysql. com Support MySQL by buying support/licenses at https// fix up. mysql. com 204 INFORMATICS PRACTICES Chapter-8 Introduction to MySQL Start and Stop The Database Software Starting the MySQL Database su cd /usr/local/mysql bin/mysqld_safe user=mysql & Starting mysqld daemon with databases from /usr/local/mysql/data Stopping the MySQL Database su cd /usr/local/mysql bin/mysqladmin -u root shutdown 040803 233627 mysqld ended 1+ through with(p) Know more Visit the undermentioned website to find a vast number of free and open source softwares available http//en. wikipedia. rg/wiki/List_of_free_and_open_source_software_packages bin/mysqld_safe user=mysql summary A database is an organised collection of data. v Data vis investment trustd in a relati onal database in one or more eludes. A group v of languages and pillars forms a dodge. The horizontal subset of a Table is known as a Row/Tuple. v The vertical subset of a Table is known as a wisespaper column/Attribute. v A medical prognosis key is an attribute (or a set of attributes) that alone(p)ly identifies a v form. A Primary Key is one of the gougedidate keys. Only v one of the Candidate keys is strikeed as the first key of a table. All some other keisterdidate keys are called Alternate keys.INFORMATICS PRACTICES 205 Chapter-8 Introduction to MySQL Multiple Choice Questions 1. A relation can have only one ________ key and may have more than one _______ keys. a) b) c) d) 2. Primary, Candidate Candidate, Alternate Candidate, Primary Alternate, Candidate The vertical subset of a table is known as a) b) c) d) Tuple Row Attribute Relation 3. If software is released under open source, it means a) b) c) d) It is expensive. Its source code is available to the user. It belongs to a company. It is a DBMS. 4. Which of the quest columns in a schoolchild table can be utilize as the primary key? ) b) c) d) Class Section First Name Admission No 5. A tuple is also known as a ___________________________ . a) b) c) d) table relation row field INFORMATICS PRACTICES 206 Chapter-8 Introduction to MySQL 6. An attribute is also known as a_________________________. a) b) c) d) table relation row column 7. A field or a combination of fields in a table that has a unique care for for each row is called a) b) c) d) Candidate key. Foreign key. Main key. Alternate key. Exercises 1. firmness of dissolve the following questions a) Define the following terms i) ii) Database Table iii) Primary key iv) v) b) c) d) e) f) 2. Candidate key Alternate keyWhat is the relationship between a Database and a Table? What is DBMS? Write names of any two DBMSs. How is data organized in a table? What is a Primary key? What is its purpose in a table? What is MySQL? Distinguish bet ween the following pairs a) b) Row and Column Primary key and Candidate key. INFORMATICS PRACTICES 207 9 Learning Objectives after(prenominal) studying this lesson the students will be able to State vcategories of SQL controversys. Create v a database Create v a table. Add rows to a table. v MySQL witness v data in various courses from table using necessitate avowal. Display v data in a sorted way using ORDER BY article.Modify v data stored in a table. View v structure of a table Modify v structure of table Delete v rows from a table In the previous lesson, you have learnt that Relational Databases use tables to store data. A table apparently refers to a two dimensional personifyation of data using columns and rows. MySQL lets us manipulate and manage these tables in an efficient way. We have learnt that MySQL is a Relational Database Management System. In this lesson we will learn about SQL (Structured question Language). It is a Standard language use for accessing and man ipulating relational databases. Ms.Sujata is a Class teacher of Class XI. She requisites to store data of her students i. e. Names and marks secured, in a database. A database is employ to house data in the form of tables. She uses a have DATABASE story to create a new database named School. 208 INFORMATICS PRACTICES Chapter-9 MySQL mysql CREATE DATABASE School Once the above mentioned bidding gets executed, a database with the name School is created on her system. Now she has to open the database to work on it. For this USE statement is required. She opens the School database Statement entered by user mysql USE School Database ChangedDisplay by system Now, MySQL prompt can take on any query related to the database School. Semicolon is standard way to end SQL statement. Creating a table After creating a database, the next step is creation of tables in the database. For this CREATE TABLE statement is used. Syntax CREATE TABLE ( , , , ) Since Ms. Sujata is just learning, she in itially creates a simple table named Learner with only two columns RollNo and Name in the School database. To do this, she enters the following statement mysql CREATE TABLE Learner ( RollNo integer, Name VARCHAR(25) ) INFORMATICS PRACTICES 209 Chapter-9 MySQL v Give meaningful name to a table. If a table will store information about students, name it STUDENTS, not Abc or Person. vnames and column names are not case sensitive. For example, Table STUDENTS is treated the same as STuDents or students. We will study about the CREATE TABLE statement in detail later in this lesson. What if Ms. Sujata wants to chequer the names of all the tables in the database? At any point of time, she can view names of all the tables contained in the current database by using doom TABLES statement as shown below mysql SHOW TABLES ++ Tables_in_school ++ Learner + 1 row in set (0. 00 sec) Once the table named Learner is created, Ms. Sujata would like to add data of students in the table, which is al so known as populating table with rows. To add row(s) in the table she uses the install INTO statement Syntax accede INTO set (,, ,) 210 INFORMATICS PRACTICES Chapter-9 MySQL She inserts 4 rows mysql INSERT INTO Learner determine (14,Aruna Asaf Ali) mysql INSERT INTO Learner VALUES (12,Tarun Sinha) mysql INSERT INTO Learner VALUES (16,John Fedrick) mysql INSERT INTO Learner VALUES (10,Yogi Raj Desai) In INSERT statement Character, date and Time data should be enclosed in Quotes. Numeric set should not be enclosed in quotes. Now that she has added 4 rows in the table, she wants to view the contents of the table. How can she do that? To view the contents of the table, she uses the following exact statement. In the simplest way, withdraw statement is used like this Syntax recognise * FROM So, she types the statement mysql rent * FROM Learner ++ RollNo Name ++ 14 12 16 10 Aruna Asaf Ali Tarun Sinha John Fedrick Yogi Raj Desai + In the above statement, FROM claus e states which table to look in for data. Any time to know the database currently in use, the SELECT DATABASE() statement can be used. INFORMATICS PRACTICES 211 Chapter-9 MySQL mysql SELECT DATABASE() DATABASE() school 1 row in set (0. 0 sec) Statements in MySQL are not case sensitive. It means select DATABASE() or SELECT DATABASE() or SELECT database() would all work the same way. Some Terminologies Keyword A keyword refers to a special word that has a special meaning to SQL. For example, SELECT and FROM are keywords.Clause A clause is a wad of an SQL statement. Each clause is identified by a keyword. For example, consider the statement SELECT name FROM Learner Here SELECT name is a clause. SELECT is a statement as well as a clause. SELECT clause is everything from keyword SELECT until keyword FROM. SELECT statement is the entire command. FROM Learner is a FROM clause, which specifies the table from which data has to be selected. Statement A statement is a combination of two or more clauses. For example, SELECT name FROM Learner is a statement. 212 INFORMATICS PRACTICES Chapter-9 MySQLMySQL Data Types Well, before we learn more about making a table, there is one thing we need to understand first Data Types. They exhibit the type of data that you are storing in a stipulation table column. So, what are the different Data Types available in MySQL? Here is a list of some of the most common ones and what type of determine they hold Class Text Data Type CHAR(size) Description A fixed-length get from 1 to 255 characters in length right-padded with spaces to the specify length when stored. Values must be enclosed in single quotes or double quotes. typeface Maths TexT VARCHAR(size)A variable-length suck from 1 to 255 characters in length for example VARCHAR(25). Values must be enclosed in single quotes or double quotes. Computer Me and u Numeric DECIMAL(size,d) It can represent number with or without the fractional part. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the quantitative point is specified in the d parameter INT Or INTEGER It is used for storing integer values. You can specify a width upto 11 digits. 17. 32 345 76 INFORMATICS PRACTICES 213 Chapter-9 MySQL Date DATE It represents the date including day, month and year It represents time.Format HHMMSS Note The supported range is from -8385959 to 8385959 2009-0702 judgment of conviction() TIME Categories of SQL Commands SQL commands can be classified into the following categories 1. Data Definition Language (DDL) Commands The DDL part of SQL permits database tables to be created or deleted. It also defines indices (keys), specifies links between tables, and imposes constraints on tables. object lessons of DDL commands in SQL are v CREATE DATABASE creates a new database v CREATE TABLE creates a new table v TABLE modifies a table transmute v TABLE deletes a table drib 2. The Data Manipulation Language (DML) CommandsThe query and update commands form the DML part of SQL Examples of DDL commands are v SELECT extracts data from a table v UPDATE updates data in a table v strike down deletes data from a table v INSERT INTO inserts new data into a table CREATE TABLE Ms. Sujata feels good that she has successfully created a table named Learner with 2 columns using CREATE TABLE statement. She now creates a table named disciple with 214 INFORMATICS PRACTICES Chapter-9 MySQL four columns. When tables are created its columns are named, data types and sizes are supplied for each column. While creating a table at least one column must be specified.Syntax CREATE TABLE ( column name , ( column name , ) Example mysql USE school Database changed mysql CREATE TABLE learner( Rollno INTEGER, Name VARCHAR(25), gender CHAR(1), Marks1 DECIMAL(4,1)) Query OK, 0 rows affect (0. 16 sec) If table scholar already exists in database school, then the error message Table savant already exists is displayed. Each column in the table is given a unique name. In the example above the column names are Rollno, Name etc. This doesnt mean each column that is named has to be unique within the entire database.It only has to be unique within the table where it exists. Also notice that the names do not use any spaces. When naming tables and columns be sure to keep it simple with earn and numbers. Spaces and images are invalid characters except for underscore(_). Column names like first_name,last_name,email are valid column names. Viewing Structure of Table The DESCRIBE statement can be used to wait the structure of a table as indicated in the Create Statement. It displays the Column names, their data types, whether Column must contain data ,whether the Column is a Primary key etc.INFORMATICS PRACTICES 215 Chapter-9 MySQL Syntax DESCRIBE OR DESC mysql DESCRIBE Student Statement entered by user ++++++-+ Field Type bootless Key Default Extra ++++++-+ Rollno int(11) Name va rchar(25) YES YES YES unreal NULL NULL NULL Output shown by system Gender char(1) Marks1 decimal(4,1) YES ++++++-+ 4 rows in set (0. 01 sec) Ms.Sujata adds some rows in the Student table using the INSERT INTO statement INSERT INTO Student VALUES (1,Siddharth Sehgal,M,93) INSERT INTO Student VALUES (2,Gurpreet Kaur,F,91) INSERT INTO Student VALUES (3,Monica genus Rana,F,93) INSERT INTO Student VALUES (4,Jatinder Sen,M,78) INSERT INTO Student VALUES (5,George Jacob,M,76) INSERT INTO Student VALUES (6,Deepa Bhandari,F,77) INSERT INTO Student VALUES (7,Akshay Nath,M,65) Changing Structure of table When we create a table we define its structure. We can also change its structure i. e. add, remove or change its column(s) using the ALTER TABLE statement.Syntax ALTER TABLE ADD/DROP datatype ALTER TABLE MODIFY 216 INFORMATICS PRACTICES Chapter-9 MySQL Example Ms. Sujata adds a column named Games. mysql ALTER TABLE Student ADD Games VARCHAR(20) Now she wants to check the structure of the table to see that the new column Games is added. mysql DESCRIBE Student ++++++-+ Field Type Null Key Default Extra ++++++-+ Rollno int(11) Name varchar(25) YES YES YES NULL NULL NULL NULL NULL Gender char(1) Marks1 decimal(4,1) YES Games varchar(20) YES ++++++-+ 5 rows in set (0. 00 sec) After slaying of the above ALTER TABLE statement, the Games column is added and a NULL value is assigned to all the rows in this column. mysql SELECT * FROM Student +++++-+ Rollno Name 1 Siddharth Sehgal 2 Gurpreet Kaur 3 Monica Rana 4 Jatinder Sen 5 George Jacob 6 Deepa Bhandari 7 Akshay Nath Gender Marks1 M F F M M F M 93. 91. 0 93. 0 78. 0 76. 0 77. 0 65. 0 Games NULL NULL NULL NULL NULL NULL NULL +++++-+ +++++-+ INFORMATICS PRACTICES 217 Chapter-9 MySQL Now, suppose we want to change the newly added Games column to hold integers(in place of character data) using ALTER TABLE statement mysql ALTE R TABLE Student MODIFY games INTEGER To delete a column of a table the ALTER TABLE statement is used with Drop clause. Ms.Sujata deletes the Games column using the ALTER TABLE statement mysql ALTER TABLE Student DROP Games mysql DESC student ++++++-+ Field Type Null Key Default Extra ++++++-+ Rollno int(11) Name varchar(25) YES YES YES NULL NULL NULL NULL Gender char(1) Marks1 decimal(4,1) YES ++++++-+ 4 rows in set (0. 00 sec) The above display shows that Games column is removed from the table. The word DESC can also be used in place of DESCRIBE Retrieving Information with SELECT Statement The SELECT statement is used to fetch data from one or more database tables. Retrieving Single Column Here is the syntax of SELECT statement to retrieve a single column from a table Syntax SELECT FROM 218 INFORMATICS PRACTICES Chapter-9 MySQL Example Ms. Sujata wants to display Roll numbers of all her students. She uses the following statement mysql SELECT Roll no FROM Student +- + Rollno +- + 1 2 3 4 5 6 7 - + 7 rows in set (0. 00 sec) Retrieving Multiple Columns We can display more than one column(s) from a table using SELECT statement Syntax SELECT , FROM Example Now, Ms. Sujata displays two columns Roll numbers and names of all the students. mysql SELECT Rollno, Name FROM Student +- ++ Rollno Name +- ++ 1 2 Siddharth Sehgal Gurpreet Kaur 219 INFORMATICS PRACTICES Chapter-9 MySQL 3 4 5 6 7 Monica Rana Jatinder Sen George Jacob Deepa Bhandari Akshay Nath +- ++ 7 rows in set (0. 00 sec) Changing the order of display of Columns We can display columns in any order by specifying the columns in that order in SELECT statement . The following statement displays Names first and then Roll numbers from the table Student. mysql SELECT Name,Rollno FROM Student +++ Name Rollno +++ Siddharth Sehgal Gurpreet Kaur Monica Rana Jatinder Sen George Jacob Deepa Bhandari Akshay Nath 1 2 3 4 5 6 7 ++ 7 rows in set (0. 00 sec) In the Output, notice that the first column displaying names is left-justified and the second column displaying roll numbers is right justified. The format of product follows the pattern that character data is left justified and numeral data is right justified. 220 INFORMATICS PRACTICES Chapter-9 MySQL Retrieving all Columns To see all the columns of the table, we can write * in place of names of all the columns. The columns are displayed in the order in which they are stored in the table. Ms.Sujata uses the following statement to see all the columns of her table mysql SELECT * FROM Student +++++ Rollno Name Gender Marks1 +++++ 1 2 3 4 5 6 7 Siddharth Sehgal Gurpreet Kaur Monica Rana Jatinder Sen George Jacob Deepa Bhandari Akshay Nath M F F M M F M 93. 0 91. 0 93. 0 78. 0 76. 0 77. 0 65. 0 +++++ 7 rows in set (0. 00 sec) The asterisk (*) means All.SELECT * means display all columns Eliminating couple values By sl ackness data is displayed from all the rows of the table, even if the data in the result is duplicated. Using the keyword DISTINCT, the duplicate values can be eliminated in the result. When DISTINCT keyword is specified, only one instance of the duplicated data is shown. The following query without the DISTINCT keyword shows 7 rows while the same query with DISTINCT keyword shows 6 rows as duplicate data 93 is displayed only once. INFORMATICS PRACTICES 221 Chapter-9 MySQL mysql SELECT Marks1 FROM Student ++ Marks1 ++ 93. 91. 0 93. 0 78. 0 76. 0 77. 0 65. 0 93 displayed twice ++ 7 rows in set (0. 00 sec) mysql SELECT DISTINCT Marks1 FROM Student ++ Marks1 ++ 93. 0 91. 0 78. 0 76. 0 77. 0 65. 0 ++ 6 rows in set (0. 00 sec) 222 INFORMATICS PRACTICES Chapter-9 MySQL Retrieving Data From All Rows If we write the keyword ALL in place of DISTINCT, then the result of SELECT query displays all the values including duplicate values. The end product is the same as what we get when we do not write DISTINCT keyword in the SELECT query.Using Arithmetic Operators with SELECT Arithmetic operators answer mathematical calculations. In SQL the following arithmetic operators are used Operator + * / % What it does Addition Subtraction Multiplication Division Modulus (or remainder) Modulus operator (%) returns the remainder of a division. We can perform simple arithmetic computations on data using SELECT statement. Ms. Sujata thinks what if all my students had secured 5 marks more. She enters the following statement to display marks of all students increase by 5. mysql SELECT Marks1+5 FROM Student +-+ Marks1+5 +-+ 98. 96. 0 98. 0 83. 0 81. 0 82. 0 70. 0 +-+ 7 rows in set (0. 02 sec) INFORMATICS PRACTICES 223 Chapter-9 MySQL Marks1 column is displayed increased by 5. The actual values are not increased in the table. Here are some more examples mysql SELECT Name,Marks1+0. 05*Marks1 FROM Student mysql SELECT Name,Marks1-10 FROM Studen t mysql SELECT Name,Marks1/2 FROM Student Using these operators on tables does not create new columns in the tables or change the actual data values. The results of the calculations appear only in the output.In the above examples, arithmetic calculations were based on Student table. Arithmetic calculations may not always be based on tables. For example when we want to compute 7*3+1, there is no table to be referenced. In such queries no FROM clause is used mysql SELECT 7*3+1 +-+ 7*3+1 +-+ 22 +-+ 1 row in set (0. 09 sec) mysql SELECT 71+34 +-+ 71+34 +-+ 105 +-+ 1 row in set (0. 00 sec) 224 INFORMATICS PRACTICES Chapter-9 MySQL Using Column Alias Till now, we have seen that when the result of an SQL statement is displayed, the heading displayed at the top of column is same s the column name in the table or the arithmetic operation being through on the Column. While displaying marks from the table Student, Ms. Sujata wants the output to display a column heading (for Marks) that is easier to understand and is more meaningful and presentable like Marks Secured instead of Marks1. Column alias lets different name (heading) to appear for a column than the actual one in the output. She enters the statement like this mysql SELECT Marks1 AS Marks Secured FROM Student ++ Marks Secured ++ 93. 91. 0 93. 0 78. 0 76. 0 77. 0 65. 0 ++ 7 rows in set (0. 00 sec) Notice that the column Marks1 has been given the column heading Marks Secured . If a column alias consists of more than one word ,then it should be enclosed in quotes as in Marks Secured,otherwise error message is displayed. Using Column Alias does not rename a column. It simply displays a different column name in the output. The AS keyword between the column name and alias is optional. We can also write SELECT Marks1 Marks Secured FROM Student INFORMATICS PRACTICES 225Chapter-9 MySQL Putting text in Query output Can Ms. Sujata make the query output more presentable by inserting items such as symbols or text in the query output ? Yes. She can. She uses the following statement. mysql SELECT Rollno,Name,has secured marks,marks1 FROM student +++-++ Rollno Name has secured marks marks1 +++-++ 1 Siddharth Sehgal has secured marks 2 Gurpreet Kaur 3 Monica Rana 4 Jatinder Sen 5 George Jacob 6 Deepa Bhandari 7 Akshay Nath has secured marks has secured marks has secured marks has secured marks has secured marks has secured marks 93. 0 91. 0 93. 0 78. 0 76. 0 77. 0 65. 0 +++-++ 7 rows in set (0. 00 sec) The text has secured marks is displayed with every row of the table. Retrieving specific rows WHERE clause Tables usually contain many rows. Mostly, we do not want to display all the rows of a table. accepted rows can be displayed based on the criteria for selection of rows using the keyword WHERE. The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified criterion. Syntax SELECT , ,. FROM WHERE Ms. Sujata wants to display the names and marks of all those students who have secured marks above 80, she enters 226 INFORMATICS PRACTICES Chapter-9 MySQL mysql SELECT Name,Marks1 FROM Student WHERE Marks1 80 ++-+ Name Marks1 ++-+ Siddharth Sehgal Gurpreet Kaur Monica Rana 93. 91. 0 93. 0 ++-+ 3 rows in set (0. 00 sec) She thinks What would be the marks of my students if they were increased by 5 for all those students who secured marks below 80? She enters the statement mysql SELECT Name,Marks1+5 FROM Student WHERE marks1 = SELECT * FROM Student WHERE Marks1=93 +++++ Rollno Name Gender Marks1 +++++ 1 3 Siddharth Sehgal Monica Rana M F 93. 0 93. 0 +++++ 2 rows in set (0. 6 sec) When we use relational operators with character data type, means earlier in the alphabet and means later in the alphabet. Aman Ayan as m comes before y in alphabet. Some more examples of queries involving relational expressions mysql SELECT Name,Marks1 FROM Student WHER E Marks1 SELECT * FROM Student WHERE Name = Gurpreet Kaur mysql SELECT RollNo,Marks1 FROM Student WHERE Rollno SELECT RollNo,Marks1 FROM Student WHERE Rollno 3 mysql SELECT RollNo,Marks1 FROM Student WHERE Name Mani Kumar 228 INFORMATICS PRACTICESChapter-9 MySQL Logical Operators OR, AND, not logical operators are used in SQL. Logical operators OR and AND are used to connect relational expressions in the WHERE clause. If any of the comparisons are true, OR returns TRUE. AND requires both conditions to be true in order to return TRUE. NOT negates a condition. If a condition returns a True value, adding NOT causes the condition to return a False value and vice versa. The symbol can be used in place of OR, && can be used in place of AND, can be used in place of NOT operator. Ms.Sujata uses the following statement (with Logical operator AND) to display Roll numbers and names of students who have secured marks above 70 but below 80. mysql SELECT Rollno, Name,Marks1 FROM Student WHERE M arks1 70 AND Marks1 80 ++-++ Rollno Name Marks1 ++-++ 4 5 6 Jatinder Sen George Jacob Deepa Bhandari 78. 0 76. 0 77. 0 ++-++ 3 rows in set (0. 01 sec) Some example of SQL statements with Logical operators are shown below. ysql SELECT Empnumber, EmpName FROM Employee WHERE Department = Accoumts OR Department = Personnel mysql SELECT Empnumber, EmpName FROM Employee WHERE Department = Accoumts AND Designation = Manager mysql SELECT Empnumber, EmpName FROM Employee WHERE NOT(Designation = Manager) mysql SELECT Name,TotalMarks FROM Candidate WHERE writtenmarks80 Interviewmarks10 SELECT Name,TotalMarks FROM Candidate WHERE writtenmarks80 && Interviewmarks10 INFORMATICS PRACTICES 229 Chapter-9 MySQL Using Parenthesis in WHERE clause Sometimes we have to write a criterion using a combination of AND and OR.The parentheses not only help us visually see how things are grouped together but they also let the DBMS know exactly what to do. SELECT * FROM Emp WHERE first_name=Ami t AND (last_name=Sharma OR last_name=Verma) So, how does that work? It simply states that we are aspect for anyone with the first name as Amit and the last name as Sharma or Verma. They must have the first name as Amit but can have the last name as either Sharma or Verma. Condition based on Range The BETWEEN operator defines the range of values within which the column values must fall into to make the condition true. The range includes both the upper and lower values.Ms. Sujata uses the following statement to display roll numbers and marks of students who have secured marks in the range 70 to 80 (including 70 and 80). mysql SELECT Rollno,Name,Marks1 FROM Student WHERE Marks1 BETWEEN 70 AND 80 ++-++ Rollno Name Marks1 ++-++ 4 5 6 Jatinder Sen George Jacob Deepa Bhandari 78. 0 76. 0 77. 0 ++-++ 3 rows in set (0. 06 sec) The following statement displays roll numbers and marks of students who have secured marks other than the ones in the range 70 to 80(including 70 and 80). 30 INFORMATICS PRACTICES Chapter-9 MySQL mysql SELECT Rollno,Name,Marks1 FROM Student WHERE Marks1 NOT BETWEEN 70 AND 80 BETWEEN displays all values between the lower and the upper values including the lower and the upper values. To display marks in the range 70 to 80, Ms. Sujata could have used the following statement to give the same output as the one using BETWEEN operator. mysql SELECT Rollno,Name,Marks1 FROM Student WHERE Marks1=70 AND Marks1 SELECT Rollno, Name, Marks1 FROM Student WHERE Marks1 IN (68,76,78) +-+++ Rollno Name Marks1 -+++ 4 5 Jatinder Sen 78. 0 76. 0 George Jacob +-+++ 2 rows in set (0. 00 sec) In an Employee table, to display rows where State is DELHI or MUMBAI or UP, we write the query like this SELECT * FROM Employee WHERE State IN (DELHI,MUMBAI,UP) In an Employee table, to display all rows except those that have State as DELHI or MUMBAI or UP, we write the query like this INFORMATICS PRACTICES 231 Chapter-9 MySQL SELECT * FROM Employee WHE RE State NOT IN (DELHI,MUMBAI,UP) Till now Ms.Sujatas table Student has 7 rows. She wants to populate it with some more rows. She uses the following INSERT INTO statement. INSERT INTO Student VALUES (8,Samdisha Sen,F,76) INSERT INTO Student VALUES (9,Geeta Sen Sharma,F,91) INSERT INTO Student VALUES (10,Geet Kadamb,M,66) INSERT INTO Student VALUES (11,Aman Ali,M,92) INSERT INTO Student VALUES (12,Ayan Ali,M,87) She checks that the table has the new rows inserted by using the following SELECT statement SELECT * FROM Student +++++ Rollno name Gender Marks1 ++++ 1 2 3 4 5 6 7 8 9 10 11 12 Siddharth Sehgal Gurpreet Kaur Monica Rana Jatinder Sen George Jacob Deepa Bhandari Akshay Nath Samdisha Sen Geeta Sen Sharma Geet Kadamb Aman Ali Ayan Ali M F F M M F M F F M M M 93 91 93 78 76 77 65 76 91 66 92 87 +++++ 12 rows in set (0. 00 sec) 232 INFORMATICS PRACTICESChapter-9 MySQL Condition based on pattern matches Sometimes whil e trying to think about somebodys name, you remember a part of his/her name but not the exact name. In such cases, MySQL has wildcards to help you out. % and _ are two wild card characters. The percent (%) symbol is used to represent any sequence of zero or more characters. The underscore (_) symbol is used to represent a single character. LIKE clause is used to fetch data which matches the specified pattern from a table.The LIKE clause tells the DBMS that we wont be doing a strict comparison like = or or but we will be using wildcards in our comparison. Syntax SELECT , WHERE LIKE Pattern AND OR For example, Ms. Sujata wants to display details of students who have their names ending with Sen, she enters mysql SELECT * FROM Student WHERE Name LIKE %Sen ++++-+ Rollno Name Gender Marks1 ++++-+ 4 Jatinder Sen M 8 Samdisha Sen F 78. 76. 0 ++++-+ 2 rows in set (0. 00 sec) To display rows from the table Student with names commencement with G, she enters mysql SELECT * FROM Student WHERE Name LIKE G% ++++-+ Rollno name Gender Marks1 ++++-+ 2 Gurpreet Kaur F 91. 0 233 INFORMATICS PRACTICES Chapter-9 MySQL 5 George Jacob 9 Geeta Sen Sharma 10 Geet Kadamb M F M 76. 0 91. 66. 0 ++++-+ 4 rows in set (0. 02 sec) To display rows that have names starting with G and ending with b, she enters mysql SELECT * FROM Student WHERE Name LIKE G%b +-++-++ Rollno name Gender Marks1 +-++-++ 5 10 George Jacob Geet Kadamb M M 76. 0 66. 0 +-++-++ 2 rows in set (0. 0 sec) To display rows from the table Student that have Sen anywhere in their names, she enters mysql SELECT * FROM Student WHERE Name LIKE %Sen% +-++-++ Rollno name Gender Marks1 +-++-++ 4 8 9 Jatinder Sen Samdisha Sen Geeta Sen Sharma M F F 78 76 91 +-++-++ 3 rows in set (0. 00 sec) 234 INFORMATICS PRACTICES Chapter-9 MySQLTo display rows that have names starting with A and then having any 4 characters and ending with Ali, she uses underscore wild card like this mysql SELECT * FROM Student WHERE Name LIKE A_ _ _ _ Ali +-++-++ Rollno name Gender Marks1 +-++-++ 11 12 Aman Ali Ayan Ali M M 92. 0 87. 0 +-++-++ 2 rows in set (0. 00 sec) Some more examples Am% matches any string starting with Am. %Singh% matches any string containing Singh %a matches any string ending with a _ _ _ matches any string that is exactly 3 characters long. _ _ % matches any string that has at least 2 characters. _ _ _ g matches any string that is 4 characters long with any 3 characters in the beginning but g as the 4th character. The keyword NOT LIKE is used to select the rows that do not match the specified pattern. To display rows from the table Student that have names not starting with G, she enters mysql SELECT * FROM Student WHERE Name NOT LIKE G% Precedence of Operators All the operators have precedence.Precedence is the order in which different operators are evaluated in the same expression. When evaluating an expression containing INFORMATICS PRACTICES 235 Chapter-9 MySQL multiple operators, operators with higher precedence are evaluated before evaluating those with lower precedence. Operators with equal precedence are evaluated from left to right within the expression. Parenthesis can be used to change the preference of an operator. Various operators in locomote order of precedence (top to bottom) are listed below (unary minus) *, /, DIV, %, MOD -, + =, , =, , INSERT INTO Student(Rollno,Marks1) VALUES (14,45) Query OK, 1 row abnormal (0. 05 sec) Since values are provided only for Roll number and marks, Ms. Sujata uses the SELECT statement and notices the word NULL displayed for Name and Gender for Roll number 14 mysql SELECT * FROM Student WHERE Rollno =14 ++++-+ Rollno name Gender Marks1 ++++-+ 14 NULL NULL 45. 0 ++++-+ 1 row in set (0. 0 sec) explicitly Inserting NULL Values We have learnt that if a column can hold NULL values, it can be omitted from the INSERT INTO statement. INSERT INTO statement will mechanically insert a null value in that column. This is called Implicitly inserting a NULL value. mysql INSERT INTO Student(Rollno,Name,Gender) Values(15,Charvi Chanana,F) Query OK, 1 row affected (0. 11 sec) In the above INSERT INTO statement Marks1 column is omitted, therefore NULL value will be inserted for it. We can also explicitly add NULL value by using the NULL keyword in the VALUES list for those columns that can hold null values. ysql INSERT INTO Student Values(14,Siddharth Sehgal,M,NULL) Query OK, 1 row affected (0. 11 sec) 242 INFORMATICS PRACTICES Chapter-9 MySQL A NULL value means no value has been entered for that column i. e. the value for that column is not known. Inserting Date Values The default way to store a date in MySQL is with the type DATE. Below is the format of a DATE. YYYY-MM-DD To insert the current date into a table, MySQLs built-in go away CURDATE() can be used in the query. Following are some examples of inserting date values. ysql INSERT INTO my_ table (idate) VALUES (19970505) mysql INSERT INTO my_table (idate) VALUES (97-05-05) mysql INSERT INTO my_table (idate) VALUES (1997. 05. 05) mysql INSERT INTO my_table (idate) VALUES (0000-00-00) While Inserting data v Text values must be enclosed in quotes. v Standard date format is yyyy-mm-dd. v Standard time format is hhmmss. v are required around the standard date and time formats. Quotes UPDATE STATEMENT In the table student, Ms. Sujata entered a students marks as 93.Suppose, that student found out that one of her answers was unchecked and got her marks increased by 1. How would Ms. Sujata change it in the table? She can use the UPDATE statement to modify existing data in the table. (a) Syntax UPDATE club = , = , WHERE INFORMATICS PRACTICES 243 Chapter-9 MySQL The statement can be used to update one or more columns together. WHERE clause helps in updation of particular rows in a table. The following statement sets the marks(Mark1) of all the rows to 94. UPDATE Student SET Marks1 = 94 The following statement sets the marks(Mark1) of the row with name as Monica Rana to 94. ysql UPDATE Student SET Marks1 = 94 WHERE name = Monica Rana Query OK, 1 row affected (0. 03 sec) Rows matched 1 Changed 1 Warnings 0 The marks displayed from the table shows 94 marks now mysql SELECT Name,Marks1 FROM Student WHERE Name = Monica Rana Output +++ Name Marks1 +++ Monica Rana 94 +++ 1 row in set (0. 00 sec) What if Ms. Sujata wants to change the name and marks both at the same time? Multiple columns can also be updated at one time.The following statement changes the name to Chhavi Chanana and Marks to 90 for the roll number 15. mysql UPDATE Student SET name = Chhavi Marks1= 90 WHERE Rollno = 15 Output Query OK , 1 row affected (0. 8 sec) 244 INFORMATICS PRACTICES Chanana, Chapter-9 MySQL cancel STATEMENT Sometimes students leave school or an employee leaves an organization. Their rows have to be deleted from the table. Deleting data from a table is very simple. D ELETE statement is used to delete rows from a table. DELETE removes the entire row, not the individual column values.Care must be taken while using this statement as accidentally important data may get deleted. Syntax mysql DELETE FROM tablename Where condn One of the students with Roll number 14 has left the school and Ms. Sujata wants to delete his/her row. She uses the following statement to delete the row with roll number 14. mysql DELETE FROM Student WHERE Rollno = 14 Query OK, 1 row affected (0. 03 sec) DELETE statement can be used to delete all rows of the table also . The following statement can be used to delete all the rows from Student table. ysql DELETE from Student mysql Select * FROM Student ++++-+ Rollno Name Gender Marks1 ++++-+ ++++-+ 0 row in set (0. 01 sec) Know more The MySQL database management system contains an enormous amount of functionality and power. Using a simple set of statements for inserting, retrieving, deleting and updating data, we can develop quite a useful set of databases and tables. To learn more about MySQL you may visit the website http//www. mysqltutorial. org INFORMATICS PRACTICES 245 Chapter-9 MySQLSummary 1. 2. 3. 4. 5. 6. 7. 8. CREATE DATABASE statement is used to create a new database. CREATE TABLE statement is used to create a new table. INSERT INTO statement is used to insert a new row in a table. The SELECT statement is used to fetch data from one or more database tables. SELECT * means display all columns. The WHERE clause is used to select specific rows. The DESCRIBE statement is used to see the structure of a table. We can change the structure of a table ie. add, remove or change its column(s) using the ALTER TABLE statement. The keyword DISTINCT is used to eliminate redundant data from display. a) Logical operators OR and AND are used to connect relational expressions in the WHERE clause. Logical operator NOT is used to negate a condition. 9. 10. (b) 11. The BETWEEN operator defines the range of values that the column values must fall into to make the condition true. The IN operator selects values that match any value in the given list of values. % and _ are two wild card characters. The percent (%) symbol is used to represent any sequence of zero or more characters. The underscore (_) symbol is used to represent a single character. NULL represents a value that is unavailable, unassigned, unknown or inapplicable.The results of the SELECT statement can be displayed in the ascending or descending order of a single column or columns using ORDER BY clause. UPDATE statement is used to modify existing data in a table. DELETE statement is used to delete rows from a table. 12. 13. 14. 15. 16. 17. 246 INFORMATICS PRACTICES Chapter-9 MySQL Multiple Choice questions 1. Which statement is used to extract data from a table? A. B. C. D. 2. SELECT DISPLAY READ EXTRACT How do you select all the columns from a table named Employee? A. B. C. D. SELECT all FROM Employee SELECT Employee SELEC T * BY Employee SELECT * FROM Employee . How do you select a column named IName from a table named Inventory? A. B. C. D. SELECT Inventory FROM Iname DISPLAY Iname SELECT Iname FROM Inventory FROM Inventory SELECT Iname, Inventory FROM Iname 4. Which of the following are valid column names? A. B. C. D. Marks Eng 66_Marks Marks_Eng Eng_Marks 5. SELECT statement can be used to perform these functions. A. B. C. D. Insert rows into a table. Choose and display columns from a table. Modify data in a table. Select and display structure of a table INFORMATICS PRACTICES 247 Chapter-9 MySQL 6. Which statement is used to insert new data in a table?A. B. C. D. ADD RECORD INSERT RECORD INSERT INTO INSERT ROW 7. How would you display all those rows from a table named Friends where the value of the column Hobbies is SWIMMING A. B. C. D. SELECT ALL FROM Friends WHERE Hobbies IS SWIMMING SELECT * FROM Friends WHERE Hobbies=SWIMMING SELECT * FROM Friends WHERE Hobbies = Swimming SELECT ALL FROM Fri ends WHERE Hobbies SWIMMING 8. Which statement is used to modify data in a table? A. B. C. D. CHANGE MODIFY UPDATE SAVE AS 9. Which SQL statement is used to delete data from a table? A. B. C. D. DELETE DROP TRUNCATE REMOVE 10.How do you select all the rows from a table named Student where the value of the column FName starts with G? A. B. C. D. SELECT * FROM Student WHERE FName LIKE G_ SELECT * FROM Student WHERE FName=G SELECT * FROM Student WHERE FName LIKE G% SELECT * WHERE Student WHERE FName=%G% INFORMATICS PRACTICES 248 Chapter-9 MySQL 11. The OR operator displays a record if ANY of the conditions listed are true. The AND operator displays a record if ALL of the conditions listed are true A. B. False True 12. Which keyword is used to return only different values in a column? A. B. C. D. DIFFERENT EXCLUSIVE DISTINCT UNIQUE 3. Which SQL keyword(s) is/are used to sort the rows in the output A. B. C. D. SORTED ORDER SORT SORT BY ORDER BY 14. How would you return all the rows f rom a table named stage sorted in descending order on the column IName? A. B. C. D. SELECT * FROM Item SORT IName DESC SELECT * FROM Item ORDER BY IName DESC SELECT * FROM Item ORDER IName DESC SELECT * FROM Item SORT BY IName DESC 15. How can you insert a new row into the inventory table? A. B. C. D. INSERT (1,Abc Rice) INTO Store INSERT VALUES (1,Abc Rice) INTO Store INSERT INTO Store VALUES (1,Abc Rice) ADD ROW Store values(1,Abc Rice)INFORMATICS PRACTICES 249 Chapter-9 MySQL 16. Which statement is appropriate to change the first name Madhur to Mridul in the FName column in the Student table? A. B. C. D. UPDATE Student SET FName=Mridul WHERE FName=Madhur MODIFY Student SET FName=Madhur INTO FName=Mridul UPDATE Student SET FName=Madhur INTO FName=Mridul UPDATE Student SET FName=Madhur WHERE FName=Mridul 17. How can you delete the rows with marks below 33 in the Student Table? A. B. C. D. DELETE FROM Student WHERE marks
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.