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

Full Mysql Class 12

Uploaded by

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

Full Mysql Class 12

Uploaded by

Manu Katiyar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 74
DATABASE MANAGEMENT FOR CLASS - XII KAPILSEHGAL KAPIL SEHGAL (P.G.T. (CS) K.V. NO2 Delhi Cantt, WHAT IS DATABASE collected information which is in an organized form for easier access, management, and various updating is known as a database. Ex, Containers having a huge amount of data are known as databases, for example, a public library stores books. Databases are 1. Oracle computer structures that save, organize, protect, and deliver data. 2. SOL Server 3. MS Access Any system that manages databases is called a database Ssoraterty, management system, or DBMS. The typical diagram representation | for a database is a cylinder. — KAPIL SEHGAL. DATABASE, TABLES, ROWS AND COLUMNS Database Database is a collection, or a set of tables. Each table has a formalized repeating list of data about one specific information, For example a table for customers, students, orders, products and so on. Visually, it's often shown like a spread sheet. Tables The table is the most basic building of a database. It’s the place where you will put your data, define their data type, and also their relationship with the other tables. It consists of rows, and columns. Rol Name Class [Marks [City 101 Rohan x1___ [400 Jammu 102 Aneeta Chopra xi__[390 (Udhampur 103 Pawan Kumar 1X [298 [Amritsar 104 Rohan Ix [376 Jammu 105 Sanjay vu [240 Gurdaspur 113 Anju Mahajan vin [432 Pathankot KAPILSEHGAL © ROW & COLUMNS Within each table, every single row represents one single student, customer, order, or employee. But each of these rows is not free form, You must apply structure to this data. So, you must say what every row is made of, and you do this by defining the columns in that table. And each column describes one piece of data. It gives it a name like name, id, email, date of birth, and a type, perhaps, a text, or a date, or a number. Now, every row must follow that same structure, following that same format. It’s not allowed to deviate from the way that the columns are set up. And by defining these columns, we're imposing rules on the data, and the DBMS won’t let us break them, Ina nutshell Columns define what’s the data that should be in the table, while the rows hold the actual values that you are going to retrieve, insert, update, and delete. KAPILSEHGAL Concept of Domain RELATIONAL DATA MODEL A domain is the original sets of atomic values used [Betts [Name [ctass [Marks [ete to model data, By atomic value, we mean that each 1?! Reba _—___1x¥_00._faina_— value in the domain is indivisible as far as [101 [Pawan Kuma [Dx [28 [Ammar the relational model is concerned. For example: 44 —_[Retwx pfs fame The domain of Marital Status has a set of [tS—[o"Siaa—[wur astro possibilities: Married, Single, Divorced. - Schema Table Relation Relation (collection of rows and columns generally refers to an active entity (not be duplicate) on which we can perform various operations KAPIL SEHGAL. The database schema of a database is its structure described in a formal language supported by the database management system (DBMS). The term "schema’ refers to the organization of data as a blueprint of how the database is constructed (divided into database tables in the case of, relational databases). Table (collection of rows and columns generally refers to an passive entity (may be duplicate) on which we can perform various operations RELATIONAL DATA MODEL Tuple A row in a relation is called a tuple. [Rot no [Name [ciase [otarks [City 101 |Rotan [400 [Fame reeiaies 102 Anceta Chopra |X_|390 | Udhampar 103 [Pawan Kumar [DC [208 [Arai Accolumn in a relation is called an attribute. Itis also HO! [Rots fare: beens termed as field or data item een Ee fer [3 [an Mahajan [vin [352 [Pathan Candidate Key Primary Ke; Set of all attributes which snate eee can serve as a primary key in Primary key is a key that can uniquely All the candidate keys other a relation. ie. A table / identifies the records/tuples ina relation, than the primary keys of a relation has more than one There are following feature of Primary key elation are alternate keys for columns which all have (1) Itcannot be duplicate in entire column —_@ relation features to become a primary (2) It cannot be NULL (absent of value) Key key. Then all such columns (3) A table / relation cannot have more than are known as candidate key. one primary key. Key is the name of column. KAPIL SEHGAL, Foreign Key RELATIONAL DATA MODEL WORKERS OES. FIRSTNAME_[LASTNAME [ADDRESS [CITY WalD | SALARY] BENEFITS | DESIGNATT ‘102 ‘Sam Tones 33 Elm St. Paris _ ON’ 105 [Sarah ‘Ackerman | HOUS. 110 [New York 102 7000 —| 15000 Manager iat [Mania Sengupta | 24 Friends Steet_[ New Delhi Tos [ 85000 ——[23000. Director 210 | George Smith 83 First Steet | Howard 144 {70000} 15000 255 [May Ione: ——[B12Vine Ave. [Loti 210 {7000 | 12500, 3 ober a ith Cross | Washingon zs {e000 T iz00 3335_—_[ Hen ‘Williams | 12Moore Sire [ Boson ‘s90__{ boon _|. tan 403 [Ronny Lee 121 Harrison St_[ New York oa ee a1 [Pat ‘Thompson [11 Red Road [Pais 451 [28000 — 7500. Salesman Definition: Foreign keys is the column of a table that points to the primary key of another table. They act as a cross-reference between tables. Definition: Foreign keys is the column of a table that takes the value from primary key from other table from the same database. KAPIL SEHGAL. The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table. Here W_ID is the Primary key in Workers Table and foreign key in Desig Table Degree RELATIONAL DATA MODEL Definition: Degree of the table / Relation means the number of Column. Cardinality Definition: Cardinality of the table / Relation means the number of Rows. workers pesic {iD [ SINAN [LAST NNE wa BeNETTS [DESIGNATE Tt | ie oe tos —|San ——[ az 13000 tite —1 Sage Tos 23000 it |Cage —[ Sa He i300 eo S00. tooo 38. Hey —— Win a 15908 ‘Rens Taw 08 tea ih — a 208 Ex. Degree : 5 Ex. Degree : 4 Cardinality : 9 KAPIL SEHGAL. Cardinality : 9 What is Structured Query Language STRUCTURED QUERY LANGUAGE SQL is a non procedural language that is used to create, manipulate and process the database relations Characteristics of SQL 1. 2. 8), Itis very easy to learn and use. Large volume of databases can be handled quite easily. It is non procedural language. It means that we do not need to specify the procedures to accomplish a task but just to give a command to perform the activity. . SQL can be linked to most of other high level languages that makes it first choice for the database programme KAPIL SEHGAL. Need of SQL It is widely used in the Business Intelligence tool. Data Manipulation and data testing are done through SQL. Data Science tools depend highly on SQL. Big data tools such as Spark, Impala are dependant on SQL. It is one of the demanding industrial skills. Processing Capabilities of SQL STRUCTURED QUERY LANGUAGE ‘The following are the processing capabilities of SQL 1. Data Definition Language (DDL) Data Definition Language (DDL DDL contains commands that are used to create the tables, databases, indexes, views, sequences etc. e.g.: Create table, create view, create index. Other than create command ALTER and DROP is also DDL Commands 3. Data Control Language: This language is used for controlling the access to the data. Various commands like GRANT, REVOKE etc. are available in DCL 2. Data Manipulation Language (DML) DML contains command that can be used to manipulate the data base objects and to query the databases for information retrieval. e.g. Select, Insert, Delete, Update ete. 4. Transaction Control Language (TCL) TCL include commands to control the transactions in a data base system, The commonly used commands in TCL are COMMIT, ROLLBACK etc. Data types of SQL Data Types STRUCTURED QUERY LANGUAGE Just like any other programming language, the facility of defining data of various types is available in SQL also. Following are the most common data types of SQL. 1 Int : Used to store a numeric value in a field/column. Itis for integer value. 2. Float : Used to store a numeric value in a field/column, It is for real or decimal value 3 Char : Used to store a fixed length characters or fixed length string 4 Varchar : Used to store a variable length characters or variable length string 5 Date ; Used to store a date type value 6 Boolean : Used to store a Boolean type value (ie. TRUE / FALSE) STRUCTURED QUERY LANGUAGE Creating Table Data Definition Language (DDL) Creating Database Sql> Create database ; Syntax Sql> Create database XII ; CREATE TABLE table_name ( column! datatype, Here a database named XII will create in column? datatype, column3 datatype, ... ); your current user id (By default is “root”) [Cotumn1 —_[Column2 [Columns Hise hrnake ative vane dave Here original sequence will be Columnl, Sql> Use ; Column? and Column3 that will never change. Sql> Use XII; Example CREATE TABLE Emp (Empld int, EmpName Here through the USE command we can varchar(30), Designation Varchar(20)); activate the database, XII is the database name. Empid | EmpName | Desi KAPIL SEHGAL, Database Constraints STRUCTURED QUERY LANGUAGE SQL constraints are used to specify rules for the data in a table. Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted. Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole table. The following constraints are commonly used in SQL: NOT NULL - Ensures that a column cannot have a NULL value (Ex. Name Varchar(20) Not Null) UNIQUE - Ensures that all values in a column are different (Ex. Rollno int Unique) PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table (Ex. Admno int Primary Key) FOREIGN KEY - Uniquely identifies a row/record in another table CHECK - Ensures that all values in a column satisfies a specific condition (Ex. Marks int Check(Marks>0) DEFAULT - Sets a default value for a column when no value is specified (Ex. City Varchar(20) default ‘New Delhi’) Database Constraints STRUCTURED QUERY LANGUAGE Similarity and Difference between UNIQUE and Primary Key. Similarity Both Primary Key and Unique cannot be duplicate in entire column Difference (1) Primary Key cannot be NULL while Unique can be Null (2) Primary Key can not more than one in a table but Unique constraints can be more than one in a table. Ex. Primary Key : Admission_No, Emp_Id, or any other types of id. Unique: Phone_No, Vehicle_No. Creating Table D.D.L. STRUCTURED QUERY LANGUAGE (Eee eee Eeezel nit a aaa Eee CREATE TABLE STUDENTS(ROLLNO INT,FNAME VARCHAR(10) NOT NULL, SNAME VARCHAR(15), CLASS INT NOT NULL, SECTION CHAR(1) NOT NULL, STREAM VARCHAR(10),CITY VARCHAR(10), MARKS INT CHECK( MARKS>0),DOB DATE, ADMNO INT PRIMARY KEY); aysal> aysql> DESC STUDENT! View the structure of the table varchar(10) varchar(15) Sql > Desc Students; char(a) Varchar(10) varchar(16) Sne(aa) ate. Snt(aa) KAPIL SEHGAL, Inserting Row into Table D.M.L. STRUCTURED QUERY LANGUAGE Inserting Row into Table with All Columns INSERT INTO TABLE-Name Value (value of column], value of column 2, value of column3...); Ex. Insert Into students values (101,’Ram',’Sharma’,12,"A’,'Science’,’New Delhi’,494,"2001-04-15",20795); Insert Into students values (102,"Govind’,’Shukla’,12,’B",’Seience’,’New Delhi*,475,'2002-08-03",25437); Insert Into students values (102,’Shyam’ Tiwari ESS 101 ,12,’C’,’Commerce’,’Bhopal’ 485,’2002-08-25’,25737); Stream City | Marks | DOB 20795 Sharma Science Ls Delhi 494 2001-04-15 102 Govind Shukla 2 B Science NewDelhi 475——-2002-08-03 25437 103 Shyam Tiwari R © Commerce Bhopal. 485. 2002-08-25 25737 KAPIL SEHGAL. D. ie STRUCTURED QUERY LANGUAGE Inserting Row into Table with Selected Columns INSERT INTO TABLE-Name ColumnsName (column1, column2,....) values (valuel value2,.....)); Insert Into students (Rollno,Fname,Class,Section, Stream, Marks,Dob,Admno) Values (104,’Murli’,11,'A’,’Commerce’,486,"2001-08-06",25187); Insert’ Into students (Rollno,Fname,Sname,Class,Section,Stream,Marks,Dob,Admno) Values_(105,"Kishan’, “Trivedi’,11,"B",’Science’,492,'2002-08-25",25987); KAPIL SEHGAL. Fetching data from table SELECT STRUCTURED QUERY LANGUAGE Select Command for all attribute with from clause Syntax. Here “ ;” Semicolon represent the termination of SQL command. “From” is a clause and “Select” is a command. Select * from TableName ; Here “*” represent “All Columns” of table Here our table students have 9 Columns so all columns is displaying here. EX. —Mysql>Select * from Students; Fetching data from table SELECT STRUCTURED QUERY LANGUAGE Select Command for selected attributes(Columns) Syntax. Select from TableName ; Here List of Attributes (Columns) must be separated with comma EX. —Mysql>Select Fname, Sname, Class, Section, Admno from Students; ott KAPIL SEHGAL, Fetching data from table WHERE. STRUCTURED QUERY LANGUAGE Select Command for selected tuple (Rows) using “WHERE” Clause Syntax. Select / * from TableName Where ; Ex. a eae ae ‘New Delhi” ; Here Only those rows will display who for which given condi will satisfied. (Condition returns TRUE ) Ex. MysqI> Select * from students where section KAPIL SEHGAL, Fetching data from table Logical Operators. STRUCTURED QUERY LANGUAGE Select Command : Selected Rows with Logical Operators (AND,OR,NOT) AND _ : All Conditions must be True to display a row OR _: Atleast one condition must be True to display a particular row NOT _ : NOT operator just reverse the stage from True to False and Vice Versa Ex. SELECT ADMNO,FNAME FROM SELECT FNAMESNAME SELECT ADMNO,FNAME FROM STUDENTS WHERE nol STUDENTS WHERE STREAM='SCIENCE’ —_ STREAM='SCTENCE’ AND FROM STUDENTS WHERE CITY='New Delhi AND "OR MARKS > 480); "OR MARKS > 480; SECTIO! ow + | 25437 | Govind | Fetching data from table Range Searching © STRUCTURED QUERY LANGUAGE Range Searching using “BETWEEN” and “AND” Operators BETWEEN : Value BETWEEN .. ... (Inclusive Both end Value) AND Here Value can be inform of (Numeric Value as well as Date Value and String Value) Ex. Value in form of String select ® from students where stream between ‘aaaaaaaaa’ select * from students where stream between ‘aaaaaaaaa’ and, and 'dzezzz27'; waa oR OR select * from students where stream >= ‘aaaaaaaaa’ and select * from students where stream >= ‘aaaaaaaa’ and stream KAPIL SEHGAL. Range Searching Range Searching using “BETWEEN” select * from students where DOB BETWEEN '2002-01-01" AND 2002-1 OR select * from students where DOB >= '2002-01-01' AND DOB <= "2002-12-31"; sab St * ru studs ie Ob >= BOO eR STRUCTURED QUERY LANGUAGE and “AND” Operators select * from students where DOB BETWEEN '2001-01-01" AND '2002-12-31'; OR select * from students where DOB DOB<= "2002-12-31"; na slet "fon sae re 89 "0-2-1 MO De | uso | rane | sve | cas | scr | ste | ery '2001-01-01" AND MEAs | as | ow Luo | FWE | SORE | CUSS | Ser | smn | CTY | mS [O08 | AD | on aerceets fovnietrmnnnteesntnesenboneet | 4A Ran [Stara | A2| A |S |v Bell | a8 | a4 42 | Gori | sida | | cece | ev eet | 95 | mes | 25 || mark | mck | | amc | || 0-8 | SH | M2 | Son | Tart | 2c | Cnc | gal |e | aes | 57 | | nt | vit | ude | a2 | © | Scene | neu DIN | 5 | RAE | 567 | a5 | shin | Tele | an [8 | Selene | mk] a | mae | 57 || at | Son | Ted | a2 || Cece | tga | | abs | 577 | 5 | sk | inet | a1 | | Scece [we | 2 | aa | 590 | KAPIL SEHGAL, Range Searching Range Searching using “BETWEEN” select * from students WHERE MARKS BETWEEN 470 AND 490; OR select * from students WHERE MARKS >=470 AND MARKS <= 490; ya selec * ru stats WHE WS 20 MO OS 8 | sk | css | Scr | sac | CTY [a | | ‘tele |u| Ut |omrce] ate | | canes | | dt in| she | || Stee | nev ote | 5 | a | 7 | 3a | Sym | Tek | 2 Cm | Bl | 5 | 025 | 27 | KAPIL SEHGAL, STRUCTURED QUERY LANGUAGE and “AND” Operators select * from students WHERE MARKS BETWEEN 485, AND 495; OR select * from students WHERE MARKS >=485 AND MARKS <= 495; ‘ys select * from tet ERE RUS RENEE AHS 5; [tu ese | cs | can | tan |v [is | oe | [Get T am [stews | Lk Se [hw || OS [a | | ame [rmetz [ne | ak | Comerce | tt | 6 | ot | 218 | sm [syan | iaek | afc | Camere | opel | | ona | 25757 | [15 [ shan | Trived | uk | at | a 25 | 59 | M(B | Sceme Fetching data from table In/NotIn STRUCTURED QUERY LANGUAGE IN keyword only affects the rows whose values matches the list of values provided in the IN keyword. IN helps reduces number of OR clauses you may have to use Ex. Give the Name and Admission number and city of those students who city either New Delhi , Mumbai or Bhopal select Fname,Admno.city from students where city in (New Dethi’,,Bhopal’ Mumbai); OR select Fname,Admno,city from students where city=New Delhi’ OR city kam | | 20798 | New Deine Govina | 28437 | New Deint Shyam’ | 25937 | Bhopal KAPIL SEHGAL. Give the Name and Admission number, Class and Section of those students who studying either Neither Section A Nor Section B. select Fhame,Admno,Class.Section from Students where Seetion not in ('A'’B'); OR select Fhame,Admno,Class.Section from Students where Sections>'A’ AND Section<>B' | Frame | Adano | Class | Section | = a | Shyam | 25737 | 12 | € 1 beceececbeceeneot 1 row in set (@.0@ sec) Fetching data from table Pattern Matching STRUCTURED QUERY LANGUAGE Pattern Matching using “%” and “_” with ‘LIKE’ clause It matches any pattern based on some conditions provided using the wildcard characters. Some of the commonly used wildcard characters in MySQL are as follows: '%' represents zero or more characters. '_' represents exactly 1 character Ex. Give Fname, Admno and Stream whose name First Name starts with ‘S* Give the details of students whose city name start with B and ends select * from students where city like 'B%L'; select Fname,Admno,Stream from students where stream like 'S%' Give the details of students whose sname contains “sh” any where in any location (either beginning ,end or middle) select * from students where Sname like '%sh%'; i KAPIL SEHGAL. L Fetching data from table Pattern Matching STRUCTURED QUERY LANGUAGE Pattern Matching using “%” and “_” with ‘LIKE’ clause Give The Details of those students whose Give The First Name, Surname, Class, second letter of surname is ‘h’ Section, Admission No and City of those students whose city contains second select * from students where sname like '_h%'; letter ‘h’ and second last letter is ‘a’ select Fname,Sname,Admno,Class,Section,city aT calico ete [mun |e |owe |cxs| scm jem jay {ams|on [amo] from students where city like ' h%a_'; | A | an | Shama | 2 | | Slate | eel | 8 | 5 | 5 | ad | Sh ence | Neh KAPIL SEHGAL, Searching NULL Values STRUCTURED QUERY LANGUAGE ISNULL / IS NOT NULL NULL is a special value that signifies ‘no value‘. Comparing a column to NULL using IS NULL or IS NOT NULL. Give The Details of those students Whose Give The Details of those students Whose city contains NULL city contains NOT NULL SELECT * FROM STUDENTS WHERE CITY IS NOT NULL; SELECT * FROM STUDENTS WHERE CITY IS NULL; KAPIL SEHGAL, Using “DISTINCT” STRUCTURED QUERY LANGUAGE The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, column often contains many duplicate values; and sometimes you only want to list the different (distinct) values. Give the details of all students but List the Different city names from duplicate record will show only once. students table Select Distinct City from Students; Fee ees ee ee Foam in Get (0,04 52) KAPIL SEHGAL, Order By STRUCTURED QUERY LANGUAGE The ORDER BY Clause can be used along with the SELECT statement to sort the data of specific fields in an ordered way. It is used to sort the result-set in ascending or descending order. List the details of the students which is List the details of the students which is . ; : : arranged by the Sname in Descending arranged by the Fname in ascending ae Order Me Select * from students order by Fname; A eee sear eee SELECT * FROM STUDENTS ORDER BY SNAME dese; Note: By default sorting of data willbe in ascending order KAPIL SEHGAL. Order By with multiple field STRUCTURED QUERY LANGUAGE When multiple columns are used in ORDER BY, first the rows will be sorted based on the first column and then by the second column and so on. Note: By default sorting of data will be in ascending order, You can also make the combination of First sorted with ascending order of any column then second may be descending order or vice versa Ex. Give the details of students sorted Class then Section the third key be first name. Select * from students order by class , section , Fname Ex. Give the details of students sorted Class then Section descending order the third key will be first name. select * from students order by class, section desc , fname ; Ex, Give the details of students sorted Class descending order then Section the third key will be first name in descending order. select * from students order by class desc, section , fname desc; KAPIL SEHGAL, Delete Command DELETE command to delete data from a MySQL table. If the WHERE clause is not specified, then all the records — will be deleted from the given MySQL table. You can specify any condition using the WHERE clause To delete all records from table. Delete from TableName; Ex. Delete All Records from Student Table Delete from Students; ‘To delete selected records from table. Delete from TableName where Condition ; STRUCTURED QUERY LANGUAGE Delete all those students whose city is not mentioned Delete from students where city is NULL ; Delete all those students whose Name is “RAJ” Delete from students where fname = “RAJ” ; Delete all those students whose marks between 400 to 450 Delete from students where marks between 400 and 500; Delete all those students whose name starts with ‘A’ Delete from students where fname like ‘A%’; Update Command STRUCTURED QUERY LANGUAGE ‘The MySQL UPDATE query is used to update existing records in a table in a MySQL database. (1) It can be used to update one or more field at the same time. (2) It can be used to specify any condition using Update city as “New Delhi”all those students whose city is not mentioned Update students Set City = ‘New Delhi’ the WHERE clause ero nN Update Fanme as “Raj Kumar’ all that students Syntax : whose admno = 1250 Update TableName Update students set fname = ‘Raj Kumar’ Set Column1=value! [, Column2= Value2, .] where admno=1250 [Where ;] Update marks as 500 all those students whose marks between 400 to 450 Update Students set marks = 500 where marks between 400 and 500 ; AGGREGATE FUNCTIONS Returns the SUM of all the values, or only the DISTINCT values, in the expression, SUM can be used with numeric columns only. Null values are ignored. SUM ( [ DISTINCT] exp Here Duplicate(in case of counts only once. Select Sum(Distinct(Marks)) from Students; Select Sum(Marks) from Students; ‘phal> Select’ Sum(Marks) fron students; Siew) | a ‘ow in sat (0.06 sec) KAPIL SEHGAL. AGGREGATE FUNCTIONS Returns the AVG of all the values, or only the DISTINCT values, in the expression. AVG can be used with numeric columns only. Null values are ignored. AVG ( [ DISTINCT] expre Here Duplicate(in case of Di counts only once. ion / Column) inct) values Select AVG (Distinct(Marks)) from Students; Select AVG(Marks) from tees te fee eta warn Students; He Son: | (S| ieee: | Sa | a Sc nS gu: (ERO ERE | RSE | BS | sve(ranes) i ~ ae + - Lincs f 1 aa al eee ee srscoossom once KAPIL SEHGAL. AGGREGATE FUNCTIONS Returns the Maximum Value from entire Column Max() can be used with numeric columns only. MAX (Column) Select Max(Marks) from Students; yet setectmoxiar) from ster KAPIL SEHGAL, SELECT MAX(MARKS) FROM STUDENTS WHERE STREAM aot ‘iar ease [seca snc” Yo i [Ber kaa T Sana science” Ties int Ta] 5 | | dst [mie | te | | Gamers | tate” |e | sr | | st | Goring | Shoe | Seteece’ | tev pans | 95 | 2eez‘a-es | 2507 | | | Sie | Steal | Seiteet | nes sein: |G | Shencncen | ase | | das | thos | fevecs | 2 fe | Sclnce’ faiths | | Sne-encas | Sever | {386 | te” | AES | [iG | Scone | t fsa SLEr xs rom STURN EE SRE SCENE issn | eT AGGREGATE FUNCTIONS Returns the Minimum Value from entire Column Min() can be used with numeric columns only. MIN (Column) SELECT MAX(MARKS) FROM STUDENTS WHERE CLASS = 12; Select Min(Marks) from Students; ty SELECT mows) Fat STUDENTS: Tangs) | oa] Faw in set (0.09 sec) KAPIL SEHGAL. COUNTO 1. Count (*) returns the number of rows : it does not consider any column contain NULL value or not. 2. Count (Column Name) : returns Number of Rows that contains Valid (Not Null) values. Count How many students in your table. Select Count(*) from Students; come) | ow im set (0.00 sec) Count the number of Cities mention in the students table Select Count(city) from Students; sq SELECT COUNT(CTY) FM STUDENTS; {camer | AGGREGATE FUNCTIONS Count number of distinct cities Select Count(distinct city) from Students; ysai> select count(aisess Count number of distinct cities of those students who studying in class 12", Select Count(distinet city) from Students where class=12; Mathematical Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS Mathematical functions perform mathematical operations on numeric values. POWER() / POW() MOD() Returns the argument raised to the specified power. pow() works the same way. POW(m,n) The mod() function returns the remainder of one number divided by another. Its syntax Its syntax is: | MOD(dividend, divisor) Here, function calculates m raise to power n. Ex. Ex. (i) select pow(2,4); Result: 16 (i) select mod(11, 3); Result: 2 Gi) select pow(2,-2); Result: 0.25 (ii) select mod(10.5, 3); Result: 1.5 (iii) select pow(-2,3); Result: -8 KAPIL SEHGAL. Mathematical Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS Round(nmuber / Column, [Number of Decimal places]) ‘The number of decimal places rounded to. This value will be a positive or negative integer or zero. If this parameter is omitted, the truncate function will round the number to 0 decimal places. Decimal place position value is rounded off to the next integer if the next number on the right side is greater than 5 (>=5), 2. Default decimal place is 0 if nothing is specified and returns the result in integer form. Ex. Second parameter is positive or zero Te Second Paraueter ls nesative 1. Select round(-1.23); Result: —1 1. Select round(27542.29,-1); Result: 27540 2. Select round(-1.58); Result: 2 Select round(27542.29,-2); Result: 27500 3. Select round(1.58); Result: 3. Select round(27542.29, ~3); Result: 28000 a Select round(3.798, Result: 4, Select round(27542.29,-4); Result: 30000 6 454.352 Valuetoberounded | bit ttl “3-24 1253 Decimalplaces Select round(1.298, 0); Result: 1 5. Select round(77542.29,-5); Result: 100000 . Select round(23.298, 2); Result: 23.30 6. Select round(27542.29,-6); Result: 0 Mathematical Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS ‘Truncate(nmuber / Column, [Number of Decimal places]) ‘The number of decimal places truncated (deleted) to. This value will be a positive or negative integer or zero. Decimal place position value is TRUNCATED off to the next integer if the next number on the right side is greater than 5 (>=5). 4.54.35 2 > Valuetobe rounded “3-24 125 Decimalplaces Ex. Second parameter is positive or zero Ex. Second Parameter is negative 1. Select truncate(3.798, 1); Result: 3.7 L. Select truncate(27542.29,-1); Result: 27540 2. Select truncate(1.298, 0); Result: 2 Select truncate(27542.29,-2); Result: 27500 3. Select truncate(23.298, 2); Result: 23.29 3. Select truncate(27542.29, -3); Result: 27000 4, Select truncate(27542.29,-4); Result: 20000 5, Select truncate(77542.29,-5); Result: 0 String Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS ‘These functions are used to deal with the string type values. The various built-in String library functions an ascii(), lower(), upper(), length() instr() left(), right), trim), ltrim(), rtrimQ). mid), substring) substr() ASCHIQ, LOWER()/ LCASE() Returns the ASCII code value of a character icc icieectentiney Converts character strings data into lower case. Syntax: ascii(character); Gusti ula tier Ex. Ex. select ascii('a') from dual; returns 97. select ascii('A’) from dual; returns 65. select lower("INFORMATION TECHNOLOGY"); select ascii('1') from dual; returns 49. Returns ~ information technology select ascii('ABC’) from dual; returns 65. String Functions UPPER(/ UCASEQ, Converts character strings data into upper case. Syntax: upper(string); Ex. select lower(“Information"); Returns ~ INFORMATION LENGTH() Returns the length of the character string, It takes spaces between the strings into account for calculating the total length of the string passed as an argument to length(). Syntax: length(string); select length(‘Information’); Returns ~ 11 Ex. SCALAR FUNCTION OR NON-DATABASE FUNCTIONS LEFTO, Returns leftmost characters from a string, passed as an argument, with the specified number of characters counting from left. left() function is used to retrieve portions of the string. Ex. Syntax: left(string, integer); select left(INFORMATION TECHNOLOGY’, 6); Returns ~ INFORM RIGHT( Returns leftmost characters from a string, passed as an argument, with the specified number of characters counting from left. left() function is used to retrieve portions of the tring. ao. i aos Syntax: left(string, integer); Ex. select right(INFORMATION TECHNOLOGY’, 6); Returns — NOLOGY String Functions LTRIM(Q, Returns a string after removing leading spaces/blanks from the left side of the string passed as an argument. Syntax: Itrim(string); Ex. y (string): select ltrim(’ LIBRARY FUNCTION’); Returns ~ LIBRARY FUNCTION RTRIMO, Returns a string after removing leading spaces/blanks from the right side of the string passed as an argument. ess Syntax: rtrim(string); Ex. _ select rtrim('LIBRARY FUNCTION’); Returns — LIBRARY FUNCTION SCALAR FUNCTION OR NON-DATABASE FUNCTIONS TRIMO Returns a string after removing the spaces from both ends the string passed as the argument to it. Syntax: trim(string); Ex. select trim(‘ LIBRARY FUNCTION "); Returns ~ LIBRARY FUNCTION INSTR() Returns the position of the second string in the first string, if present else return 0. Syntax: instr (first_string, string_to_search); io’); select instr(‘Hello’,'IP’); select inste(“Hello ~* Returns — 3 Returns ~ 0 String Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS SUBSTRING()/ SUBSTR()/ MID() Returns part of an inputted string. A substring() function retrieves a portion of the given string starting at the specified character (start_index) to the number of characters specified (length). Syntax: substring(string, start_index, length); Ex. select substring(‘STRING FUNCTION, 1, 6); Returns : STRING Ex. select substring(‘STRING FUNCTION’, 8, 4); Returns : FUNC Date Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS These functions are used to deal with date. Curdate() Returns the current system date. Ex. select curdate(); Result: '2020-08-06" Now() Returns the current date and time. Ex, select now(); Result: '2020-06-11 13:58:11" KAPIL SEHGAL. Sysdate() Returns the time at which the function executes. Ex. select sysdate(); Result: ‘2020-06-11 13:59:23! Date() Extracts the date part of a date or date-time expression. Ex. select date('2020-06-11 01:02:03); Result: '2020-06-11" Date Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS Dayname() Returns the name of the weekday. Ex, select dayname('2020-06-11'); Result: THURSDAY Dayofweek() Returns the weekday index of the argument. Ex, select dayofweek(2020-06-11'); Result: 5 (Sunday is counted as 1) Dayofyear() Returns the day of the year (1-366). KAPIL SEHGAL Ex, select dayofyear('2020-06-11'); Result: 202 Date Functions SCALAR FUNCTION OR NON-DATABASE FUNCTIONS Month() Returns the month from the date passed. Ex, select month('2020-06-11'); Result: 6 Year() Returns the year from the inputted date. Ex, select year('2020-06-11'); Result: 2020 Day) Returns the day from the inputted date. Ex, select year('2020-06-11'); Result: 11 KAPIL SEHGAL. GROUP BY The GROUP BY clause is a SQL command that is used to group rows that have the same values. The GROUP BY clause is used in the SELECT statement . Optionally it is used in conjunction with aggregate functions to produce summary reports from the database. That's what it does, summarizing data from the database. nbs SELECT cl, ¢2,.. en, aggregate_function(ci) FROM table WHERE where_conditions GROUP BY cl , c2,...,cn; "SELECT statements..." is the standard SQL SELECT command query. "GROUP BY column_name1" is the clause that performs the grouping based on column_name! "{,column_name2,...]" is optional; represents other column names when the grouping is done on more than one column, "[HAVING condition]" is optional; it is used to restrict the rows affected by the GROUP BY clause. It is similar to the WHERE clause. GROUP BY SELECT CITY, SUM(Marks) FROM STUDENTS SELECT CLASS, AVG(Marks) FROM. STUDENTS GROUP BY CLASS; tysal> SELECT CLASS.AVG(H4 CLASS | AVG(Marks) i i [ie | asase000 | ! 1 aa | 484.3333 | 42 | 484.6667 | } rows in set (0.08 sec) Bet (e100 Sec) select class.city,sum(marks) KAPIL SEHGAL from students group by class,city; The HAVING clause is used in the SELECT statement to specify filter conditions for a group of rows or aggregates. The HAVING clause is often used with the GROUP BY clause to filter groups based on a specified condition. To filter the groups returned by GROUP BY clause, we use a HAVING clause. WHERE is applied before GROUP BY, HAVING is applied after (and can filter on aggregates) GROUP BY WITH HAVING select class,avg(marks) from student group by class having avg(marks)<90; eT nc , select class,avg(marks) from student group lass having count(*)<3; Pre) Ere) D.D.L. Command ALTER TABLE To change a column's definition, use MODIFY or CHANGE clause along with the ALTER command Alter Command Can do the following Things Alter Command Can not do when data Present in table 1. Add a Column 1. Add Primary Key 2. Delete a Column 2. Change the Type of Column 3. Rename a Column Which Keyword (Clause) used with Alter Command 4, Increase / Decrease the size of Column 1. Add 5. Add a Primary key 2. Drop 6. Remove a Primary Key. 3. Modify 7. Change the Type of Column, 4. Change KAPI HGAL D.D.L. Command Add New Column u ¢ “ADD” Keywords ALTER TABLE STUDENTS ADD(MotherName varchar(25)); Removing a Column using “DROP” Keywords ALTER TABLE STUDENTS DROP MotherName ; Change the size of Column city using “MODIFY” Keywords either increase or decrease. ALTER TABLE STUDENTS MODIFY CITY VARCHAR(25); KAPIL SEHGAL, ALTER TABLE Some Modification can be done only when table data not present. (i.e. Table is Empty) Change the Type of Column city using “MODIFY” Keywords either increase or decrease. ALTER TABLE STUDENTS MODIFY CITY int; Add Primary Key ALTER TABLE STUDENTS ADD PRIMARY KEY(Column Name) Remove Primary Key ALTER TABLE STUDENTS DROP PRIMAY KEY. Rename a Column ALTER TABLE STUDENTS CHANGE OLD_COLUMN NEW_COLUMN DATATYPE; Delete and Drop Command The following Differences as follows Delete is DML Command While Drop is DDL Command. Delete Command is Deletes the rows from the tables but Drop Command Delete the Entire table with rows. Apart from this Drop command Delete the database and sequence, index etc. . Delete Operations can be rolled back(Undone) while Drop Command Operation Can not be rolled back. KAPIL SEHGAL. DIFFERENCES Update and Alter Command The following Differences as follows. Le ae Update is DML Command While Alter is DDL Command. Update Command modifies in the data (Rows of a tables) while Alter tables changes the design of the table (Make Changes in the structure of the table). DATABASE - CONSTRAINTS FOREIGN KEY A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table. Syntax FOREIGN KEY (Col-Name) REFERENCES STUDENTS (Primary-Key); FOREIGN KEY (STUDENTID) REFERENCES STUDENTS(ADMNO)); KAPIL SEHGAL. ONE MORE EXAMPLE “teen abe: Perso Lasthame 2 sendien 3 Petes “ont table ‘OnderiD——_Ordertuber ersonio 1 9s 2 3 56 2 4 2862 1 KAPIL SEHGAL, stare ne os = Twe a ka a» CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderlD), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) % FOREIGN KEY Notice that the "PersonlD" column in the "Orders" table points to the "PersonID" column in the "Persons" table. ‘The "PersonID" column in the "Persons" table is the PRIMARY KEY in the “Persons” table. ‘The "PersonID” column in the “Orders” table is a FOREIGN KEY in the “Orders” table. ‘The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. ‘The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to. CARTESIAN PRODUCT (X) / CROSS JOIN ; , JOINS jesian Product is denoted by X symbol. Lets say we have two relations RI and R2 then the Cartesian product of these two relations (RI X R2) would combine each tuple of first relation R1 with the each tuple of second relation R2. ran ct) Deis Diss us VARIOUS TYPES OF JOIN Join — Join is used to fetch data from two or more tables, which is joined to appear as single set of data. It is used for combining column from two or more tables by using values common to both tables. ‘Types of JOIN Following are the types of JOIN that we can use in SQL: + Inner + Outer * Left + Right KAPIL SEHGAL. JOINS + Inner join INNER Join or EQUI Joins This is a simple JOIN in which the result is based on matched data as per the equality condition specified in the SQL query. JOINS INNER OR EQUI JOIN An equi join is a type of join that combines tables based on matching values in specified columns. Please remember that: The column names do not need to be the same. The resultant table contains repeated columns. It is possible to perform an equi join on more than two tables. INNER Join or EQUI Join and SELECT A.NAME,A.VAL,C.M1,C.M2,C.M3 FROM A,C WHERE A.VAL = C.M2; INNER Join Using “ON” Clause SELECT A.NAME,A.VAL,C.M1,C.M2,C.M3 FROM. AINNER JOIN C ON A.VAL = C.M2; me | oer | V rows dn Set’ (0.02 ste) NATURAL JOIN JOINS Natural JOIN(04) Natural Join is a type of Inner join which is based on column having same name and same data type present in both the tables to be joined . Select * from C natural join D; LIMITATION OF srysal> SELECT * FROM C NATURAL JOIN 0; ana NATURAL JOIN yoo ii Select * from a natural join b; Both Table have one | 25| “Si | column with same name L sea ietel tener y and same data type. i Select * from A natural join D; mysql> SELECT + FROM A: mysql> SELECT * FROM A NATURAL JOIN D; [mame [vat [92 | (o.00 sec) KAPIL SEHGAL, LEFT OUTER JOIN JOINS The left outer join returns a result set table with the matched data from the two tables and then the remaining rows of the left table and null from the right table's columns. i aed SELECT * FROM C LEFT OUTER JOIN Select * from a left outer join b; PONCE LIMITATION OF and LEFT OUTER JOIN Result table contains only number of row as the left table. ‘SELECT * FROM A LEFT OUTER JOIN D ON A.NAME = D.NAME; mysql> SELECT * FROM A LEFT OUTE [NAME | VAL | NAME | M2 | [asc | 25 | asc | 25 | [oR | 5 | NULL | NULL | ©-00 sec) 3S rows in set (0-00 sec) [DEF | so | DEF | se] KAPIL SEHGAL. 3 rows in set (0.00 sec) RIGHT OUTER JOIN JOINS RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of join, The rows for which there is no matching row on left side, the result-set will contain null, RIGHT JOIN is also known as RIGHT OUTER JOIN reo SELECT * FROM D right OUTER JOIN Select * from a right outer join b; Conca nNtT LIMITATION OF en and RIGHT OUTER JOIN 7 Result table contains only | mut | mut | 20 | 5 | 250 | ae lige a= fe a coral number of row as the [ii iaas meme metal! RIGHT table. + “+ + SELECT * FROM D RIGHT OUTER JOIN A ON A.NAME = D.NAME; [Name | m2 | NAME | vaL | S rows in set (0-00 sec) KAPIL SEHGAL, MYSQL CONNECTOR MySQL connector is an interface for connecting to a MySQL database server from Python It implements the Python Database API and is built on top of the MySQL C API. import mysql.connector OR Import mysql.connector as con Steps to use mysql-connector connector is properly installed KAPIL SEHGAL Download Mysql API exe file and install it. Install Mysql-Python Connector (Open command prompt and execute command) >pip install mysql-connector Now connect Mysql server using python Write python statement in python shell import mysql.connector If no error message is shown means mysql PYTHON-MYSQL CONNECTIVITY WHAT IS CONNECTION The next step to using MySQL in your Python scripts is to make a connection to the database that you wish to use. All Python DB-API modules implement a function ‘module_name.connect()* This is the function that is used to connect to the database, in our case MySQL... CURSOR CREATE CURSOR ‘The next step is to create a Cursor object. It will let you execute all the queries you need. In order to put ‘our new connection to good use we need to create a cursor object. The cursor object is an abstraction specified in the Python DB-API It gives us the ability to have multiple separate working environments through the same connection to the database. We can create a cursor by executing the ‘cursor’ function of your database object. Ex. mycursor = mydb.cursor() KAPIL SEHGAL PYTHON-MYSQL CONNECTIVITY How to create cursor object and use it import mysql.connector mydb=mysql.connector.connect(host="localhost",us er="root" passwd="root") mycursor=mydb.cursor() mycursor.execute("create database if not exists school") mycursor.execute("'show databases") for x in myeursor: print(x) EXAMPLES Simple code to connect to MySQL import mysql.connector as con mydb=con.connect(host="localhost’, user=‘root’, passwd="rootj”) mycursor=mydb.cursor() sql="show databases’ mycursor.execute(sql) myresult = — mycursorfetchall() for data in myresult: print(data) mydb.close() KAPIL SEHGAL. PYTHON-MYSQL CONNECTIVITY Some function and data ‘We can use fetchone() method to fetch single record and fetchall() method to fetch multiple values from a database table. fetchone() ~ It fetches the next row of a query result set. A resultset is an object that is returned when a cursor object is used to query a table. fetchall() ~ It fetches all the rows in a result set. If some rows have already been extracted from the resultset, then it retrieves the remaining rows from the resultset. rowcount ~ This is a read-only attribute and returns the number of rows that were affected by an execute() method. EXAMPLES PYTHON-MYSQL CONNECTIVITY How to create table at run time Table creation is very easy ,if we are already well versed in sql table creation then we have to just pass the create table query in execute() method of cursor object. But before table creation we must open the data base. Here we are opening database school(through connect() method) before student table creation import mysql.connector mydb=mysql.connector.connect(host="'localhost" user=root" passwd="root" dat abase="school") mycursor=mydb.cursor() mycursor.execute(“create table student(rollno int(3) primary key,name varchar(20),age int(2))") On successful execution of above program a table named student with three fields rollno, name, age will be created in school database. We can check student table in mysq] shell also if required. KAPIL SEHGAL EXAMPLES PYTHON-MYSQL CONNECTIVITY How to insert record in a table at run time import mysql.connector mydb=mysql.connector.connect(hos' mycursor=mydb.cursor() while 1 ch=int(input("enter -1 to exit any other no to insert record into student table")) ifel break rollno=int(input("Enter rollno")) class1=int(input("Enter Class")) name=input("Enter name") marks=int(input("Enter marks")) mycursor.execute("insert into student values(""+str(rollno)+",""+name+"',""+str(class1)+",""+str(marks)+")") mydb.commit() "localhos " user="root" passwd="root" databa se: KAPIL SEHGAL, EXAMPLES PYTHON-MYSQL CONNECTIVITY How to change table structure/( add, edit, remove column of a table) at run time To modify the structure of the table we just have to use alter table query. Below program will add a column mark in the student table. import mysql.connector mydb=mysql.connector.connect(host="localhost" user="root" passwd ="root" database="school") mycursor=mydb.cursor() mycursor.execute(“alter table student add (marks int(3))") mycursor.execute("dese student") for x in mycursor: print(x) Above program will add a column marks in the table student and will display the structure of the table KAPIL SEHGAL. EXAMPLES PYTHON-MYSQL CONNECTIVITY How to search records of a table at run time Statement demonstrate the use of select query for searching specific record from a table. import mysql.connector mydb=mysql.connector.connect(host=" localhost" user="root” passwd="ro ot" database=" school”) mycursor=mydb.cursor() nm=input("enter name") mycursor.execute("select * from student where name="+nm+"") for x in mycursor: print (x) KAPIL SEHGAL, EXAMPLES How to fetch all records of a table at run time import mysql.connector mydb=mysql.connector.connect(host="localhost” user ="root" passwd="ro ot” database=" school") mycursor=mydb.cursor() mycursor.execute("select * from student") myrecords mycursor.fetchall() for x in myrecords: print (x) KAPIL SEHGAL PYTHON-MYSQL CONNECTIVITY How to fetch one record of a table at run time import mysql.connector mydb=mysql.connector.connect(host="localhost”, user="root" passwd="root" database="school") mycursor=mydb.cursor() mycursor.execute("select * from student") row=mycursor.fetchone() while row is not None: print(row) row = mycursor.fetchone() FUNCTIONS PYTHON-MYSQL CONNECTIVITY MySQLCursor.fetchone() Method This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects. MySQLCursor.fetchmany() Method rows = cursor. fetchmany(size=1) This method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list. KAPIL SEHGAL. EXAMPLES PYTHON: CONNECTIVITY rowcount Rows affected by Query. We can get number of rows affected by the query by using rowcount. We will use one SELECT query here. import mysql.connector :=mysql.connector.connect(host=" localhost” ,user="root” passwd=" root” database= 's chool") mycursor = mydb.cursor(buffered=True) mycursor.execute("select * from student") noofrows=mycursor.rowcount print(""No of rows in student table are" noofrows) buffered=True We have used my_cursor as buffered cursor. my_cursor = my_connect.cursor(buffered=True) This type cursor fetches rows and buffers them after getting output from MySQL database. We can use such cursor as iterator. There is no point in using buffered cursor for single fetching of rows.If we don’t use buffered cursor then we will get -1 as output from roweount KAPIL SEHGAL, EXAMPLES PYTHON-MYSQL CONNECTIVITY How to delete record of a table at run time import mysql.connector mydb=mysql.connector.connect(host=" localhost" user="root” passwd="root" database="se hol”) mycursor=mydb.cursor() mycursor.execute("delete from student where rollno=1") mydb.commit() In above program delete query will delete a record with rollno=1.commit() method is necessary to call for database transaction. KAPIL SEHGAL, EXAMPLES PYTHON-MYSQL CONNECTIVITY How to update record of a table at run time import mysql.connector mydb=mysql.connector.connect(host=" localhost" user="root” passwd="root" database="sc hol") mycursor=mydb.cursor() mycursor.execute(""update student set marks=99 where rollno=2") mydb.commit(). In above program update query update the marks with 99 of rolIno=2 Students are advised to develop menu driven program using above concepts for better understating of python mysql database interface KAPIL SEHGAL,

You might also like