0% found this document useful (0 votes)
29 views

Cs

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
29 views

Cs

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 20
In This Chapter 13.1 Introduction 135. Making Simple Queries 13.2 Some MySQL SQL Elements 13.6 MySQL Functions, 133 SQL Command Syntax 13.7 Aggregate Functions 134 Sample Database “SQL, Structured Query Language, was developed in 1970s in an IBM Laboratory. SQL, Maatimes also referred to as SEQUEL is a 4th generation non-procedural language. The procedural languages just need to be specified “WHAT” of the problem and not a detailed cabout HOW itis o be done’, Since SQL. is non-procedural and that is what makes it nple, it makes an RDBMS possible. ening oceinenaatyngs caee’s structure (i Changing security settings for system (HD FEnmiNNE say being _non-rocedual users for working on databases or tables (i?) Querying database Gescribes WHAT all data is to be i ing the database contents. retrieved or inserted ot modified (2) Inser s , deleted, rather than specifying : ee is Je queries. But before 9" This chapter is dedicated to making simp code describing HOW to perform that let i talk about some important elements of SQt- ae Gave ost “ONG IR 4 om 13.2 Some MySQL SQL Elements has certain elements that play an importan, S plementation of SQL ; E The MySQL eee database. In this section, we shall talk about some basic g le defining/querying a databas oO erenes aa ‘ MySQL SQL that you must be aware of. These basic lemen (@ Literals (ji) Datatypes (ii) Nulls_ (iv) Comments 13.2.1 Literals Literals, in general, refer to a fixed data value. This fixed data value may be of charactertyy, numeric literal. For example, ‘Synthia’, ‘Ekagra’, ‘Raunak Raj Singh, “8° and “305° are all chey, text literals. Notice that all character literals are enclosed in single quotation marks or out, quotation marks. Characters that are not enclosed in quotation marks refer to the schema object names e.g., value refers to a . schema object whereas ‘valitc’ refers to a character literal. ares eae To store an apostrophe in a text literal, you should use \’ mum of 53 digits of precsng, (backslash followed by apostrophe e.g., to store Kush’s in a text literal, you should write it as ‘Kush\’s’). Numbers that are not enclosed in quotation marks are numeric . literals e.g., 22, 18, 1997, 2003 are all numeric literals. ‘i A text literal can have ma Numeric literals can either be integer literals i.e., without any mum length of 4000 bjs « decimal or be real literals ie., with a decimal point e.g. 17 is an MySQL5.1. integer literal but 17.0 and 17.5 are real literals 13.2.2 Data Types Data types are means to identify the type of data and associated operations for handling? A value’s datatype associates a fixed set of properties with the value. These properties cause differat treatment of datatypes. For example, you can add values of NUMBER datatypes, but you cannot” add values of CHAR or VARCHAR types. Internal datatypes supported by MySQL includett= ‘ones given here. MySQL uses many different data types, divided into three categories : © Numeric Date and time,and _ String types Numeric Dota Types Fed io TAL 1 ) MySQL uses all the standard ANSI SQL. common numeric data types and their d signed, the allowable range ' oe | range is from 0 to 4294967295. be signe or unsigned. If signed, the allowable range i from 8 the allowable range is from 0 to 255. You can specify a width of up to 4 dig that can be signed or unsigned. I signed, the allowable range is from e is from 0 to 65535. You can specify a width of ane SIMPLE QUERIES IN qu GBR A rinse nee at an 33 to 8388607, If inal red te oF is cane Ge 109 dig BU allowae St I Maned, the alow abe range i rom gh neem ae ls from 6 t0 16777215, You can specify i -9223372036854775808, 1844674407370955161: an be 9 ged oF wns to snaasransessarmsgnt HE signed, the att Erk yaa he allowable ang i trom at te lee rng em can define the display length (M) and th will default to 10.2, where? isthe number (including decimals), Decimal precision can yAT(M.D) flo’ number of decimals (1p), be unsigned. You of decimals and 10 is the total anol eared is the P go to 24 places for a LOA umber of digits EMD) A double precisi DOUEMET ength (MD) and the mu Munber ha cenno be tpt (0) ae he muro dec oy le You defi te dopa REAL isa synonym for DOUBEAE, Dest Precson can go 5 plas for DOUBLE CECMALW.D) | An unpacked floating point number that cannot be unsigned, in unpacks signed. In unpacked decimals, each decimal corresponds to one byte. Definin, Defining the display leng required. NUMERIC is a synonsen foc seed OM) and the numberof decimals (D) Date ond Time Types ‘The MySQL date and time datatypes are : A date in YYYY-MM-DD format, between 1000-01-01 ar ‘Acdate DOE MED ore omen -O1 and 9999-12-31. For example, December A date and time combination in YYYY-MM-DD HH:MM:SS iat, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the aftemoon on December 30, 1973 would be stored as 1973-12-30 15:30:00. TESTA A timestamp between midnight, January 1, 1970 and sometime in 2038. This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 (YYYYMMDDHHMMSS). DATE DATETIME TIME Stores the time in HH:MME:SS format. YEAR) Stores @ year in 2-digit or #digit format. Ifthe length is specified = (for example YEAR(2)), YEAR : canbe 1970 to 0870 to 69) Ifthe length is spefid as 4, YEAR can be 1901 692195 ‘The default length is 4. String/Text i o/ Text ee at, This list describes the common string Most data that you use in 2 __ datatypes in MySQL. : ? mid 255 characters in length. (fOr ‘example CHAR@)), 1a ‘fored, Defining a length is not ao the spectied length wen database is in string form: ant 255 craters in ena F example VARCHAR(5)- vrpen ereating & V {CHAR field ‘oman fl TS BLOBS are “Binary Lane oe a ata, such as images OF riven the two is ints of data; the diler nd are not case tive on se with BLOB or TEXT. ~ a COMPUTER SCIENCE WITH PYTHON ig, 536 ; rINYBLOB ‘A BLOB or TEXT column with @ maximum length of 255 characters. You do not specify i eT length with TINYBLOB or ‘TINYTEXT. sesh ' saximum length of 16777215 characters. You do not specify | (BLOB or A BLOB or TEXT column with a1 Meo MREXT a length with MEDIUMBLOB or ‘MEDIUMTEXT. ; ae 967295 characters. You do no, LONGBLOB or A BLOB num length of 4294: ‘or TEXT column with « maximum LONGTEXT specify a length with LONGBLOB or LONGTEXT. ENUM ‘An enumeration is a fancy term for list. When defining an ENUYE You Eo a stot items from which the value must pases Ge ieenibe NID resample fou wa 1 field to contain “A” or “BY or “C", you your ENUM as ENUM, (aac) and only those values (or NULL) could ever populate, that Feld. Difference between Char and Varchar Datatypes In order to understand the difference between CHAR clear about fixed length and variable length fields. 'A field is a data element which can store one type of information which is composed of characters, Number of characters thataa field can store, is called field length or field width, As each character requires one byte for its storage, number of characters inside a field determine its field width in bytes (as those many bytes the field requires for its storage). and VARCHAR datatypes, one must be There can be fixed length fields as well as variable length fields. de Fixed length fields have fixed lengths ie., they occupy fixed number of bytes for every data element they store. These number of bytes are determined by maximum number of characters the field can store. Not necessarily, all data elements inside a field are of same length, but the field length is determined by determining the maximum possible characters in a data element. In fixed length fields, some space is always wasted as all data elements do not use all the space reserved but processing is much simpler in case of fixed length fields. Variable length fields have varied field lengths ie,, field length is determined separately for every data element inside the field. The number of characters in the data element become its field length. Let us consider a field “Student Name“ is having data elements “KINARI BAZAR” and “RANG MAHAL”. For the first data element “KINARI BAZAR” field length is 12 bytes (1 byte for space also, as it is also a character) and for “RANG MAHAL" it is 10 bytes. In variable length fields, there is no wastage of ing i i i ee 'g¢ of space, but processing is complex in case of variable hooter 13 + SIMPLE QUERIES IN sq 53.2.3 Null Values Ifa column in a row has no vak appesr "th btaminalta ae aa then column is said to be null, or to. contain a null. Nulls can PRIMARY KEY integrity constrained Yeni they are not restricted by NOT NULL or known or when a value would Te be me singe use a null value when the actual value is not 8 rpreentavalusofze because thy emote ——— : f zero, becau alent Any 8 @ null always evaluates to Any arithmetic expression con- 0.9 mull To fact, alLoperators | tinin # wll cays erfames When given anulloperand, _*! (except concatenation) return null 13.2.4 Comments ‘A comment is a text that is not executed ; it i zl itis only f i eer ect heme rp nt A cme A ae can appear between any keywords, parameters or punctuation marks in a statement. You can include a comment in a statement using either of these means : © Begin the comment with /*. Proceed with the text of the comment, This text can span multiple lines. End the comment with */. The opening and terminating characters need not be separated from the text by a space or a line break. > Begin the comment with —~ (followed by a space). Proceed with the text of the Comment. This text cannot extend to a new line. End the comment with a line break. © Begin the comment with #. Proceed with the text of the comment. This text cannot extend to a new line. End the comment with a line break. A SQL statement can contain multiple comments of both styles. The text of a comment can contain any printable characters in your database character set. For example, SELECT ename, sal, job, loc /* Select all employees whose compensation is greater than 300. */ FROM empl, dept WHERE emp].deptno = dept .deptno #joining two tables ANDsal>3@0; _-- this condition is testingwhether salary is more than 380 or not. 13.3 SQL Command Syntax The SQL provides a predefined before discussing them, we must commands. ial meaning in SQL. They are understood to be Keywonis, are eee mcrae ave been printed in capital letters. Commands, or erties ee ee given by you to a SQL database. Commands consist of one or more statements, are instructions 81°71 T°" Clauses begin with a keyword for which they are ts. Examples of clauses are “FROM sales’” ruments complete or modify the meaning of a clause, In aes argument, ea FROM is, the keyword. of FROM latinas is set of commands that help us work on relational databases. But be familiar with the conventions and terminology used in SQL : Set called clauses. logically a oi, eee, of keywords and argumen COMPUTER SCIENCE WITH PrTHoy, 3 Likewise ‘euue = 1500.07" is the argument of the WHERE clause. Objects are structures ease aRaie ies eves ool eked a? Piya nd nana Now that we are about to start SQL commands, following table 1) summa symbols used in syntax statements : ‘Table 13.1 Symbols Used in Syntax Statements This symbolic way of saying “or”. Thats, whatever precedes this symbol may option be replaced by whatever follows it Everything enclosed in tis treated as a unit for the purposes of evaluating, . or other symbn This means, everything enclosed in it is optional. : ‘This means whatever precedes it may be repeated any number of times. Whatever precedes this, may be repeated any number of times with the individual occurene, separated by commas. SQL and other special terms are in angle brackets. A stalement in MySQL SQL is completed with a semicolon() ie., at the end of the So statement, you have to give a semicolon(;). Also, you can write SQL statement in any case, whether lower-case or upper-case, as the commands in SQL are not case-sensitive. However the text literals or character 2, {itera that you specify in quotation marks are case-sensitive, cormangs nga case-sensitive, 13.4 Sample Database ae, In the coming sections, you'll be learning about how to use SQL commands on a My database. But before you start using commands, one more thing you need to do and that is #0 load a sample database. For this purpose, we downloaded menagerie example database from the MYSQL site (dev/mysql/com/doc/) and loaded it on our MySQL server ac er given instructions. (Create a folder namely SampleDB on hard disk of your machine. Say its path is DASampleDB. You can create this folder on any other drive too. If youintend to do so, simply use that pathin Place of the “D:\SampleDB” in the coming lines.) 1. To load this database, first you need SampleDB that you created earlier. to uncompress the menagerie.zip file in the folder following text in it : Drop database if exists menagerie ; CREATE DATABASE menagerie ; USE menagerie ; SOURCE D: /SamplepB/er ¢ CChopter 13 + SIMPLE QUERIES IN SQL hs To use Downlon,uncompres then ead to MysGLermne Example Databases ‘elye dita asl, chan at and estefan te) wort database (a versions, used mySQL cerications an raring) _slda database (requires MySQL 5.0 or later renagee bane (avesons) 3. Replace D:/SampleDB/ with the path of your folder you created earlier, if the path of that folder is different from D:/SampleDB. (Make sure to use front slash (/) in place of backslash (\) in paths and pathnames.) 4. Save the file. 5. Now start MySQL. In front of MySQL prompt, type : mysql> SOURCE D: /SAMPLEDB/MENA. SQL 6. It will create the example database “menagerie” for you. (See fig below) ae Crt serected, 1 wera 2.0 2) faeces. Pe Te rece, win 00 0) foe ered 8 ner 80 areal “tbysk Sting 7, Now type Show tables; in front of mysql> ! mysql> show tables; tb will display the lis of tables in your newly crea COMPUTER SCIENCE WITH PYTHON 9g 540 : 1 “The two tables of menagerie database are as shown below : Table 13.2 Event Table of Database Menagerie name date _type 5 remark a Flutiy 1995-05-15 litter 4 kittens, 3 female, 1 male Buffy 1993-06-23 litter pups eet c eens Buity 1994-06-19 | litter 3 puppies, 3 female Chirpy 1999-03-21 vet needed beak straightened Slim 1997-08-03 vet ‘broken rib Bowser | 1991-10-12 kennel NULL Fang. 1991-10-12 kennel NULL Fang 1998-08-28 birthday Gave him a new chew toy Claws 1998-03-17 birthday Gave him a new flea collar Whistler | _ 1998-12-09 birthday First birthday lable 13.3. Pet Table of Database Menagerie name ‘owner | species sex birth death Fluity Harold | cat f 1993-02-04 | NULL. Claws Gwen cat m 1994-03-17 | NULL | Buty Harold | dog f 1989-05-13 | NULL Fang, Benny dog, m 1990-08-27 | NULL Bowser | Diane dog, m 1979-08-31 | 1995-07-29 Chirpy | Gwen bird f 1998-09-11 | NULL Whistler | Gwen bird NULL | 1997-12-09 | NULL cep Benny snake m 1996-04-29 | NULL ~ Puffball_| Diane hamster £ 1999-030 | NULL A database once created, is ready for further processing. You must not create database OTE. every time you log on to MySQL. Just create it although databases for the very first a cies at ete ee sites your home machines only. In your school labs, your teachers keep every thing ready for you. Just give it a thought, how much extra work they do to make your learning ef and fruitful. Don’t a heartfelt thanks for that sink oe CChopter 13 + SIMPLE QUERIES IN SQL 13.5.1 Accessing Database Before you start making queries database for use. For this afte: oc pa in ne oe ‘you neeg to open the 'ySQL, you need to issue a command : Use ps For example, we want tow: abl : > ork on flowing command ate ogg sce eam nam mem oe sal wnethe mysql> USE menagerie ; Database changed mysql> Once the database menagerie is o ymand! c ed f z be lesmingihtaghorwhia tomer | film baa aoe Melee wi 13.5.2 The SELECT Command ate SELECT command of SQL lets you make queries on the database. A query is a command t is given to produce certain specified information from the database table(s). There are various ways and combinations, a SELECT statement can be used into. It can be used to retrieve a subset of rows or columns from one or more tables. In its simplest form, SELECT statement is used as given below : SELECT [, , FROM ; Selecting columns ns For example, if you want to view only the cd information of two columns riame and owner of hte. O on eae table pet, you may write your query as | claws | Gwen ‘ jButty MoMaroid mysql> SELECT name, owner | Fang | Benny | s ; | Bowser | Diane | *EROERS 1 Chirpy Gwen 1 Then MySQL will produce the adjacent result | Whistler | Gwen \ which is based on the Pet table of Menagerie a database, shown in Table 13.2 5 rows in set (0.00 sec) If you want to see the information of columns | owner 1 1 a name, owner, and species from the table pet, you Harold oe | will write Gwen ea | naroid dog ; SELECT name, owner, species Benny Bee i FROM pet ; Diane: \ Gwen COMPUTER SCIENCE WITH PYTHGN Ji 3.5.3 Selecting all Columns : lecting all If you want to see the entire table i.c., every column of a table, you need not give a complete of columns, The asterisk (*) can be substituted for a complete list of columns as follows : i be li SELECT * FROM pet 5 This will display all the rows present in the pet table. 13.5.4 Reordering Columns in Query Results ‘ While giving a querying, the result can be obtained in any order. For example, if you give SELECT species, name, sex, FROM pet ; the result will be having species as first eer Ts | species column, name as second column, and sex as third column, will be displayed as shown. | cae | Flutty | € { below. You can write the column names in. Locat 1 Claws: 4 m fot any order and the output will be having, ! ge 4 Busy lef aft i information in exactly the same order. age cose aaron | bird |chirpy | f i mysql> SELECT species, name, sex Tacs antec , Scie Pa ea ! | hamster | Puffball | £ \ ae i ) 3 rows in set (0.02 sec) The order of selection determines the order of display. 13.5.5 Eliminating Redundant Data (with keyword DISTINCT) By default, data is selected from all the rows of the table, even if the data appearing in the result gets duplicated. The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement, For example, if the Suppliers table stores the names and cities of the. suppliers and we want to see the cities where the Suppliers belong to. The table may consist of more than one supplier belonging to the same city but the result of the query Id contain duplicated city names. ; To do so, we shall write SELECT DISTINCT city FROM Suppliers ; In the output, there would be no duplicate rows, enever DISTINCT is used, only one NULL value is returned in the results, no matter how many NULL, alues are encountered. If we consider Suppliers table of chapter 12, e output in the right. Chopter 19 : SIMPLE, QUERIES IN SQL panete 13.1 Display distinct species of pets from able pe, Solution. mysql> SELECT OISTINCT( species) FROM pet ; 13.5.6 Selecting from all the Rows ~ ALL Keyword ees tin place of DISTINCT, you give ALL then the result ° <** 1" set (0.03 secy retains the duplicate output rows. It is just the same as when you specify neither DISTINCT nor ALL; ALL ic essentially a clarifier rather than a functional argument, Thus if you give SELECT ALL city FROM suppliers ; itwill give values of city column from every row of the table without considering the duplicate entries. Considering the same table Suppliers, now the output will be as shown here. XAMPLE 13.2 Display species of all pets from table pet. oeleona Solution. oases mysql> SELECT ALL species FROM pet ; eae | 609 dog | dog | bara | bird | snake 3.5.7. Viewing Structure of Table Loeasies just ba u ybasename> ; A., learnt just back that Use USE menager: eee patabase changed mysql> SHOW TABLES ; COMPUTER SCIENCE WITH PYTHOW) : ESCRIBE pets OF DESC pet ; will display the structure of table For instance, the commands : D! mysql> DESC pet : default | extra | Null | Key! char (1) pirth | date i + Takenanta0) | YES 1 ' | varenes (20) \ i Vwenae (25) | 128 i i i as | i ' t i i i 6 rows in set (0.01 sec) 2 a Often a simple calculation needs to be done, for example, 4 *3, The only SQL verb to cause ay ‘output to be written to monitor is SELECT. For instance, when a calculation is to be performed such | se being referenced, only numeric literals are being used as3* 4or8* 3etc, there really isno tab! For this you can use SELECT statement to retrieve rows computed without reference to any table, For example, consider the following query that computes the expression 1+ 6 and outpus the result. Notice that no fable or FROM clause is used in the following query. ; 13.5.8 How to Perform Simple Calculations mysql > SELECT 1465 ee ‘The result of expression given with SELECT 1 row in set (0.00 sec) ing ir MySQL also provides a dummy table called Dual to provide compatibility with SQL of tte DBMSs. Dual table is a small worktable, which has just one row and one column, It can be use! for obtaining calculation results and also system-date. add The following query : SELECT 4 * 3FROMdual ; will produce the result as : ‘The current date can be obtained, using function curdate( as shown below : a mysql> SELECT curdate( ) ; ‘Chopter 13 : SIMPLE QUERIES IN s@L 13.5.9 Scolar Expressions with Selected Fields If you want to form sit * ASE 7s co sumeric computations on the data to put it in a form more wcleced OLSEN aati san a to place scalar expressions and constants among the Si eanple, consider it desirable to present your sal commissiol a Me ns 2S percentage rather than decimal numbers, You may do it a a pi SELECT salesman_name, comm+100 FROM salesman ; The output will be somewhat like : on ‘that if a value in the expression is Null then result of the ‘expression will be Null only. ‘operators that you can use in arithmetic ex] i lt inus (—), divide (/) tipl Olah a ae spressions are plus (+), minus (~), divide (), multiply 13.5.10 Using Column Aliases The columns that you select in a query can be given a different name i, column alias name for output purposes. For instance, if you want to extract information (date and type) from Event table and want the name of Type column should appear as Event Type, then you should give query as follows : SELECT date, type As "Event Type” + 1 FROM Event 5 | 1995-05-15 | litter t | 1993-06-23 | litter 1 The i -06-- litter 1 ‘output produced by above query will be : 1 1996-06-19 | u y - | 1999-03-21 | vet 1 mysql> SELECT date, type AS “Event Type” | 1997-08-03 © 1 vet 1 | 2991-10-12 | kennel 1 = EROMGL ane | 1991-10-12 | kennel 1 | 1998-08-28 | birthday I j 1998-03-17 | birthday 1 | 1998-12-09 | birthday i tice that the column Comm has been given) >-7-—-- es x reareslisst nace Commission. This has been“? (0100 sec) done as per following syntax : Select AS [columnalias] [, AS [colunnalias]} COMPUTER SCIENCE WITH POW ‘Table : Student a etl ee the expression 22/7 has been given alias as PI, When the alias name contains more than one word, you have to enclose them in quotes as we did in previous query where we enclosed the column alias Event Type in quotes as “Event Type”. EXAMPLE 13.3 Given a table student as shown here. Write a query to display name, sex and aggregatel5. Label this computation as percentage. Solution. mysql> SELECT name, sex, aggregate/5 AS Percentage -> FROM student ; & | Percentage | aot | Abu Bakar | |} 91.2000 1 | Aanya LF | 68.0000 | Gurvinder | F | 36.0000 | alt lu | 52.0000 | Michelle | F | 64.2000 | Zubin is | 82.4000 Simran | F | 75.6000 | Fatimah | F 1 80.0000 | Anup im | 60.4000 I Mita ee 1 30.0000 iy: isis 10 rows in set (0.00 sec) 13.5.11 Handling Nulls As already mentioned, the column having null values id PLE QUERIES IN SQL < choles '3 SIMP| : ; H1_val ates ‘ see the null values appear as NULL. If you want to substitute i ‘ null with a value in the you can use IFNULL() function. IFNULL() function may be used as per f lue oo TNULL (, Value-to-be-substituted) That is, if you want to substitute value alive for null in death, the query should look like : SELECT name, birth, TFNULL (death, “alive") FROM pet 3 And the output will be like : mysql> SELECT name, birth, IFNULL (death, “Alive") FROM pet; \ name | bazth) | TENULL (death, "Aliven) | | Florey | 1993-02-04 | alive t | Claws, | 1994-03-17 | Alive f | Buffy | 1989-05-13 | Alive 1 ) Fang | 1990-08-27 | Alive 1 | Bowser | 1979-08-33 | 1995-07-29 1 | chirpy | 1998-09-11 | Alive ' | Whistler | 1997-12-09 | Alive ' | stim | 1996-04-29 | Alive 1 | Puffball | 1999-03-30 | Alive 1 9 rows in set (0.03 sec) - You may also use column alias to replace output heading, This can be done as follows: mysql> SELECT name, birth, IFNULL(death, Alive") AS "Died On" Ee FROM pet 5 4 Now the output produced will be: | pied en he 3993-02-04 | Alive ) 1994-03-27 j 1989-05-13 | 1990-08-27 548 COMPUTER SCIENCE WITH. UPTON — 5.12. Putting Text in the Query Output base The previous example can be refined by marking the commissions as percer \ Percent sign (%). This enables you to put such items as symbols and comments in the in the following example : SELECT sal FROM s. n_name, comm * 100, *X' A sample output produced by above query is shown here. See, the same comment or symbol gets printed with every row of the output, not simply once for the table. ‘You could insert text in your query also, making it more presentable. For example, comm*200 | commission gets the commission | 11.00 commission Chopter 13 : SIMPLE QUERIES IN SQL SELECT [, , . FROM
WHERE ; when a WHERE clause is present, the database program goes through the entire table one row ata time and examines each row to determine if the given condition is true. Ifitis true for a row, that row is displayed in the output. For example, to display the name and aggregate for students having their aggregate marks more than 350, the command would be mysql> SELECT name, aggregate ie | name | aggregate | => FROM student ae > WHERE aggregate > 350 ; | Abu Bakar | 456 \ | Gurvinder | 480 \ ‘The above query will produce adjacent output : | 2ubin | 42 I | simran | 378 ' Only the records having aggregate > 350have | Fatiman | 400 1 appeared in the ouput. +=~ 5 rows in set (0.03 sec) AMPLE 13.5 Write a query to display name, age and marks rate) of students whose age is greater than or equal to 16 m table student. Solution. mysql> SELECT name, age, aggregate FROM student > WHERE age >= 16 ; relational operator is used. The result of the comparison is true or es f relational operators : ee 550 i COMPUTER SCIENCE hilt 13.5.15 Logical Operators The logical operators OR (||), AND (S&) and NOT (!) are used to connect the WHERE clause. For example, SELECT ecode, ename, FROM employee \des ‘E2’ or ‘E3! from table employee (not Z ee SOR WHERE (grade ="E4" AND gross <98e0) 1 To list the employees’ details having | the EMPL table), logical operator OR will ved Symbol && may also be used as AND. SELECT ecode, ename, grade, gross ‘operator. | FROM employee : WHERE (grade ="€2' OR grade="E3") 3 BE Ae lie eae te th Symbol || may also be used as OR operator operator NOT will be used as: i, above query may also be written as : SELECT ecode, ename, grade, gross SELECT ecode, ename, grade, gross FROM employee a i FROM employee WHERE (NOT grade = ‘e1 ys i WHERE (grade ="E2'||grade ="E3") 5 | symbol 1 may also be used Not 2. To list all the employees’ details having | Operator. Biase oasis grades as EA’ but with gross< 9000, logical | maeng sealesitt operator AND will be used as : when all the logical operators are used together, the order of precedence is NOT (1), AND (&&) and OR (1). However, parentheses can be used to override the default = EXAMPLE 13.6 Write a query to display all the details from pet table for species fish avin: ze Jas male (‘m') mo Solution. mysql> SELECT * FROM pet SS WERE (species = ‘cat’ |||spentes | name | owner | speci Chopter 13: SIMPLE QUERIES IN. SQL If the Items Table is as shown below ; Table 34. Items | rcode | Desep 1 goa 1 (Only the lems having QOH beoween 30 ee je ath i 0.50 have been lised ‘The operator NOT BETWEEN is reverse of BETWEEN operator, that is, the rows not satisfying the BETWEEN condition are retrieved: For example, SELECT icode, descp FROM items “This query wil ist the toms whose ROL is WHERE ROL NOT BETWEEN 1@@ AND 1000 ; thelae 1 Bag above £000. EXAMPLE 13.7 Write a query to display name and aggregate marks of those students who don't have their aggregate marks in the range of 380 — 425. Solution. | name | aggregate | mysql> SELECT nane, aggregate cts => FROM student | Abu Baker | 456 1 => WHERE aggregate NOTBETWEEN 380AND425; | serv snaor | ay : yas | 260 1 | Micherze 322 i | Sincen | 378 \ ition Based on a List | Anup | 302 1 F {vite | iso \ of values, IN operator is used. The IN values that:match any valueinagiven rows in set (0.00 sec) a list of members from ‘DELHI, ‘MUMBAI’, ‘CHENNAI’ or may give say ee aE COMPUTER SCIENCE WITH PYTHON EXAMPLE 13.8 Write a query to display all details of pets of species bird, snake or hamster from table pet Solution. mysql> SELECT * FROM pet => WHERE species IN(‘bird’, ‘snake’, hamster’); tp | 1 birth death | species | sex | Chizpy | Gwen | bird | £ | 1998-09-11 | NULL | Whistler! Gwen | bird © | NULL | 1997-12-09 | NULL { Slim | Benny | snake | m | 1996-04-29 | WULL ¢ | Puffball) Diane | hamster | | 1999-03-30 | NULL 4 rows in set (0.00 sec) 13.5.18 Condition Based on Pattern Matches SQL. also includes a string-matching operator, LIKE, for comparisons on character strings using patterns. Patterns are described using two special wildcard characters : © percent (%). The % character matches any substring. © underscore (_). The _ character matches any character. wits Patterns are case-sensitive, that is, upper-case characters do not mat ase characters, or vice-versa, To illustrate pattern matching, consider the following examples: © ‘San%’ matches any string beginning with ‘San’ athe wene © %idge% matches any string containing ‘idge’ as a substring, for example, ‘Ridge, ‘Bridges’, ‘Cartridge’, ‘Ridgeway’ etc. ; © ‘---~ matches any string of exactly 4 characters. © ‘---% matches any string of at least 3 characters. keyword is used to select rows contai To list members which are in SELECT firstname, FROM members WHERE pin LIKE "13%"

You might also like