0% found this document useful (0 votes)
71 views18 pages

Document 5

Uploaded by

samiran das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
71 views18 pages

Document 5

Uploaded by

samiran das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
structured Query Language (SQL) Giicaeaucs Inthe last chapter, we discussed the basic concepts of database and DBMS. We shall now learn to practically implement a relational database and execute our queries on it. We have used MySQL software. You can download it freely from the Internet. Topics that we will be covering here include, = + Basic introduction about MySQL \ ‘* Working with WHERE, WHERE IN, WHERE LIKE, ‘+ Understanding the Structured Query Language WHERE BETWEEN, ORDER BY, DISTINCT, + Data types, Arithmetic and Logical Operators in GROUP BY, HAVING clauses SQL * 1ax, avg, count + Using the Select statement : integrity issues + Applying functions on strings + Handling NULL values + Creating and deleting database ‘+ Adding primary key and foreign key constraints * Creating, deleting, altering and updating tables + SQL Joins Inserting values in a table 10.1_ INTRODUCTION TO MYSQL ee In this chapter, we have used the MySQL database because it Before starting with SQL, we must first have a database. In this chapte : isa fase easy-to-use RDBMS that is widely used. MySQL is popular forthe fllowing reasons . sean open-source sofware so users do nothave to pay touseit. Fo $ ee powerful program ‘that can handle a large subset of the functionality MySQL is developed, mar- of the most expensive and powerful database packages. ied sd eer + MySQL uses SQL data language. Sve + Tecan be used on a number of operating systems. ae MySQL can be integrated with many languages including PHE, PERL. C, . Tesh wel wi even large data sets having up to 50 million rows or more The US tech company table. The default file size limie for a table is 4 GB. In fact, a database of | Sun_ Microsystems bought in etyes (TB) i not uncommon these days MySQL AB in 2008, Later, z Tecer eke ‘customized as per user requirements, in 2010 Oracle acquired © Tesatisfies ACID property. - Re ieee ae ete pe power echniqusto cme hat aly autbord wera} MySQI- has ben prac access the database- ‘owned by Oracle since chen. Beas Sd 1 See-Qurell, is a database query language. Many people think of it as a ivisa language that os tusers to access and manipulate data stored in a relational database. SQL queries ats ens) can be used to perform operations lke retrieving, inserting, updating and deleting data, They can also cs eft co ereate tables or modify the structure of existing tables. However, to use SQL queries, ou eae install beat ac ke Oracle, MySQL, MongoDB, Poses SQL, SQU. Server, DB2, et SQL, prone! database Dut 1318 Computer Scence with Python for CBSE Class Xt 10.2.1 How MySQL Works MySQL works on client-server model. Computers that 1. Request install and run RDBMS software are called clients. =——S Whenever they need to access data, they connect to the ss 2. Response RDBMS server. That is the pelea es SS i sic client-set ree ae ae) anaes to a server to access Client/server request/response moe data stored in the database server. Every client can make a request from the graphical user interface (GUI) on their screens, basic working of such a client-server model can be understood as, and the server responds with the desired output Th | MySQL is written in C and 1. MySQL creates a database for storing and manipulating data. { Crs. 2. Clients request data using specific SQL statements that are executed on the MySQL. : + 1 3. The server application responds with the requested information that is then displayed on the client machine. 10.3 USES OF SQL SQL allow users to create queries where a query isa request for data stored in one or more tables in the database. These queries are simple English-like statements. With the help of queries, users can access, modify, insert and delete data from table(s) stored in the database. SQL can also be used to create metadata for describing the data. With SQL, users can create and drop (delete) tables. Users can also create procedures and functions and set permission on them to restrict their usage. Types of SQL Queries The two types of SQL queries that we will be reading about in this chapter are DDL and DML. While DDL ot the Data Definition Language is used to create or modify database objects (like tables, views, indexes, users, etc), the DML or the Data Manipulation Language, on the other hand, is used to manipulate data (like inserting, updating, deleting data). 10.4 SQL DATA TYPES Before we actually start creating tables and inserting records into it using DDL and DML, we must first know the permitted datatypes in SQL. Each column in a table must have a valid name and a data type. While creating a table, the SQL developer must specify what type of data will be stored in each column, In this chapter, we have used MySQL version 8.0, Some important data types used in MySQL are given in Table 10.1. Data ypes in SOL Perr Een CHAR(SIZE) A fixed-length string that may have alphabets, digits, and special characters. ‘The size parameter specifies maximum number of characters. Its value may vary from 00 255. By default, its size is 1. VARCHAR(SIZE) A variable-length string that may have alphabets, digits, and special characters. The size parameter specifies maximum number of characters. Its value may vary from 0 to 65535. (Table 10.2 shows the difference between CHAR and VARCHAR). Take 101 (Continued) SECEMIN Continued Data Type Deny The size parameter whi ich displaying the value. FLOAT(P) BOOL Zero is ic ies, Fra neted Fs nomero ass atone it can be used to specify a si nsidered as true, if Pecify a signed of unsigned 2147483648 to 2147483647 and sone ge. signed incepesisin the ig take any value from 0-255, Struc tured Query Language Sal 319 igned integer is in the range 0 to 4294967295, specifies the maximum wideh for Difference between CHAR and VARCHAR enn Te stands for Character. Values are stored in fixed lengths and are padded with space characters to match the specified length. Tecan hold a maximum of 255 characters. Ie uses static memory allocation. Takes 1 byte per character for storage. Used when the length of the variable is known. | Iconly accepts characters. [Perms er than Varhnr__tdoweshan ep 10.4.1 Date and Time Types ‘The MySQL date and time datatypes are a follows: Date: A date is 30th, 2021 woul: binatic ‘A date and time com 9. For example, 1d be stored as 2021-09-30. Datetime: and 9999-12-31 23:59:5 09-30 14:20:00. Timestamp: A‘ ic Ist, camp between midnight, January Ist, csnly without the hyphens between numbers; VARCHAR Data Type It stands for a Variable Character. Values are stored in variable length and are not padded with any characters Ie can hold a maximum of 65,535 characters. Teuses dynamic memory allocation. ‘Takes 1 byte per character plus an additional 1 or 2 extra bytes for storing length information. Used only when the length of the variable is not known, Ic accepts both characters and numbers. cis slower than Char. ved in YYYY-MM-DD format, beeween 1000-01-01 and 9999-12-31, For example, Seprembsr stored ii ion in YYYY-MM-DD HH:MMSS formar, between 1000-01-01 00:00:00 2:20 in the afternoon on September 30th, 2021 would be stored as 2021- 1970 and sometime in 2037, This looks like the previous 2:20 in the afternoon on September 30th, 2021 DATETIME format 1 50142000 (YYYYMMDDHHMMSS ). would be stored a5 20) Time: Stores the time in My: Scores & HH:MMSSS format. Year(l “ Fon 2069 (70 0 69). If the length isa 4-digit number, 9 mn 1970 00° Hogth of ear year in a 2-digit ora 4-digit format. If the length is a2 igit number then it can specify any year then YEAR can be from 1901 co 2155. The default 1u./_SWL NUMERIC FUNCTIONS: SERENE aaiacaia mel Numeric Functions are used to perform operati fanctions used in SQL are discussed below. ABS () returns the absolute value of a number. mysql> SELECT ABS(-98.7); os | aBS(-98.7) | pect 1 row in set (0.01 sec) CEIL() returns the smallest integer value that is greater than or equal to a number. mysql> SELECT CEIL(21.345); | CETL (21.345) | a 1 row in set (0.00 sec) DIV () is used for integer division. mysql> SELECT 100 DIV 20; is 1 100 prv 20 | 1 row in set (0.00 sec) jons on numbers and return numbers. Some com: monly used numeric cos (), SIN(), TAN(),COT() functions return the cosine, sine, tangent and cotangent of the given number respectively. mysql> SELECT TAN (45); ‘2 | TAN (45) i | 1.6197751905438615 | re) 1 row in set (0.00 sec) DEGREES () converts a radian value into degrees. mysql> SELECT DEGREES (1.02); “+ | DEGREES (1.02) ' + | 58.44169510334397 + 1 row in set (0.00 sec) —+ EXP () returns ¢ raised to the power of the given number, mysql> SELECT EXP (2); + --+ | EXP (2) 1 + | 7,38905609893065 | + 1 row in set (0.00 sec) FLOOR () returns the largest integer value that is less than or equal to a number, mysql> SELECT FLOOR (21.345) 1 Fuoon2i-348) | ' ieee in set (0.00 sec) @qSNTEST () returns the greatest value in the given ist, ysql> SELECT GREATEST (-10,210,20, 720, 30, -30, 100, ~100) ; + | GREATEST (-10, 210, 20, ~20, 30,-30, 100, -100) 4- 1 row in set (0.00 sec) LEAST () returns the smallest value in the given lst. mysql> SELECT LEAST(-10,210,20,-20, 30, -30, 100, -100); - + | LEAST (-10, 210, 20,-20, 30,-30,100,-100) | 1 row in set (0.00 sec) IN(), LOG10(), LOG2() returns the natural MOD () returns the remainder of » divided by m. logarithm, base-10 logarithm and base-2 logarithm of a number respectively. mysql> SELECT 103 MOD 5; | 103 Moo 5 | \ tL ; 1 row in set (0.00 sec) mysql> SELECT LOG10(100); | LoG10(100) 1 row in set (0.01 sec) PI () returns the value of Pi displayed to 6 decimal BOW () returns m raised to the mth power places. mysql> SELECT POW (10,3); mysql> SELECT PI); Trowao,3) 1 n 1 1 yo00 1 1 row in set (0.00 sec) | 3.141593 | 1 row in set (0-00 sec) value in degrees to radians. RAND () returns a random number. RADIANS () converts eunce RADIANS (360)? yogi? SELECT RAND(); 1 RANDO) \ nyse? 5 | 0.8558367722256451 | 1 row in set (0.00 sec) mysql> SELECT ROUND (3.14156, 2) + | ROUND(3.14156,2) | rae 1 row in set (0.00 sec) 1 row in set (0-00 sec) TRUNCATE () truncates the given number after the specified number of places right of the decimal point. mysql> SELECT TRUNCATE (3.141567, 3) + be | TRUNCATE (3.141567, 3) | 1 row in set (0.00 sec) 10.8 STRING FUNCTIONS —— “The string functions in MySQL are used to manipulate textual data stored in tables. These functions can also be use along with update commands to change data values stored in tables. Some most frequently used string functions a discussed below. [ASCII () function is used to find the ASCII value of a character. mysql> SELECT ASCII('R')? | ASCII('R') we 1 —_ 1 row in set (0.02 sec) eo 1 + ' + CONCAT () function is used to add two words or strings. mysql> SELECT CONCAT('GOOD' MORNING") re | CoNcAT(*GooD', ", "MORNING" ) 1 row in set (0.05 sec) CHAR_LENGTH () function is used to find the length of a string. mysql> SELECT CHAR_LENGTH ("GOOD MORNING") 7 + 42 1 row in set (0.02 sec) FIND_IN_SET() function is used to find a symbol from a set of symbols. mysql> SELECT FIND_IN_ 'M,O,R,N,I,N/G") i SET('I* | PIND_IN_SET('I', *M,0,R,N,I,N,G") | 1 row in set (0.00 sec) gxsTR() function is used to find the aysql> SELECT INSTR('Goop MORNING’, 'R') ; occurrence of an 1 row in set (0.02 sec) UCASE () function is used to convert the given stin into upper case. You can even use the UPPER () . function to do the same work. mysql> SELECT UPPER('good morning"); + | UPPER ("good morning") | + | GOOD MORNING t + 1 row in set (0.02 sec) LPAD () function makes a string of specified size by adding the given symbol. mysql> SELECT LPAD('GOOD MORNING", 20/'* 1 row in set (0-02 sec) i substring of given length ion dol ton he SUBST® 1¢ speci the same task. 1g00D MORNING MID () fan starting from ! good morning 7 1g 1 row in set (0.05 sec ‘LEFT () function is used to SELECT a sub-stri from the left of given size or aneae in mysql> SELECT LEFT("GOoD MORNING*, 7) 7 | LEFT ("GOOD MORNING',7) | + | Goop Mo i 1 row in set (0.01 sec) LITRIM () function removes leading white spaces from the given string. oop mysql> SELECT LTRTM(* MORNING") - | ure’ GOOD MORNING") | GOOD MORNING 1 row in set (0.00 sec) REPEAT () function re-writes the given string, the specified number of times. mysql> SELECT REPEAT (‘BYE',2)7 + + | REPEAT (*BYE',2) | | BYEBYE 1 1 row in set (0-01 sec) Sr mysql> show databases; as | Database \ ss | information_schema | mydb I mysql I performance_schema | sys \ i rows in set (0.00 sec) 10.11 CREATING TABLES — To create a table, we must specify the name of the table. We must also define its columns and each column's data typ In SQL, the CREATE TABLE statement is used to create a table. The basic syntax of this statement can be given as CREATE TABLE table_name( columni datatype, column2 datatype, column3 datatype, columnN datatype, PRIMARY KEY (one or more columns ) In the above syntax, (CREATE TABLE is the keyword that specifies that you want to create a table in the database. table_name is a unique name or identifier for the table. A round bracket is opened following the table_name. ‘Within the opening and closing brackets, the list of columns and their corresponding data types are specified. PRPPTPETED Let us create 2 Student table with columns- Roll_Number, Name, Phone_Number, Marks and Class. Remember that NOT NULL is a constraint that means value for a particular field cannot be NULL. In the Student's table, we will explicitly specify that the Roll_Numbes, ‘Name and Phone Number cannot be NULL. We will also set Roll_Number as the primary key of the table. mysql> CREATE TABLE STUDENT ( => R0LL_NUMBER INT NOT NULL, => NAME VARCHAR (20) NOT NULL, => PHONE_NUMBER CHAR (10) NOT NULL, -> AGE INT, -> MARKS INT, -> CLASS CHAR (10), => PRIMARY KEY (ROLL_NUMBER) OF ¢ sry OK, 0 rows affected, 1 warning (1.32 sec) the table is created, we can use the DESC command to see the description of the newly created table. Default | Extra decree a tart | 1 i \ 1 | NAME | varchar (20) | NO | | NULL | PHONE NUMBER | char (10) | NO | ens fet | AGE | ant (11) \ YES | | NOLL | | MARKS | int (11) | Yes | }woLL | | CLASS | char(10) | YES | | NULL | 6 rows in set (0.04 sec) ‘The above results verify that the student table is created in our database with the specified fields and constraints. 10.12 DELETING TABLE SS [Arable can be deleted using the DROP TABLE statement. When a table | You should be very careful while us- is deleted, all its definition, data, indexes, views, triggers, constraints and | ing the DROP TABLE command as permission specifications are removed from the database. The syntax of | once it is executed, the table is com- DROP TABLE statement can be given as, | pletely deleted along with all che in- DROP TABLE table_name; formation in it. FEN = ee ce owe tte sree: mysql> drop table students Query OK, 0 rows affected (0.56 sec) [Note that 0 rows are affected as we have not inserted any row till now. To verify whether our table was deleted or not, let us again use the DESC statement and observe the result. mysql> desc students , ; : le aise (azs02): Table ‘mydb.student' doesn't exist Note that che error indicates thatthe student table in mydb database no longer exists. 10.13 INSERTING VALUES IN TABLE 203 “To insert values i a able, i¢ must frst be created using the CREATE TABLE command. In the . Ten STUDENT table but for executing other SQL. statements, we have vemand tn the last section, we had the table usi TABLE command: an be instead using the INSERT 1 le using CREATE, daa ble dat enn in the database ERT INTO statement. This statement is used to add new rows of 1 are oo basi syntaes of the INSERT INTO statement which are shown belo aNsERT INTO TABLE_NAME VALUES (valuel,value2,value3 valueN) 1s. svalueny ; "re sence wth Python fr CSE Cas a“ ‘ | Example 10.4 Fo eS eT mysql> INSERT = INTO STUDENT VALUES (1, 'RAHUL', "9876543210", 18, 89, 12-D') uery OK, 1 row affected (0.26 sec) Query, oNSERT INTO STUDENT VALUES(2, 'SARFARAZ", "9823416790", 17, 97, "L1-A"); Query OK, 1 row affected (0.07 sec) Bee? INSERT INTO STUDENT VALUES (3, ‘RIA', 7825516230", 16, 67,'10-C'); Query OK, 1 row affected (0.04 sec) RYSGL> INSERT INTO STUDENT VALUES (4, 'PALAK' , '9999123456", 9,75, '9-B'); Query OK, 1 row affected (0.18 sec) mysql> INSERT INTO STUDENT VALUES (5, 'KRISH', '9807126534", 14, 90, '8-D") ; Query OK, 1 row affected (0.12 sec) 10.14 _RETRIEVING DATA FROM TABLE ‘The SELECT statement in SQL is used to fetch or retrieve data from one ot more tables in the database, The resu of the SELECT statement is in the form of a table. This resultant table is known as the resule-set. The syntax of SELECT statement can be given as, SELECT columal, column2, columnN FROM table_name; Here, column], column2... are fields of the table from which data has to be fetched. To fetch all felds from table, the syntax is SELECT * FROM table_name; te Let us select the entire data from all fields in the student table. Also select only the Roll ‘Number and Marks fields from the student table. mysql> SELECT * FROM STUDENT; Fa | ROLL_NUMBER | NAME | PHONE_NUMBER | AGE | MARKS | CLASS ¢-----4-4 . i 1 | RAHUL | 9876543210 | 181 89 | 12-p 1 2 | SARFARAZ | 9823416790 | 17) 97 | aa-a i 3.1 RIA | 7825516230 1 161} 67 | 1o-c 1 4.1 PALAK | 9999123456 | 9) 75 | o-p 1 S | KRISH | 9807126534 | 14) 90 | @-p 5 rows in set (0.00 sec) mysql> SELECT ROLL_NUMBER, MARKS FROM STUDENT; ROLL_NUMBER | MARKS | 11 ' 21 1 31 671 at ! 51 1 + 1 1 1 1 1 a 5 rows in set (0.00 sec} ‘Structur 0.15 _THE WHERE CLAUSE ied Query Language (SQl) 331 ‘the WHERE clause is used in the SELECT sta Jes. We use the WHERE clause to fi ement {0 speci ai addition to the SELECT ence cer oa table and fetch only those that meet th : , ; re iadnige gatements. The basic syntax of the SELECT statement with ewe used with the UPDATE ace sevecT column, column2, columnN eee FROM table_name WHERE [condition] pacer) si condition for retrieving data from one ot more “We can even use comparison and logical o i the SELECT statement with WHERE if Cae WHERE clause, Let us see a couple of queries to see how Display the name and class of the students who scored less than 90 marks, mysql> SELECT NAME, CLASS FROM STUDENT WHERE MARKS < 90; r + ; | NAME | CLASS | | RAHUL | 12-D | tRIA | 10-¢ 1 | PALAK | 9-B | + + 3 rows in set (0.00 sec) pene” cor aan aRKs, CLASS FROM STUDENT WHERE NAME ~ ‘SAREARAZ'? mysql> SELECT PHONE_NUMBE i iti () but numeric values should vad ings sould be specie win single ques (1) bu umes rere ree ae chareepown in the Example 10) sjren without any 0% 1D OR, OPERATORS 40.16 SQL AND AN -¢ used for combining multiple condit ‘operators 1p and OR operate Te called as the conjunctive operators Touma table. TH Pes, the AND operston « Tonetthe existence of multiple conditions in an SQL statements te nae yas of wing the AND operator can be given as as co specify a criterion for ase on sroM rebbegseiont) AND [condition2}...AND [conditionN] 7 FEE egy number of conditions inthe WHERE Sass oe the AND operator. For an action to be wee sr een al condton pared bythe AND oper mst bbe TRUE. ken 332 Computer cence with Python for CSECIAS XI Let us write a query to display the name and class of all the students having marks more than 90 and age >=15. Note that we have inserted an additional row in the table. mysql> SELECT NAME, CLASS FROM STUDENT WHERE MARKS < 90 AND AGE>=15; | NAME | CLASS | | RAHUL | 12-p | | RIA | 10-c | 2 rows in set (0.00 sec) ‘The basic syntax of the OR operator with a WHERE clause can be given as, SELECT columnl, column2, columnN FROM table_name WHERE [condition1] OR [condition2]...0R [conditionN] As per the syntax, » number of conditions can be tested using the OR operator. To execute the query, any one of the conditions separated by the OR operator must be TRUE. Display the name and class of students scoring more than 90 marks or having age = 18. mysql> SELECT NAME, CLASS FROM STUDENT WHERE MARKS < 90 OR AGE = 18; ato nana I cLass | 1 RAHUL | 12-D | [RIA | 10-c | | PALAK | 9-B | 3 rows in set (0.00 sec) ee mysql> SELECT NAME, CLASS FROM STUDENT -> WHERE MARKS >=75 AND MARKS <=90; + + | NAME | CLASS | + + | RAHUL | 12-D | | PALAK | 9-B | KRISH | 8-D | Socecnact a+ 3 rows in set (0.00 sec) 10.17 THE WHERE BETWEEN CLAUSE ———— ‘The WHERE BETWEEN clause returns values that fall within a given range. This clause is a shorthand for >= AND <=. Note that WHERE BETWEEN operator is inclusive of starting and ending values. The syntax of this clause can be given as, ce Structured cr column-names Query Langu: on table-name age(Sal) 333 fgg, colunn-name BETWEEN vai, ‘uel AND value2 Display the Name, Class and inclusive) using the’ Marks of students who i the WHERE BETWEEN clause, "4 b*¥°#875.and90 (bound qysql> SELECT NAME, CLASS, MARKS FR WHERE NARKS’ BETWEEN 75 ano oon SUES? SS ml ; | CLASS | MARKS | eRe ee 3 rows in set (0.01 sec) 40.18 THE SQL WHERE IN CLAUSE ———— “The WHERE IN clause returns values that match values in alist ora sub-query. This claus is a shorthand for multiple OR conditions. The general syntax of WHERE IN clause can be given as, SELECT column-names FROM table-name WHERE column-name IN (values) FN Oo a ree mnnee mysql> SELECT * FROM STUDENT “> WHERE MARKS IN (897 90)7 | MARKS | CLASS 1 a9 | 12-D | 16) 67 | 10-¢ I i) 901 8D I a x 3 rows in $¢ sal. SELECT DISTINCT STATEMENT jE sone ent is used co return only distinct (ferent) values In oer words di ce eect DE BIN repaying daa from the rable, The aynas DISTINCT clause, when used wid ‘The 5! hi centric oan be given a5, duy eliminatt ments the SELECT" og column, column2, +++ -coLumnN “The SQL DISTINCT key- pisT word is used in conjunction c ni SELECT apie st tion with che SELECT statement ROM onaition! anere (O Fes the namels) ofthe table) fom which data has to Be to eliminate all duplicate re- .e speci oe ‘more than one table name also. F SELECT * FROM ISSUE? + + | Rol1NO | Name | Book_Issued | Class | | 121 | MAHEK | LAB MANUAL | XI-A’ | | 283 | NIYON | PHYSICS | ix-c 1 | 390 | GIRIZ | SCIENCE xB | 404 | CHINUK | PaYsics 1 xII-B | | $07 | £ATZAL | BIOLOGY [xp I | 611 | NASIMA | MATHS | vI-a 1 | 729 | KIARA | SCIENCE | vrr-c | + ca 7 rows in set (0.00 sec) Let us select value for Book_Issued from the table without using the DISTINCT clause first. mysql> SELECT Book_Issued FROM ISSUE; Book Issued | 1 | LAB MANUAL | | PHYSICS i | SCIENCE I | Paysrcs I | BIOLOGY 1 | MATHS ' | SCIENCE I 7 rows in set (0.00 sec) Now let us use the same query but with DISTICT clause to appreciate the results, mysql> SELECT DISTINCT Book_Issued FROM ISSUE; Book_Issued | LAB MANUAL | PHYSICS 1 SCIENCE ' BIOLOGY I fl MATHS rows in set (0.00 sec) Did you notice that the first select statement selected all values includi i ‘The SELECT statement with DISTINCT clause, however, prone 's duplicates from the Book_Isued column? distinct subjects books were issued, we can write plicate values. To know how many tow in set (0.00 sec) 10.20__ORDER BY CLAUSE See ‘The ORDER BY statement in S sort the value in the resule-set by By default, ORDER BY sorts we can use the keyword ” ing order, the keyword ASC is used, Tre syntax ofall eas of using ORDER BY clause with the SELECT statement can be given as, Secording to one column: Ta sort in ascent descendi © sein Tegan Bor descending order we can use the keywords ASC or DESC SELECT expressions FROM tables (WHERE conditions] ORDER BY expression [ asc | pEsc 1 where, DESC is optional. If present, it sorts the result-st in descending order by expresion. according to multiple columns: To sort according to mult iple columns, separate the names of columns by (,) operator. The syntax can be given as, SELECT * FROM table_name ORDER BY columni ASC|DESC + column2 aASC|DESc Enna To sort records of Employee table in ascending order of thes slarcs, we cam wolw "YSq1> SELECT EMPNO, SAL FROM EMPLOYEE ORDER BY SAL; VEmpwo | saL | a + 1486 1 Nou | | 367) Nunn 1 678) wun 4 ' 423 1 35000 1 ' 234 1 50000 | | 345 | 75000 1 ees 6 ows in set (0.05 sec) and further on descending order of salary, if some a dingly srt records based on ascending order of name and. rrespondingly, ro sor records bated on ascendin employees have the same name, then we can wri LECT * RI E ASC, SAL DESC; 1. AME ASC, SA\ ELECT * FROM EMPLOYEE ORDER BY Ni mysql> s) 10.21 _UPDATING THE TABLE —— ‘The SQL UPDATE statement is used to modify the existing data in a table. We can even i ee WHERE due with the UPDATE query to update only selected rows, so that not all the rows are affected. The basic syntax of the UPDATE query with a WHERE clause can be given as, UPDATE table_name SET columnl = valuel, column2 = value2.... WHERE [condition] ; Again, according to the syntax, any number of conditions can be specified using the AND or the OR operators in the WHERE clause. EAERE MED Update the STUDENT table to set age of the student in class 9-B to 15. Also show the records of the table to check whether the record was updated or not. , columnN = valueN ‘o-B'; mysql> UPDATE STUDENT SET AGE = 15 WHERE CLASS = Query OK, 1 row affected (0.08 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SELECT * FROM STUDENT; se a a NUMBER | NAME | PHONE_NUMBER | AGE | MARKS | CLASS | -+ I 1 | RAHUL = | 9876543210 | 18 | 89 | 12-D | I 2 | SARFARAZ | 9823416790 | 171 97] 11-A | ' 3 | RIA | 7825516230 | 161 671 10-c | 1 4 | PALAK = | 9999123456 | 415] 75 1 9-B J i 5 | KRISH | 9807126534 | 141] 901 8D | + + 5 rows in set (0.00 sec) Ez Let us update the class of all the students to 6-A. Note that in this case, we do not need the WHERE clause. We will simply write, mysql> UPDATE STUDENT SET CLASS = '6-A'; 10.22 DELETING ROWS FROM A TABLE a — ee} ‘The DELETE query in SQL is used to delete existing record(s) from a table in the database. To delete only selected rows from the table, we can even use WHERE clause with DELETE query, otherwise all the records would be deleted. “The basic syntax of the DELETE query, when used with WHERE clause, can be given as, DELETE FROM table name WHERE [condition]; In the condition, any number of conditions can be specified using AND or OR operators. Let us delete the record of the student having roll number 6. mysql> DELETE FROM STUDENT WHERE ROLL NUMBER = 6; sq. a 7 Let us delete all the records from the STUDENT table. mysql> DELETE FROM STUDENT, - ' name of the co: ployees in each 6. Write a Pyth many that pays highest salary, "PANY: 1on code to create th given below. the following tables, enter atleast 5 record : 0 Ssoplis No, Sane, Sus, ip ® in each table and answer the queries Pitts (PNo, Pname, Colour, Weight City) Project (JNo, Jname, Jcity) tie Shipment (Sno, Pao, Jno, Qunatity) . anal brimary and foreign keys ret SU i i ‘ pee namber for suppliers in Paris with statuss20, suppliers who supply part P2. Di numbers, PPIY Part P2. Display the supplier list in increasing order of suppl 4) Get suppliers names for suppli plier © For each shipment get fil shipment donee pan f) Get all the shipments where ity isin dn 8 fal shipment weights, the quantity isin the range 3 8) Get part nos. for parts that eith ange 300 to 750 inclusive. ; ve red parts, 7 eae ai deal of pats sup by a supplier in Del Doe art numbers for part supplied by a supplier in Allahabad toa projec in Chennat 1) Get the total number of project supplied by a supplier (ay $1) ') Get the total quantity ofa part (say, P1) supplied by a supplier (say, $1) Laursen 1: is a database query language. 2. Language is used to create or modify database objects (like tables, views, indexes, users, etc). 3. Data type is used to define fixed length strings. 4. statement is used to see alist of ll the databases present in MySQL. to create a table 5. In SQL, the statement is used to create a tl : G. Once the table is created, we can use the command to see the description of the newly created ae starement is used to add new rows of data in a table that exists inthe database. = statement in SQL is used to fetch or retrieve data from one or more tables in the database. Bn ent eliminates duplicate entries while displaying dat fom the abe, 9. method returns curr abject which then used to eceute SQL ques. 5 ako am 1 database is 11. The default username ee _______ method is used. 3. To insert multiple rows bute and returns the number of rows that were affected by an execute () 1 is a read-only attribut 8 paid function is used to finalize changes in the aes used with _____ functions. 14 ‘UP BY statement is often The GRO! 15+ fa ou vdeary sofovate 6. DIL is used to manipulate data, Myst js a prop’ ved only on Windows 7. Char performs faster than varchar. si be used 0 8. ‘The ALL keyword is used to compare any applical : MySQL fies ACID Proper value in the lise Penn sealiatt, - satis language ; a ea ee re iiibe migusned 92 The WHERE cawe cantbe’ wed to reisndaia 3 ysQh is jon responk only from a single tab 3. My - applica played on the client machine. ly le table. the server chat 5 Mformatl inl 376 Computer cence with yan for CE Cs 10. The ORDER BY clause can be used to sort data 14. User working as root does not need a password, according to multiple columns. 15. fetchone() method fetches all the rows in 11. The primary key must contain NULL values result set. 12. A table can have only one primary key and the 16. commit () method is used to revert the changes primary key may consist of one or more fields. made to the database. 13. We can execute a query even after the cursor object is closed. SER 1. Which data type uses dynamic memory allocation? a. char b. varchar c. int 4, float 2. We cannot. data using SQL statements. a. delete b. update c. retrieve d. None of these. 3. Which of the following is not an example of a database? a. MySQL. b. SQL c. PostGres SQL d. SQL Server 4 Which clause is used with SELECT statement to filter the records in the table and fetch only those that meet the specified criteria? 2. ORDERBY —_b, WHERE DISTINCT — d. UPDATE 5. Which SQL statement is used to modify the existing data in a table? a ORDERBY —_b, WHERE c INSERT INTO d. UPDATE 6. Which method is used to establish a connection between MySQL database and Python program? a connect () b. cursor () c. close() d. interface () 7. Which method is used to close the MySQL database connection? a connect .close() b. connection.close() «©. cursor.close() d. db.close() 8. is the server name or IP address on which MySQL runs. 2. User name b. Connection name ¢, Host name d. Database name 9. Which method fetches the next row of a query result set? a fetch() b. fetchone() c fetchnext() d. fetchall() Fill in the Blanks 1. SQL 5. DESC 11. ro0r. 2. Data Definition ”. INSERT INTO 12, executemany () 3. char 8. SELECT 13, rowcount 4. show databases; 9. SELECT DISTINCT 14, commit () 5. CREATE TABLE 10, connection.cursor() 15, aggregate State True or False 1. False 5. True 9. False 13. False 2. False 6. False 10. True 14, True 3. False 7. True 11, False 15, False 4, False 8. False 12. True 16, False Multiple Choice Questions 1b 3. b 5. d 7b wb 2d 4b 6 a Bc

You might also like