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

Dbms

Uploaded by

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

Dbms

Uploaded by

Pinchu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 68
notnull unique & 2 natural join ° 9 g £ createtable 8 = 4 join » o 8 8 3 having = delete 5 my orderby Where § Topics to he covered 1. Database concepts 2. Relational data modet 3. Stusctuned Quey Language 4 Interface of python uth an sgt database 157| Page UNIT-III DATABASE MANAGEMENT: Database Concept: Introduction of Database: Database is a word which composed of two words Data and Base. Data means raw facts and figures and base is place or location where data is being stored. Or we can say that Database is collection of interrelated data or record in organized form so it can easily be accessed, managed and updated. Interrelated data means that the data is related or connected to each other with respect to the given attributes or column. Database uses various fields to manage and store large amounts of information in organized and structured format per Gara lected & Stored a DIAGRAM: 1 HOW DATABASE WORES Introduction of Database Management System (DBMS) DBMS is shorten name used for Database Management System. So, as we are aware of database now, we need to understand what DBMS is. Let’s understand it. DBMS is a software system which is used to manage Database. DBMS acts as an interface between a user and database which enables the user to create, insert, retrieve, update and delete the data. Need of Database: Centralized Storage: Storage of data in a single location or central database. Data Integrity: Enforces data integrity rules which ensures that information stored is accurate, valid and consistent, Data Security: Control access to sensitive data and protecting data from unauthorized access. Data Retrieval: Authorized User/Application can access and retrieve the information as per their need. 158| Pace Efficient Data Retrieval: Database helps user to retrieve data in an efficient way. DBMS Model: DBMS refers to that architecture/approach for how data is stored, organized and manipulated ina database. There are several types of DBMS Model. 1. Relational Model: Data organized into tables with rows and columns. 2. Hierarchical Model: Data organized in Tree like structure with parent child relationship 3. Network Model: Similar to hierarchical model. It uses pointers to navigate through data 4. Object Oriented Model: Data is represented as object. This model uses object oriented databases. Now as per you CBSE syllabus we will discuss about Relational Data Model in detail 159| Pace Relational Data Model: Relation Data Model is proposed by E.F. Codd in 1970. In simple words, we can say that Relational data model is a model which uses relation to organize their data. Here, Relation means table and table is composed of rows and columns. CoE Deed Ic) convert Implement, | MEUIer ns eae ies Cs DIAGRAM: 2 ABOVE DIAGRAM SHOWS THAT HOW TO IMPLEMENT RELATIONAL DATA MODEL ‘After creating conceptual data model using ER Diagram we need to convert it into Relational Data Model so that we can implement using any RDBMS language like MySQL, Oracle SQL. Before we proceed further, let's discuss about some aspects of Conceptual Data Model Conceptual Data Model is used to capture the meaning of data from the viewpoint of the user and try to represent it using Data Model tools like ER Diagram and Object Oriented Diagram Basic Terminology of ER Model: ER stands for Entity-Relationship Model. ER Model tools are used to represent Conceptual Data Model. Let’s see some basic tools of ER Model. Entity ‘Any real world object is known as entity person, place, object and event Relationship | Show interconnection between two or more entity Attribute [Shows property/characteristics of an entity/relationship type 160| Pace Relation/Table: Relation is also known table. And table is a collection of related data and information in row and column. Relation is composed of rows and columns. Row/Tuple/Record: Row represent horizontal form of Table/Relation. Row is also known as tuple/record. Column/Attributes: Column represent vertical form of Table/Relation. Column is also known as attributes. Cardinality: Total number of row/record/tuple in a relation is called as Cardinality. Degree: Total number of column/attributes in a relation is called as Degree. - i= = Rohit a Networking Cardinality: 6 2 Sunny rr Sat 3 Ruby @ Python | Preeti a Data Stucture 5 ‘nul 10 Oracle 6 Viney BR Networking DIAGRAM: 3 RELATION/ TABLE COMPOSED OF ROW/RECORD AND COLUMN/ATTRIBUTES Domain: Domain is set of possible value or range of valid values or set of all unique values that an attribute/column can hold. ‘A.Domain of database i attribute/column. set of atomic value (which can’t further be distributed) of a particular 161|Pace For example: In table Employee, Attribute/column gender may have only M, F and T Domain. Only these value valid for that column. Domain of S.No. Contain set of all possible roll numbers, Domain of Martial Status contain set of all possible values like Married, Widow, Unmarried and Divorce. In the below diagram 4, Table Employee contain S.No, Name, Address, Gender and Marital status. Two domain is showing name gender and marital status which contain set of possible values that an attribute can hold. Gender can only hold three possible values and marital status can only hold four possible values aoe aaa S.No Name Address Gender} marital Status 1 Preet Dwarka FE Widow 2 Akash Najafgarh M_ | Unmarried 3 Rahul Uttam Nagar M Married 4 Yashi Kaushambi F Divorce 3 ie Diacram: 4 DOMAIN IN A RELATION DATATYPES IN SQL: Before discussing commands in detail we need to learn about datatype of column/attribute: We need to assign datatype when we are declaring any column/attributes. Every column required name and datatype. This datatypes is used to declare what type of data that will be stored in particular column. There are lots of datatypes available in SL we will discuss some important datatype. 162| Pace Commonly used datatype in SQL: 1. Numeric Type ¢ INT: Integer type ‘* FLOAT: Floating-point number ‘* DECIMAL or NUMERIC: Fixed-point number 2. Character String Type: ‘© CHAR(n): Fixed-length character string with maximum length of n ‘* VARCHAR(n): Variable-length character string with maximum length of n © TEXT Type : Variable-length character string with no specified maximum length 3. Data and Time Type: © DATE: for date only ‘+ TIME: for time only ‘* DATETIME or TIMESTAMP: for date and time combined 4, Other Data type: * NULL: to represent a missing/unknown/empty value + ENUM: A enumeration type for a set of predefined values Now let’s learn datatype in detailed as per your syllabus NUMERIC INT/INTEGER DATATYPE ‘SMALLINT(SIZE) TINYINT(SIZE) MEDIUMINT(SIZE) ‘Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295 ‘SIGNED RANGE IS FROM -32768 TO 32767 UNSIGNED RANGE IS FROM 0 TO 65535 ‘SIGNED RANGE IS FROM -128 TO 127.UNSINED RANGE IS FROM 0 TO 255 ‘SIGNED RANGE IS FROM -8388608 TO 8388607. UNSIGNED RANGE IS FROM 0 TO 16777215 DATATYPE BIGINT(SIZE) Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615 FLOAT(SZ,D) ‘SZ IS SIZE AND D IS NO. OF DIGIT AFTER DECIMAL STRING ‘CHARISIZE) CHAR IS FIXED SIZED STRING AS PER SIZE DEFINED IN PARANTHESIS. SIZE OF CHAR DATATYPE IN RANGE OF 0 TO 255. BYDEFAULT SIZE OF CHAR IS 1 VARCHAR(SIZE) VARCHAR STANDS FOR VARIABLE LENGTH CHARACTER STRING RANGE OF VARCHAR IS 0 TO 65535 163 | Pace DATE AND DATE ‘AS THE NAME SUGGEST IT IS USED TO STORE TIME DATE IN ANY ATTRIBUTE SUPPORTED FORMAT : YYYY-MM-DD DATATYPE TIME USED TO STORE TIME IN ANY ATTRIBUTE SUPPORTED FORMAT : HH:MM:SS Keys In database, keys is column/attribute which is used to fetch/extract/retrieve row in a table. Or we can say that Keys are used to uniquely identify records in a table through column or combination of column. To extract any particular row/record from a table, we need a key attribute which contain unique values. aa fmp_I| /Name ‘Address fendel 1001 [eset Dati} 1002 [ee buat 1003 ||| Rohit |) [Paprawat 1004 ||| sunny | [Najafgarh 1005 || |_Ruby [| |Harinagar z|njgizig 7 1006 || | vinay |) [Nawada / healt] 5 DIAGRAM: S KEYS IN TABLE (PLEASE READ IN ORDER OF NUMBER) 164 | Pace Primary Key: Primary Key is a unique identifier which identify unique record in a particular table. It must contain unique values for each record. And Primary key attribute/column/field can’t be NULL. A table can have only ONE primary key Note: A Primary key must be a candidate key but not all candidate key are Primary key Candidate Key: Candidate key are those key which are el ina table. le for p ary key and can be used as p ary key Candidate key is a set of one or more column that could be used as primary key and from the set of these candidate key, one column is selected as primary key. From Diagram 5, Candidate key can have more than one attribute like Emp_ID, Name, and Address etc. Alternate Key: ‘After selecting primary key from candidate key, the remaining keys (which are also eligible for primary key) are called Alternate Key. Foreign Key: A Foreign key is a column or group of columns in a table that provides a link between two tables. Let’s see how actually foreign key work in table. Stu_ID Name | Gender Course_Name 1001 | Yamin Computer Science 1002_| Akshay Information Technology 1003 Sachin Mechanical 1004 | Prashant Civil 1005 | Rohit Electrical 1006 | Vinay DIAGRAM: 6 HoW FOREIGN KEY WORKS BETWEEN TWO TABLES Zeer z 0 165|Pape It is an attribute whose values can be derived from primary key of some other table. It ensure referential integrity. Referential Integrity is protocol which is used to ensure that relationship between record/row is valid and can’t change in related data. Structured Query Language: Introduction: ‘SQL is shortened of Structured Query Language. And it is pronounced as See-Quell. SQL is used to manage database. SQL was developed in 1970 in IBM Laboratory and it became a standard of the ANSI (American National Standard Institute) in 1986. SQL is query language not a database system. You are required to install DBMS software in your system to perform SQL Language operation with help to query Example - Oracle, MySQL, MongoDB, PostgreSQl, SAL Server, DB2 etc. SQL is mainly used for maintaining the data in relational database management system. SQL provide interaction between user and database via set of standard commands. In simple words, SQL is language that help user to communicate with databases. SQL is not case sensitive language means you can type your query in small or capital letter as per user. DIAGRAM: 7 How SGL PROVIDE INTERACTION BETWEEN USER AND DATABASE You may write comments in SQL using “--” (Double hyphen) User may get information from a database file from required query. Query is a request in the form of SQL command to retrieve information with some condition. You will see lots of query performing different type of operations. SQL is query language (Query based language) which works on structured data (data in structured form). Now let's discuss all the SQL Commands in categorized way. 166|Pape SQL (STRUCTURED QUERY LANGUAGE) COMMANDS os DIAGRAM: 8 SGL COMMANDS CAN BE CLASSIFIED INTO FOLLOWING CATEGORY SQL perform following operation: "Create a database "Create a table "Create view = Insert data * Update data * Delete data "Execute Query "Set Permission or Constraints in table SQL Commands: ‘SQL commands are predefined set of commands which are already defined in SQL. Commands are basically combination of keyword and statement you want to execute. Keywords are reserved words that has special meaning for SQL, you don’t need to define they are already defined in SQL. All you need to use these keywords with you particular statements. CLAUSE IN SQL: Clause: Clause are built in functions which is use to deal with data inside the table that help SQL to filter and analyses data quickly. 167|Pave Used to select or filter rows based on particular valid condition. ee ee Came UUs eae ee want to fetch/retrieve data. It is mainly used with SELECT Vee eC ea Ee ea CT ao bY can use DESC keyword to sort in descending order CLAUSE Cito cM CaN Peete tthe cea aes columns. It’s mainly used with aggregate functions. eT nero based on aggregate function applied to grouped columns Veter ae column. It uses wildcard (%,_) characters to match the strings Any SQL statements is composed of two or more clause. ‘These clause are used with your SQL statements to filter commands you may learn in detail in further section, Some mainly used clause are discussed below. NOTE: All SQL statements are terminated with (;) semicolon ‘SQL statements are not case sensitive means SQL treats both upper and lower case commands as same. 168 | Pace We are going to use these above clauses in our all types of commands in SQL. Few basic SQL Commands: Create database: To create a new database, create databases command is used. SQL Syntax: create database ; [Der Meee Wee ele ay Query OK, 1 row affected (0.00 sec) Show database: To view the list of available/created databases in SQL, show databases command is used. SQL Syntax: show databases; (eat Ca eerie) Pee Pte mee Pa Re a a) Use database: To select a database among available databases, use database command is used, SQL Syntax: use ; Inysql> use test Bela Lid To view the list of available/created databases in SQL, show tables command is used. SQL Syntax: show tables; 169 | Pace To Tables_in_test pire perro cess cree ery Poon pees PrUbe es eet sete Peat Create table: To create a new table in the selected database. For example, if | want to create a table Student with following attributes and data types: SQL Syntax: create table ( (size), (size) ... ); Name of attribute Data Type Student_1D. int Student_Name char(30) ‘Age int Phone int ‘Address varchar(50) [age ta- eee ona cae Meta Sere er gel Age int, Peas CES LDH Query OK, 0 rows affected (0.04 sec) Describe table: To view the structure of table (like attributes and its data types, keys, constraints, default values), desc command is used. SQL Syntax: desc
; OR describe
; 170| Pace Se mee tte iin NVI NUTR cNUTa va Insert command: To insert data in table, insert command is used (one row at a time). Here in this example, data of 4 students are inserted in table student. SQL Syntax: insert into
values (, , ...); erage CN Cree mao Cae erariaer ie PERO eae ga: Ct) Ord cP Kduery 0K, 1 row affected (0.08 sec) EC ORR eae Besa Oa aed oe Mr eee duery 0K, 1 row affected (0.11 sec) Select command: To show the data of a table, select command is used. Let’s show the data of 4 students in student table that was inserted in the previous command. SQL Syntax: select * from
; Chet eae 2 Ot al er Steen ected ures oo feel ee ws in set (0.86 sec) Drop table command To delete data as well as structure of a table, drop command is used SQL Syntax: drop table
; 171| Pace eee oor equil etsy Seren Ete ca Temes Drop database command: To delete a database along with all the tables present in the database, drop command is used. SQL Syntax: drop database ; Der Mer Cory Database chanc house i u - a row in set (0.00 sec) imysq1> drop database home; , 1 row affected (0.03 sec) Constraints in SQL are set of rules that are applied to the data in a relation/table. Constraints are used to ensure the accuracy and reliability of the data. Constraints can be at column level or at table level. Column level constraints apply to a column, and table level constraints apply to the whole table. After applying constraints to the table, if any violation happens then the data can’t be inserted or action can’t be completed. Types of constraints: Primary key Unique Not Null Foreign Key PeNE 172| Page Let's uss in Details: 1. Primary Key Constraints: NOT NULL+UNIQUE=Primary Key This key applies unique and not null constraint to the column. This constraints ensure that each column/attribute of table contain unique value for each row. Let's learn with the help of example: First we have created a table named student_demo and applying primary key constraints on roll_no attribute. SQL Syntax: create table { ); Command: create table student_demo(roll_no int(10) primary keyname_ varchar(20), subject varchar(20)); (1S create able) etudent“denaCroT1 no 1sECLO) priwary Kay,nabe varchar(20) subject varchar (2009) Wiery Ok, 0 rows affected (0-03 sec) ae 4 i Praline | ineG0) | so (Par | wat 1 frame" | varchar@20) | Yes Nut | | Subject | Yarenarc20) {Yes | 1 NAL 1 rows i Set (0.02 sec) 2. Unique Constraints : NULL VALUES or (NOT NULL VALUES+UNIQUE) =UNIQUE Unique constraint make sure that all values present or inserted in a column are different. And this constraints follows all property of primary key constraints except that Primary key can’t contain NULL values but unique constraints allows NULL values. It ensures that values in the column are unique across all rows. NOTE: You can have more than one unique key but only one primary key ‘SQL Syntax: alter table add (); Command: alter table student add unique(standard); mysql> alter table student add unique (standard) ; Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0 Let's see table schema after applying above code: 173 | Pace ‘As you can see Unique Key constraints assigned to attribute/Field named standard. Which means standard column hold unique value. Now as we know standard attribute can only hold unique value. If we attempt to insert duplicate values in standard attribute. This may occur an error. Let's see how Now we are going to enter a valid entry in student table. Let’s see As you can see all entry are clearly affected in table student. Now we need to check that standard attribute allows NULL values. Let’s understand with SQL command. 174|Pace 3. NOT NULL Constraints : Which never accept NULL values NOT NULL constraints ensures that columns in table does not contain any NULL values. NULL values means missing or unknown values. If you enforce this NOT NULL constraints to any attribute than you are not able to insert any NULL values in it. Let’s see how. In student table, only two attribute assigned with NOT NULL constraint, first one is roll_no and std_name which means that these column can’t accept NULL values Now we enforce NOT NULL constraint to another column named subject in existing table student. ‘As you can command is successfully executed, Let’s see the schema of the table to check NOT NULL constraint successfully applied on subject column. In below diagram it is clearly shows that subject NULL Type is set to NO means you can’t insert NULL value. ‘After that we have to check by insert a command with NULL values whether the subject column is accepting NULL value or not. Let’s see 175 |Pave mysql> dese student; + + = | Default | Extra | * =o-4 = | roll_no | int@1y [no | [nue | i | std_name | varchar(50) | NO | PRE | | I | standard | varchar(20) | Yes | UNE | NULL | ! | subject | varchar(30) | no | [nu | \ J gender | char (1) les | Im | | + + + 5 rows in set (0.02 sec) mysql> insert into student values (11, "anaaya","1st_A”,NULL,"F"); ERROR 1048 (23000): Column *subject’ cannot be null As you can there is error occur that column ‘subject’ cannot be null Now we try to insert a another command in the student table and check whether the insertion is successful or not wysql> insert into student values (11, "anaaya","8th A”,"AT","—"); Query ok, 1 row affected (0.01 sec) mysql> select * from student; | rell_no | std_name | standard | subject | gender | 1 11 | Anaaya | 8thA | AL le 1 1 4 | Anuj | NULL | c# iM 1 1 4 | Gaurav | lithB | Java iM I | 2 | Mohit | 11th A | Informatics Practices | M 1 1 1 | Rohit | tithe | data structure iu 1 1 3 | sarika | 10th A | Information Technologies | F 1 I 4 | Vinay | the | CH Pau | 7 rows in set (0.00 sec) 4. Foreign Key: In Foreign Key constraints, unique, not null and primary key constraint applies to a single table where as foreign key constraint applies to two tables. For example: we have two tables’ student and awards as follows: Table: Student Table: Awards ID Name | Age | City ID Award Sport 1__[amit__|15_| Delhi 1 Gold Badminton 2 Madhu [14 | Gurugram | | > Sliver Tennis 3 Manoj | 15 Noida 4 [Asif [15 | Faridabad || + Silver Hockey 4 Bronze Badminton Here we will establish foreign key constraint on column ID of student table and column id of awards table. Here we will consider Student table as parent table and Awards table as child table. Following rules must be followed: 176 | Pace (a) Column ID of Student table must be its primary key. (b) Column ID of Awards table may or may not be primary key of Awards table. ‘© Foreign key constraint ensures that only that data can be inserted in column ID of ‘Awards table which is present in column ID of Student table. Example: We will create two tables. Student table as parent table and Awards table as child table. Now we will establish foreign key constraint on column ID of student table and column id of awards table. mysql>? create table Student(ID int primary key, -> Name char(2@),Class char(2@) Phone int 3} Query OK, @ rows affected (0.12 sec mysql> create table Awards(ID int,Event char(2Q), I -> foreign key(ID) references Student (1D)); Query OK, @ rows affected (@.16 sec) Now let’s check how foreign key constraint works. We have already added data in Student table. mysql> select * from Student; t-- ato | ID | Name Rahul Zz Mahima Gauri Mohan | + Io2 | t-- ot 4 rows in set (0.00 sec) Now let’s check how foreign key constraint enforces referential integrity. Press greats Rey BNerehcrentes SredenE UE5SS? lauery OK°"S Bows bivecten {Or3E sec) mysql> insert into Awards values(1, cricket"); Ruery 0k; i row affected (B06 sec! mysql> insert into Awards values(2,*football"); Query OK, 1 row affected (0.09 sec) myzgl> insert snto Awards values (5, "khokho" ); ERRGe” 1452" (29000); Cannot add or Update's child row: a foreign key constraint Fails Saibfkai® FOREIGN KEY" ¢°Tb'S REFERENCES. ‘student © ¢'1D")) Here we can see that ID 5 is not present in parent table (Student). So, ID 5 can’t be added in child table (Awards). DDL (Data Definition Language) Command: These commands are used to make any changes in the structure of the table/database. These command don’t change the data of the table. Example: create table, alter table, drop table, create database, create view etc. 4771) P. We have already covered few DDL Commands like create database, create table, drop database, drop table. Few more DDL commands like alter table will be discussed now. Alter Table: This is a DDL command and it is used to modify a table. This command can be used to add, delete, or modify columns, add or drop constraints ete. SQL Syntax: alter table
[alter option); Add a column to the table: We have table student which was created in previous section ear era ets str) SQL Syntax: alter table
add [constraint]; Example: If we want to add a column class with data type varchar and size 0 and nulls are not allowed. ee ee comer eee e ee Ceasers Desi Tee iu ast Poe e Reg Fer Drop a column from the table: Let’s delete a column class from table student which we added in the previous section. SQL Syntax: alter table
drop column; 178| Pace ysql> alter table student drop column class; OO ear aera ig gts Se Dryer ) LOM Co Sede ues a (steerer er ats EEC eo 8769876 Ea) em Wk} rte ery ui errata rows in set (0. Modifying column of a table: we have different ways to modify a table like column name, data type, default value, size, order of column, constraints. 1. Changing column name: We can change the column name of a table using alter command. For example, in table student, we are going to change column name Student_ID to ID. SQL Syntax: alter table
change column ; mysql> alter table student change column Student_ID ID int; Query OK, @ rows affected (@. 14 sec) Records:'@ Duplicates: @ Warnings: @ mysql> select x from student; gurusram jaipur 76 | noida 4 rows in set (8,00 sec) Changing column data type: We can change the column data type from varchar to char or int to varchar etc. of a table using alter command. For example, in table student, we are going to change datatype of column ID from int to varchar. SQL Syntax: alter table
change column ; mysql> desc student i Type i Null | Key | Default | Extra | iGo Tinea] 7 ai i 1 Sraaent Ware | toot ' | I i tot i | | Bhgne | | | | i i | Addr | i it \ i S rows in set (8.00 sec) mysql> alter table student modify column ID varchar(5@); Query’ OK, 4 rows affected (8.48 sec) Records!’ 4 Duplicates: @ Warnings: @ 179| Page mysql> alter table student modify column ID varchar(52); Query’ OK, 4 rows affected (0.48 sec) Records:’4 Duplicates: @ Warnings: @ mysql> desc student; a ee | Type char tag 1 Intcity I int (11) I hi S rows in set (@.@1 sec) 3. Changing maximum size of the data in a column: We can change the maximum size of the data in a column of a table using alter command. For example, in table student, we are going to change size of column ID from varchar(50) to varchar(40). SQL Syntax: alter table
change column ; chartae int (qd) int Ct) varchar(SQ) mysql> alter table student modify column ID varchar(4@); Query OK, 4 rows affected (4.31 sec) Records:'4 Duplicates: @ Warnings: @ varchar (40) char intcd) int(1L) 4. Changing order of the column: We can change the order of the column of a table using alter command. For example, in table student, we are going to place column ID after column Age. SQL Syntax: alter table
modify [first after ]; 180 | Pace nysql> select © from studen Student_Name | Age 98769876 88769876 | 68769876 Query OK, 4 rows affected (0.23 se Records: 4 Duplicates: @ Warning I | Amit { 17 fa] | 98769876 | delhi { Sonam, 1 161 | 88769876 | gurugram | | Mahesh 1 a7t | 68769876 | jaipur | riya | 18 114] | 78769876 | noida | 4 rows in set (@.@0 sec) Now we are going to put column ID back to first position. mysql> select x from student mit, Sonam | 88769876 | gurugram Mahesh | 68769876 | jaipur | Priya | 78769876 | noida 4 rows in set (0.00 sec) mysql> alter table student modify ID varchar(4@) first; Query’ OK, 4 rows affected (8.27 sec) Records:'4° Duplicates: @ Harnings: @ mysql? select * from student I] ID] | Student_Name | Age | Phone | Address | a 1 Amit | 17 | 98769876 | delhi 1 2] | Sonam, | 18 | 88769876 | gurugram | 1]3 | | Mahesh | 17 | 68769876 | jaipur | 14} 1 Priya | 18 | 78769876 | noida I 4 rows in set (0.80 sec) |. Add/drop constraints/column: We can add/drop constraints in a table using alter command. > Adding primary key: We are going to add primary key at column ID using alter command Command: alter table
add primary key(); 181| Pace v aysql> alter table student add primary key(ID); Ruery OK, 4 rows affected (0.51 sec) Records:'4 Duplicates: @ Warnings: O nysql> desc student; I Field | Type TNull | Key | Default | Extra | t i har(40) | ifPRI]i i i ! Seudent Name | char(3a) | YES {Leet} NULL | | ' | intcaiy 1 Yes | 1 NUCC i | Beene | intra) | YES | 1 NuCr | | Address |_varchar(S9) | YES I I NUCL I 5 rows in set (0.16 sec) Dropping primary key: We are going to remove primary key at column ID which we added in the previous section, Command: alter table
drop primary key; sql gltgr table student degp primary keyi Bier ofa" Sue sefected' (B38 ScetorY Kev eeotdet'a® Boplicates:°8 Harhines: @ ysql> desc student j Extra | rows in set (0.00 sec) Adding a new column: We are going to add a column country with data type char of size 50 to the table student using alter command Command: alter table
add column ; mysql> alter table student add column country char(S@); Query OK, 4 rows affected (0.27 sec) Records:'4 Duplicates: @ Warnings: @ mysql> desc student 1 Field | Type T Null | Key | Default I Extra | 1 | varchar(4a) | NO. | i 1 i 1 Student _Nane | char(3a) | YES | PUL} i 1 1 intCiip 1 YES | FNULE | | BRS. | int(i1) 1 YES | FNUEE i | Address | Varchar(so) | YES | FNUEE | | country I char(Se) | YES | I Nuc i 6 rows in set (0.01 sec) Dropping a column: We are going to remove a column ‘country’ which we added in the last section using alter command. Command: alter table
drop column ; 182| Pave mysql> alter table student drop column country; Query OK, 4 rows affected (9.31 sec) Records:'4 Duplicates: @ Warnings: @ | Field I Type UNull | Key | Default | Extra | i i No. | i 1 1 1 I! 30. t i PMULL 1 | Age 1 Ent (1d) ives | PNUCL 1 | PRone | int (1) | YES | PMuce 1 | Address t I I 1 1 S rows in set (0.01 sec) DML (Data Manipulation Language) Commands: These commands are used to make any changes in the data of the table. DML commands: insert, delete, update, select etc. We have already covered few DML Commands like insert and select. Now we will discuss delete and update command. Delete comman Delete command is used to delete data from the table. Where clause is used to give condition ina SQL query. All those tuples which satisfies the condition will be deleted from the table. SQL Syntax: delete from
where ; Now let's delete data of all those students from student table whose ID is greater than 5. 98769876 88769876 68769876 98769875 rows in set (0.00 sec) mysql> delete from student where ID?5; Query OK, 2 rows affected (@.13 sec) mysql> select ® from student; | ID | Student_Name | Age | Phone | Address | 2 1 Amit | 47 | 98769876 | delhi i 12 | Sonam | 18 | 88769876 | gurusram | 13 | Mahesh | 17 | 68769876 | jaipur | 14 | Priya | 18 | 78769876 | noida i 15 1 Monika | 17 | 98769876 | delhi 1 S rows in set (0.08 sec) 183 | Pace Update command: Update command is used to update data from the table. Where clause is used to give condition in a SQL query. All those tuples which satisfies the condition will be update from the table. SQL Syntax: update
set = where ; Now let’s update the Address from ‘Delhi to ‘Sonipat’ of that student whose name is ‘Amit’. mysql> select * from student; + | + | | 98769876 | | ! 16 | 88769876 | gurugram | 1 17 | 68769876 | jaipur 1 1 18 | 78769876 | noida 1 | 98769876 | delh 1 mysql> update student set Address=’Sonipat’ where Student_Name=’ Amit’; Query’ 0K, 1 row affected (9.09 sec) Rows matched: 1 Changed: 1° Warnings: @ 98769876 Aliasing: Aliasing in SQL is the process of assigning a nick name or a temporary name to a table or column. We create aliases to make queries more readable and easier to use. Alias created using as keyword. Creating aliases don’t change name of any table or column permanently. Imysql> select * from student j ! ! | 98769876 | Sonipat | | Sonam, ! 16 | 88769876 | gurugram | | Mahesh | 17 | 68769876 | jaipur | ! i ! 18 | 78769876 | noida | | 17 | 98769876 | delhi | | + 184) Pa ID, Student_Name as Name from student; + | 1 1 1 1 | + ¢ 5 rows in set (@.06 sec) Distinct clause: Distinct clause is used to remove duplicate values from the table. As we studied earlier, changes in data of a table is done using delete and update command, So, removing duplicate values using distinct clause is temporary and only reflected during output. Distinct clause can be used for more than one column \nysal> select * from student + I I | Phone | Address | e-2--+ Se genes cett iy 14 1 Amit | 17 | 98769876 | Sonipat | 12 1 Sonam | 16 | 88769876 | gurugram | 13> | Mahesh | 17 | 68769876 | jaipur | 14 | Priya | 18 | 78769876 | noida | 15 | Monika | 17 | 98769876 | delhi | 12 | Ajay | 17 | 98769857 | jaipur | 13 | sona | 18 | 94769857 | noida I b-=--4--- nan tenet oe 7 rows in set (8.00 sec) Here in student table, two duplicate ID's 1 and 3 are present. Now using distinct clause we can get only unique values. mysql> select distinct (ID) from student; te on + 1 Il [a | 12 | 13 | 14 1 1s t bene 4 (5 rows in set (0.0 sec) ‘As we can see that all duplicate ID's are removed but it is temporary. Duplicate values are not removed and still present in the table. 185 | Pace Where clause: ‘The WHERE clause in SQLis used to filter the results of a SELECT statement by specifying one or more conditions. All those tuples which meets the condition will be included in the final result. ‘The WHERE clause is a very powerful technique to select particular rows from a table. It can be used to filter by the values in a column, by the values in multiple columns, or by the outcome of any calculation Uses of where clause: ‘© Where clause can be used with select statement to filter the result. ‘+ Where clause can be used with update statement to update the data of table that matches with the condition ‘* Where clause can be used with delete statement to delete the rows of table that matches with the condition. SQL Syntax: where select * from student; t---- = aattnne + oe | ID | Student. —Neme | Age | Phone | Address | + a= =o- + manent 12 1 Amit ! 17 | 98769876 | Sonipat | 12 | Sonam ! 16 | 88769876 | gurugram | 13 | Mahesh ! 17 | 68769876 | jaipur ! 14 | Priya ! 18 | 78769876 | noida ! 1S | Monika ! 17 | 98769876 | delhi ! 12 | Ajay ! 17 | 98769857 | jaipur ! 13 sonal | 18 | 94769857 | noida | 4 SSeS eae fa + [7 rows in set (0.00 sec) mysql> select * from student where age<=17 eee Songeee + | 1D | Student_Name | Age | Phone | I * =e oe SHE + | | Ami | 17 | 98769876 | Sonipat | 12 | Sonam | 16 | 88769876 | gurugram | 13 | Mahesh | 47 | 68769876 | jaipur | 15 | Monika | 47 | Sa7ega7e | delhi | Ii 1 Ajay | 17 | 98769857 | jaipur | * ese cae ot + S rows in set (8.05 sec) 186 | P 2. To filter the result based on multiple condition: Inysql> select © from student where age<=17 and Address=' jaipur’; ne + + | Address | + | 3 | Mahesh | 17 | 68769876 | jaipur ; + + | ID | Student_Name | Age | Phone 11 | Ajay | 17 | 98769857 | jaipur t-==-+- ate (2 rows in set (8.06 sec) In clause and not in claus clause is used to filter the rows in output based on list of values, In sql, in clause and not Syntax for in clause: where in (item, item2,...); ‘Syntax for not in clause: where not in (item4, item2,. Example of in clause: if we want to find the data of those students who lives in either delhi or fer we write multiple Jaipur or gurugram. Now to solve this problem, we have two ways. comparison using or keyword or we can use in clause. Now you will see that using in clause for comparing with a list of items is an easy option, * on Addres: jaipur? or Addres: 8769876 88769876 5769876, 98769857 in set (0.00 sec) Thi! Jaipur’ ,"aurusram"); jaipor aethy i Example of not in clause: if we want to find the data of those students who don’t lives in delhi or Jaipur or gurugram. t_in Cdelhi’,’ Jaipur’, ’gurugram’ ); Address | Sonipat noida Reida i Leong? Tows in set (6.02 sec) 187| Pace Between Clause: It is used to filter the rows in output based on the range of values. SQL Syntax: where between and ; Note: The final result of between clause filters the rows of the table based on range of values including starting and ending value. mysql> select from student where age between 17 and 18; i101 Address | = “+ fal i Sonipat | 131 | jaipur | 141 | 78769876 | noida | 1s | | 98769876 | delhi | lit | 98769857 | jaipur | 131 | 94769857 da | [6 rows in set (2,05 sec) Order by Clause: It is used to sort the output of the select statement in ascending or descending order. SQL Syntax: order by [ASC| DESC]; Note: If not mentioned, by default it will sort the output in ascending order. So, if you want to sort the data in ascending order, you need not to mention the order of sorting. mysql> select * from student order by Student_Name; cope Tip T Student Name 1 Age | Phone | Address | M. . ry Taj 137 1 98769867 | jaipur] 11 ot Ami: 1 17 | 98769876 | en Bat I | 3 | Mahesh | £2 | ée7edaze | an i 15 | Wontka | 17 | 38768876 | de. ther i la | Beye | 18 | 78769876 | noida | 13 | sonal | 18 | 9479857 | noida | 12 1 Sonam | 16 | 88769876 | Surusram | 7 rows in set (0.00 sec) 188 | Pace mysql> select * from student order by Seaene —Name ASC; 12 | Ajay | iz 1 376985 | jaipur | 12 | Amit | 17 | 98769876 | Sonipat | 13 | Mahes | 17 | 68769876 | jaipur 1 1S | Monika | 17 | 98769876 | deihi 1 14 | Priya | 18 | 78769876 | noida 1 13 | sonal | 18 | 94769857 | noida 1 12 | Sonam | i6 | 88769876 | gurugram | + 7 rows in set (0.00 sec) mysql> select from student order by Student_Name DESC; + + | ID | Student_Name | Age | Phone i Address 7 tenant + + | 2 | Sonem | 16 | 88769876 | gurugram | | 3 1 sonal 1 18 | 94769857 | noida | 14 | Priya | 18 | 78769876 | noida | |S | Monika | 17 | 98769876 | delhi 1 | 3 | Mahesh | 17 | 68769876 | jaipur | 1 tot Amit 1 17 | 28769876 | Sonipat | !iot _Aley | 17 | 98769857 | jaipur | + + em 7 rows in set (0.00 sec) We can sort multiple columns together in ASC and DESC order. mysql> select = from student order by Address DESC,Student_Name ASC; noida jaipur jaipur guyugren NULL: In SQL, nullis a special value which means absence of value or a field doesn’t has a value. Null doesn’t mean zero, Null also doesn’t mean empty string, Null is a kind of placeholder of that value which is not present or not known. Example: If the phone number of a student is not known at present, so we can store NULL instead of zero or make it empty. 189 | Pace mysql> insert into student values (6s "Tanya’,16,NULL, "delhi" ); Query OK, 1 row affected (0.09 sec) 1 + 98769876 | Sonipat | 88769876 | gurugram | 68769876 | jaipur | 78769876 | noida I 98769876 | delhi I 98769857 | jaipur | 94769857 | noida I ILL | delhi 1 Si ee + rows in set (0.2 sec) IS NULL Clause: IS NULL clause is used to check that value in particular column is NULL value Example: To find out name of students whose phone number is NULL. mysql> select * f rom student where Phone is null; t-———+ | IDI leon: 1 row in set (8,02 sec) Note: is keyword is used to compare values of a column with NULL. IS NOT NULL Clause: IS NULL clause is used to check that value in particular column is not NULL value Example: To find out name of students whose phone number is not NULL. mysql> select * from student where Phone is not null; + I tat 98769876 | Sonipat | 12 1 Sonam 88769876 | gurugram | 13 | Mahesh 68769876 | jaipur | 14 | Priya 78769876 | noida 1 1S | Monika 98769876 | delhi | 12 | Ajay 98769857 | jaipur | 13 1 sonal 94769857 | noida I 7 rows in set Like operator: Like operator is used to match a pattern. The like operator is used with were clause. Like operator has 2 wildcards: 1. _ (underscore): It is used to match one character. 190 | Pace 2. % (percentage sign): It is used to match zero or more characters. Example 1: To match a string that starts with ‘sits pattern will be ‘s%’. As we don’t know how many characters are there after ‘s’, so ‘9’ sign is used after ‘s’ ike 's%5 i 1 1 meen 769876 | gurugram (769857 | noida sonal ee an! 2 rows in set (0.00 sec) Example 2: To match a string that ends with ‘a’, its pattern will be "%a’. As we don’t know how many characters are there before ‘a’, so 6’ sign is used before ‘a’ ysal> select * from student where Student_Name like *Z%a’; | Address 4 rows in set (0.00 sec) Example 3: To match a string that contains with ‘a, its pattern will be ‘%a%’. As we don’t know how many characters are there before or after ‘a’, so ‘%6’ sign is used before and after ‘a’. x a fan"; Sonipat gurugram jaipur noida delhi jaipur Roida delhi OHLONE rows in set (0.00 sec) Example 4: To match a string that has letter ‘a’ at second position, its pattern will be “_a%’. As we know there must be exact one character before ‘a’ and we don’t know how many characters are there after ‘a’, so ‘_’ sign is used before ‘a’ and ‘%’ sign is used after ‘a mysql> select * from student where Student_Name like ’_az’; hots Hea ee ene le ==-+ ID | Student_Name | Age | Phone | Address | + | Mahesh \ a7 | 68769876 | jatpur | 2 rows in se sec 191] Pace Example 5: To match a string that has exactly 5 character, its pattern will be ‘ know there must be exact § character, so ‘_’ sign is used 5 times. _ LAs we I + = + {4 | Priya | 18 | 78769876 | noida | 1S | Monika | 17 | 98769876 | delhi | 13 | sonal 1 18 | 94769857 | noida 1 16 | Tanya | 16 1 NULL | delhi I + 4 rows in set (@.0@ sec) Example 6: To match a string that has exactly 7 character and ends with ‘t’ its pattern will be _t. As we know there must be exact 7 character, so ‘_’ sign is used 6 times before mysal> select * from student where Adress like ’ at's _ | ID 1 Student _Name | Age y Phone i Address | 11 1 Amit 117 | 98769876 | Sonipat_| aot ei 1 row in set (0.00 sec) Update Command: It is used to update the existing data in a table. SQL Syntax: update
set = where ; Example 1: Let’s update the Age to 18 of that student whose name is Amit. mysal> select * from student aot + + | ID | Student_Nane | Age I I i pana + + 1 tLAmit 17]! | Sonipat | 12 | Sonam ! | gurugram | 1 3 | Mahesh ! i7 | | jaipur | 14 | Priya | 1g | | noida | 1o t heat ka 1 i7l | delhi | 12 | Ajay | 17 | | jaipur | 13 | sonal | 18 1 | hoida | 16 1, I 161 | delhi | == + & rows in set (0.08 sec) 192 | Pave mysql> update student set Age=18 where Student_Name="Amit'; Query OK, 1 row affected (8.09 sec) Rows matched: 1 Changed: 1 Warnings: @ Sonipat gurugran jaipur noida delhi jaipur noida Example 2: Let’s update the city to delhi of that student whose ID is 1 and Age is 17. mysql> select x from student; Student _Name | Age |_Phone in set (@.01 sec) pysal> update student, set Address=\delhi’ where ID=1 and Age=17; Query OK, 1 row affected (0.11 51 Reoermctohen! “Unenocns 1 Wersitom: @ mysql> select * from student Amit Sonam, Mahesh gurugram jaipur Roida B rows in set (2.00 sec) Delete Command: It is used to delete the existing rows in a table that matches the condition. ‘SQL Syntax: delete from
where ; 193 | Pace Example 1: Let’s delete data of those students whose ID is 1 but age is not 18, geceze ee | Sonipat | gurugram | jaipur | noida 78769876 8 rows in set (0.00 Sec) mysql> delete from student where ID=1 and Age!=18; Query OK, 1 row affected (0.11 sec) mysql> select * from student + + ¥ | ID 1 Student_Name | Age | Phone | Address I acceapel coceceseeees ee cceee yen ccoeuees geneeeeenee 1a | Amit | 18 | 98769876 | Sonipat | 12 1 Sonam | 46 | 88769876 | gurugram | 13 | Mahesh | 47 | 68769876 | jaipur | 14 | Priya | 18 | 78769876 | noida | 15 | Monika | 47 | 98769876 | delhi | 13 1 sonal | 4B | 94769857 | noida | 16 | Tanya tel | delhi | catnip em asearareanegionn mea eesnges aces seenercsnes ¥ Frows in set (@.00 sec) Example 2: Let’s delete all data of student table. For doing those, we needs to give a condition that matches with all the records. As ID’s are greater than 0, so let’s delete all those records where ID is greater than 0. 194 | Pace mysql> select * from student} + Sonipat | gurugram | jaipur ! noida | delhi ! noida | 94769857 po tt sec. mysql> delete from student where ape Query OK, 7 rows affected (@.11 sec) mysql> select _* from student; Empty set (0.00 sec Aggregate Functions: ‘Aggregate functions are those functions that operates on a list of values and returns a single digit value or we can summarize the data using aggregate functions. 1, Max(): It is used to find out the maximum value from a column. it . | | 98769876 | Sonipat | | 88769876 | Gurugram | | 7698" | Jaipur 1 | 78769876 | Noida 1 | 769876 | Delhi | | 765876 | Noida | | 28765876 | Delhi 1 He ee ence nn Hes en en enne + + in set (0.00 eed select max(ID) from student; + i+ 1 row in wee (0.89 sec) 2. Min(): It is used to find out the minimum value from a column 195 | Pace mysql> select min(ID) from student; aonnt 1 row in set (8,00 sec) . Ave(); Itis used to find out the average value from a column. \nysql> select avg(Age) from student; + <-+ | avgCAge) | sumi(): It is used to find out the sum of all values of a column. mysql> select sum(Age) from student; sum(Age) 1 row in set (@.02 sec) Count: it is used to count number of values in a column, inysql> select count(ID) from student; +-- =+ | count (ID) | t+ in 1 row in set (@.00 sec) Note: Distinct keyword can be used with aggregate functions to find out max, min, sum, avg, count of only unique values. Example: Let's find out total number of cities from where student came for study. Here more than one student is from same city. So we needs to use distinct keyword along with count function. 196 | Pace lmysql> select x from student; feecese + | ID | Student Name | Age | Phone | Address | teoan4-= 4-2 2o__ + aoa 4 11 | Amit | 18 | 98769876 | Sonipat | 12 | Sonam 1 16 | 88769876 | Gurugram | 13 | Mahesh | 17 | 68769876 | Jaipur | 14 1 Priya ! 18 | 78769876 | Noida 1 15 | Monika | 17 | 98769876 | Delhi | 16 | Raman 1 18 | 98765876 | Noida 1 17 | Pawan 19 | 28765876 | Delhi | baa--4 Seneeeecee= ene 7 rows inysal> count (distinct (Address)) from student; 1 row in set (8.00 sec) Group by clause: ‘The GROUP BY clause is used to group rows that have the same values into summary rows. Group by clause is often used with aggregate functions like MAX(), MIN(), SUM(), AVG() and COUNT() to group the result by one or more columns, ‘* It canbe used with or without where clause in select statement. * Itis applied only on numeric values. ‘+ It can’t be applied with distinct keyword, SQL Syntax: group by Example 1: select © from studen’ onan I 6 Mahesh { 7 riya 1 18 Monika 1 a7 Raman. I 18 in set (0.05 sec) Let’s count number of students having same age in student table. 1 98769876 | Sonipat | 88769876 | Gurugram | 68769876 | Jaipur | 78769876 | Noida I 98769876 | Delhi I! 98765876 | Noida I 28765876 | i I 197 | Pa mysal> select Age.count (ID) as Students_Count from student group by As aliasing Example 2: Let's city wise find out the minimum value of ID. fnysal? select Address, min(ID) from student group by Address: rows in set (8.00 sec) Having clause: It is used to filter the result set of group by clause in select statement. Note: To filter the result set of group by clause, only having clause can be used whereas for all other queries where clause is used. Inysal> select count (ID) es No_of_student,Age From student group by Age having Age=18; irom in set (0,60 sec) Joins: Joins are used to combine rows from multiple tables. Types of joins: 1. Cartesian product (Cross Join It gives all possible combinations from more than one table. It combines every row from one table with every row from another table. Suppose we have 5 rows in first table and 4 rows in second table then the total number of rows in Cartesian product of these two tables will be 20 rows. Cardinality of final table of Cartesian product = cardinality of first table * cardinality of second table Example: we have two tables’ student and awards. Let’s apply Cartesian product on these two tables. 198 | Pa 98769876 | Sonipat Sonipat Sonipat Sonipat Gurugram Gurusram Gurusram Gurugram Jaipur Jaipur Jaipur Jaipur Noida Noida Noida Noida ARADO OOUITIUIU DE. S ROWOWNNNNEEEE WNNEONNEWNNEWNNEWNNEWNNEUNNE: 28765876 28 rous in set (8.08 sec) Equi join: It joins the tables based on one common column. However, final result will consists of common column from both the tables. Example: we have two tables’ student and awards. Let’s apply equi join on these two tables. juysal> select * from student. awards where student. 1 iD T Student Name | Age i 1 it 1 Amit i 18 | 98769676 | Sonipat 1 11 gold | 12 | Sonam I 16 | 88769876 | Gurugram | 2t Bechee I 12 | Sonam, I 16 | 88769876 | Gurugram | 21 silver | | 3 | Mahesh | 17 | e87e9e7e | Jaipur | | bronze | Here both the tables has common column ID. So, to avoid ambiguity (confusion), we needs to mention table name before column name Fey sshtblb tect fren ptusgrt jstergs where, student. IDsavards 105 eal tudent .1D,Student_Nane from student awards where student. [O=awards 1D; | Sonsm 21 RAS, raat eet REED ech 199 | Pa 3. Natural J It joins the tables based on one common column. However, final result will consists of common column only once. Example: we have two tables’ student and awards. Let’s apply natural join on these two tables. mysql> select * from student natural join awards; i i Hy 1d 1 Amit 14g 1” 99769876 | Sonipat 1 gold | 2 | Soham | 18 | 887¢9858 | dcrusram | Bronze 1% | Sonam | 18 | 887¢9858 | doruaram | sliver 13 | Rakesh | 19 | 6876986 | Jaipur” | Bronze Lae ah 4 rows in set (0,00 sec) Here both the tables has common column ID. But there is no ambiguity arises on name of common column. $d Imysql> select ID,Student_Name from student natural join awards; 3 | Mahesh I @ rows in set (0.00 sec) Python and MySQL Interface In real life scenario, user interact with applications whereas data is stored in database. We have already developed python applications and database tables. Now, we will connect python application and MySQl database. Steps for creating python and MySQL connectivity application: 1, _ Import mysql.connector 2. Create a connection =mysql.connector.connect (host="localhost”, user=, passwd= , database =) Username = To know the user name, run select user(); command on your MySQL. 200 | P mysql> select user(); 1 + -+ 1 ODBC@localhost | 1 row in set (0.20 sec) Password: It should be same as we set during MySQL installation Example: Let’s create a connection of python with MySQL and test it. Python Code: import mysql-connector con=nysql . connector .connect (host="1ocalhos con.is connected () = print ("connect ior ‘OvBCBLocalhost” rest") on Failure") print ("connec Output: Connection Success >>> | Here in above example, | had not set any database password, so, passwd option is not mentioned in connection string. Is_connected() function checks whether connection string is able to connect python with MySQL. If connection string is able to make connect python and MySQL, is_connected() returns True otherwise False. 3. Create a cursor Cursor: It is a pointer or iterator which points towards the resultset of the SQL query. Whenever a SQL query runs, It give the entire result set in one go. We may not require the entire resultset at once. So, a cursor is created and data from the entire resultset will be fetched row by row as per our requirement. Syntax: = .cursor() 4. Execute query Syntax: . execute() 5. Extract data from result set ‘As we know that, Data from database is retrieved using select query. After running the select query, we get the resultset. Now to fetch the data from resultset, following functions are used a) fetchall(): It returns all the records from resultset. Each individual record will be in the form of a tuple whereas the entire resultset will be in the form of alist. Syntax: =fetchall() 201| Pave b) °) import mysql.connector as mys fnys is alias of mysgl.connector con=nys. connect (host ‘ODBCLocal host", database="test") ocalost" user ‘on.cursor() #cteating cursor elect * from student” #SQL query becur-execute (a) #executing SQL query ‘a' with cursor ‘curt crcur.fetchall() #retrioving the ontire dataset from cursor using fetchall () print (c) #priting the fetched dataset con.close() fclosing the connection - RESTART: C:/Usere/sWY/connec.py [(1t, ‘anitt, 18, 98769876, ‘Sonipat'), ('2", ‘Sonam’, 16, 98765676, *Gurugrant }, (3, Mahesh", 17, 68769876, ‘Jaipur'), ("4", ‘priya', 18, 70769076, ‘Noida’ "Monika", 17, 98769876, "Delhi'), ("6", | 'Raman‘, 18, 98765876, 'Noida') ‘pawan', i9, 26765076, ‘Delhi)) fetchone():It returns one row from resultset in the form of a tuple. It returns None, if no more records are there. To get multiple rows, we needs to run fetchone() multiple times. Syntax: =.fetchone() import mysql.connector a5 mys gays is alias of mysgl.connector con-mys.connect (host="1ocalhost" user="0DBClocalhost™,database="test") curscon.cursor() creating cursor elect * from student” #SQb query Decur-execute (a) #executing SOL query ‘a’ with cursor ‘curt cur. fetchone() #retrieving the one record using fetchone() print {e) #priting the retched dataset con.close() #closing the connection RESTART: C:/Users/SNY/connec.py C1", ‘amit', 18, 98769876, 'sonipat") >| fetchmany():it returns n number of records from resultset in the form of a list where each individual record is in the form of a tuple. It returns empty tuple, if no more records are there. ‘Syntax: .fetchmany(n) Python Code: import mysql.connector a5 mys gays is alias of mysgl.connector con-mys.connect (host="1ocalhost" user="0DBClocalhost™,database="test") on-cursor() #creating cursor elect * from student” #SQb query Decur-execute (a) #executing SOL query ‘a’ with cursor ‘curt c=cur.fetchmany(5) #retrieving the five records using fetchmany() ‘d-cur-roweount #to count the nusber of rows In resultset print (c) #priting the fetched dataset print ("Number of rows in resuitset is = *,d) fon.close() closing the connection 202 | Pave Output : ~ RESTART: C: /Users/SHY/ Py T(t, ‘Amie, 18, 98769976, 'Sonipat'), ("2', 'Sonam', 16, 69769876, ‘Gurugran! ), (3', tmanesh*, 17, 68769876, ‘aipor'), ('4", 'Priyat, 18, 78765876, ‘Noida’ ), C5", ‘Monika’, 17, 98769876, "Delhi')] Number Of rows in’ resultset is = 5 d) rowcount: It is cursor’s property to count the number of rows in resultset. Syntax: =.rowcount Example: Refer to the example of fetchmany() 6. Close the connection After doing all the processing, connection should be closed. Syntax: .close() Example: Refer to the example of fetchmany() Format specifier: We need format specifier to write SQL query based on user input. For doing this we have two ways: 1. Using % formatting: Whenever we needs to complete SQL query based on user input, we write a placeholder %s on that place. Example: Let’s fetch all the data from student table where age is ‘x’ and city is ‘y’. (Here, value of x and y will be given by the user during run time). Python Code: Inport aysel.connector as mys fays is alias of aysal.connector connys. connect (hest="localhost™, user="ODBClocalhost", database="test") eur=con.cursor() #ereating cursor xeint (input ("enter student's age = ")) y-input ("Enter student's city =") astselect * from student where Age=ts and Address = '$s!"4(x,y) #801 Query using § formatting where age and address is given’ by user becur-execute(a) fexecuting SgL query ‘a’ with cursor tcur* cxcur.fetchall() #retrieving all recoxds using fetchall() print (c) #priting the fetched datasst con.close() #closing the connection Output: RESTART: Bnter student's age = 18 Enter Student's City = Sonipat (C1, tamit', 18, 99769876, ‘sor /sers/SN¥/connec.p pat") ] 2, Using format() function: Whenever we needs to complete SQL query based on user input, we write a placeholder {} on that place. If we needs to complete the SQL query based on multiple user input, we 203 |Pace write placeholder {), (1, (}and so on at those places and pass user defined values in format function in sequence. Here 1* values passed in format function will be passed to 1* {}, 2 values passed to 2" {}, 3" value passed to 3" {} and so on, Example: Let's fetch all the data from student table where age is ‘x’ and city is ‘y’. (Here, value of x and y will be given by the user during run time). Python Code: con-nys. connect ( cur=con.cursor() gcreatin xint (input ("Enter studen sanector alhost", database="test") format (x.¥) fess is given By user e-execute (a) fexecuting SQ) r-fetchall() #retrieving Commit() : Whenever we perform update, delete or insert query, commit() function must be run before closing the connection. ‘Syntax: .commit() Example 1: Insert data in student table which will be given by the user during run time. Data in student table before insertion lmysaql> select * from student a-- — oo mont | ID | Student_Name | Age | Phone | Address | t-= - == =o- = ant 12 1 Amit ! 18 | 98769876 | Sonipat | 1 Z | Sonam | 16 | 88769876 | Gurugram | | 3 | Mahesh | 17 | 68769876 | Jaipur | 14 | Priya ! 18 | 78769876 | Noida | 1S | Monika | 17 | 98769876 | Delhi | 1 6 | Raman ! 18 | 98765876 | Noida ! | 7 | Pawan | 19 | 28765876 | Delhi | tom n toon conte = - aot [7 rows in set (8.08 sec) Python code: 204) Pave nport mysgl-connector a: mys #mys is alias of mysql .connect (host="localhost" ,user="0DBClocal hos! cursor () #creating curser ("Enter Student ut (“Enter Student t (input ("Enter Student (input ("nt 1)" format (v4, %,¥, 2) mn vhere data is given by user op7aaa Faridabad Data in student table after insertion fmysql> select % from student; a = Sa - = | ID | Student_Name | Age | Phone | Address + eo = Se ane Ae —— [12 1 Amit | 18 | 98769876 | Sonipat | 12 | Sonam | 16 | 88769876 | Gurugram | | 3 | Mahesh I 17 | 68769876 | Jaipur I 14 | Priya ! 18 | 78769876 | Noida ! 1S | Monika ! 17 | 98769876 | Delhi ! ! 6 | Raman ! 18 | 98765876 | Noida ! | 7 | Pawan ! 19 | 28765876 | Delhi ! | 10 | Shaan 16 | 987444 | Faridabad | toon n tenn - -o- too sonnnt 8 rows in set (0.20 sec) Example 2: Delete data of those students whose ID is given by the user during run time in student table. In the previous example, after inserting a record in student table, we have 8 records in the student table. (Kindly refer previous example for current state of student table). Python code: ayaqi. conne ya is allas of mysqi suser="ODACLocalhost* databasi 1)". format (x) ing format () function ‘2 ID is given by user con.commlt () print ("ata ae! con.close() #closii sprinting confirmation message 205 | Pace 88769876 pact !Z | Sonam ! 16 | | Gurugram | | 3 | Mahesh | 1/ | 68769876 | Jaipur | {4 | Priya | 18 | 78769876 | Noida | 1S | Monika | 17 | 98769876 | Delhi | 16 | Raman ! 18 | 98765876 | Noida ! | 7 | Pawan ! 19 | 28765876 | Delhi ! | 10 | Shaan | 16! | Faridabad | 987444 Example 3: Update name of those students whose name and ID is given by the user during run time in student table. In the previous example, after deleting a record in student table, we have 7 records in the student table. (Kindly refer previous example for current state of student table) Python code: syaqi . connect connect ys is ailas of m a5 ay .connect (host="1ocalhost",ser="ODBclocal host", database= ) nccursor() #creating cursot ut("Enter Student's 1D = ") (inter Student's Nane = ") tuden fe Namo="{}* where ID="() to updai nt" nane using format () func is given by us: ecute(a) fexecut con-commit() #commlting the changes in th print ("bata updated successfully") #print con.closa() #clasing the connection 19 SOL query ‘a’ Output: RESTART: Ci /Users/SMY/update.py == adent'2 Nane = Moana fa updated successfully 206 | Pave Data in student table after updating mysql> select * from student: $= -+ ig Mahesh 68769876 | Jaipur Priya Noida Moana Delhi Raman Noida Pawan Delhi Shaan Faridabad oe Powe ton ten nian ne nn tonnes cnc n nt in set (@.@@ sec) 207 | Pave MULTIPLE CHOICE QUESTIONS (MCQ) 1. What is the use of DBMS? Data Retrieval Data Storage Data Manipulation Allof the above 2. What is relational data model? Where data is organized in tree like structure with parent child relationship Where pointer is used to navigate through data Where data is represented as objects. Where data is organized into tables with rows and columns 3. What is tuple is relation? row column field attribute 4. What is attribute in relation? row column tuple key 5. What is degree in database? Foreign key of the table Primary key of the table Number of columns in the table Number of rows in the table 6. What is domain in database? The alternate key of a table The primary key of a table The set of all possible values in column The number of rows in table 7. What is cardinality in database? Number of columns Number of rows Number of primary key Number of attribute key 208 | Pace 8. What is key in SQL? Which is used to uniquely identify record To maintain data integrity To enable efficient data retrieval Allof the above 9. Which key is used to uniquely identify record in table and doesn’t allow NULL values? a. Alternate key b. Primary key c. Super key d. Foreign key 10. A column that could potentially be used as the primary key and it should also contain unique values? Alternate key Primary key Candidate key Surrogate key 11. A candidate key that is not selected as primary key which can serve as a unique identifier. a. Alternate key b. Primary key ©. Candidate key d. Surrogate key 12. What is the use of foreign key? a. To uniquely identify record b. To enforce data integrity ©. To define the data type of column d. To establish a link between two tables 13. A column or set of column in table that refers to the primary key of another table. a. Alternate key b. Primary key ©. Candidate key d. Foreign key 14, Which of the following SQL commands is used to view list of all database? a. select databases b. show databases c. view databases d. project databases 15. Which of the following SQL commands is used to use/select a particular database? 209 | Pave use select view project 16. Which SQL command is used to define and maintain physical structure or schema of table database like creating, altering and deleting database object such as table and constraints? a. DDL b. DML. c. DCL a. TCL 17. Which SQL command used to change or modify any attribute/column like addition and deletion of column in database? create alter delete update 18. A user request to retrieve data or information from database/table is called? key data query view 19. Which of the following is not a valid datatype in SQL? a. Date b. String ©. Decimal d. Char 20. Which command is used to delete database permanently? a. create database b. delete database ©. drop database d. use database 21. Which commands is used to show all table in current using database? a. display tables; b. show tables; ©. view tables; d. select all tables; 210|Pavce 22. Which command is used in where clause to search NULL values in a particular column? a. ISNULL b. IN NULL cc. NOT NULL d. 1S NOT NULL 23, Wild card operator (%,_) are used with? a. count b. max c. like d. min 24. Which SQL function is used to determine the no. of row or non-null values? min max count sum 25. Which SQL function is used to count the entire number of row in database table? a. count b. count(*) max d. min 26. In relational database, a key that established a link between two tables? Primary key Alternate key Foreign key Candidate key 27. A table containing data organized in the form of row and column in relational data model? Relation View Tuple Database 28. Which SQL clause is used to filter the result of SELECT statement in Relational Database? a. from b. where cj d._ having 29, INSERT command is used in database to perform 211|Pace To retrieve a set of statement To add new row of data to a table To change already existing data in table To delete any existing row in table 30. How many candidate key can a relation/table have in relational database a. One b. Two ©. Multiple d. None 31, What is the main difference between candidate key and primary key? a. Acandidate key can contain NULL value but primary key can’t contain NULL value b. Aprimary key can contain unique value but it is not necessary for the candidate key to have unique value c. Candidate key is chosen by database system while primary key is chosen by the designer d. No difference 32. Which DDL command is used to modify the structure of an existing table? a. create table b. modify table c._ alter table d. update table 33. Which DDL command is used to remove a table along with its all content from a database? a. DELETE TABLE b. DROP TABLE c. REMOVE TABLE d. ERASE TABLE 34. Which constraint enforce data integrity by ensuring that a column always contain a values? a. NULL b. NOT NULL c. CHECK d. DEFAULT 35. What is primary difference between candidate key and primary key in database? a. Primary key is chosen by the end user/designer while candidate key is generated by database system b. Acandidate key uniquely identifies each row in a table, while primary key is not unique A primary key can have NULL values while a candidate key can’t 212 |Pave d. Acandidate key can become a primary key, but a primary key can’t become a candidate key 36. Which key is used to enforce referential integrity between tables in database system Primary key Candidate key Foreign key Alternate key 37, What is the main difference between CHAR and VARCHAR datatype in SQL? a. CHAR is case-sensitive while VARCHAR is non case sensitive b. CHAR store variable length strings while VARCHAR stores fixed length string ©. CHAR store fixed length strings while VARCHAR stores variable length string d. CHAR is used storing numeric data while VARCHAR is used for text data 38. What is the primary purpose of unique key constraints in a relational databases? To ensure that values in a column are NULL To ensure that values in a column are unique To define relationship between tables To specify a condition that must be met for data to be valid in a column 39. Which constraint key is used when you want to enforce uniqueness but allows NULL values in database a. PRIMARY KEY b. UNIQUE KEY cc. NOT NULL d. CHECK 40. Which of the following is not a valid DML command in SQL? a. INSERT b. UPDATE c. ALTER d. DELETE 41. Which keyword is used for table aliasing that involves giving a table short and alternative name to simplify query syntax? from as where on 42. Which SQL clause is used in database table to eliminate duplicate rows from the query result? a. group by 213 | Pave b. distinct c. describe d. duplicate 43. Which of the following clauses in SQL is most appropriate to use to select matching tuples in a specific range of values? a. IN b. LIKE ©. BETWEEN d. 1S. 44. Which of the following SQL datatype allows NULL values by default? a. INT b. CHAR cc. VARCHAR d. FLOAT 45. Which of the following is NOT a required argument to the connect{) function? Hostname Username Password Database name 46. Which method is used to execute a SQL query on a MySQL database? a. execute() b. query() c. run() d. None of the above 47. Which method is used to fetch n number of results from a SQL query? a. fetchall() b. fetchone() c. fetchmany() d. Allofthe above 48. it is a pointer or iterator which points towards the resultset of the SQL query. a. cursor b. rset. cc. temp d. None of these 49, Which of the following is not a valid method to fetch records from database in python. a. fetchmany() b. fetchone() 214|Pape c d, fetchmulti() fetchall() 50. To get all the records from result set, you may use cursor.fetchmany() cursor.etchall() cursorfetchone() cursor.execute() Short answer type Questions: 1. 2 3. > What is SQL? Differentiate between DML and DDL. Explain with the help of examples. What are the different type of SQL data type? What is the difference between where statement and having statement in SQL? What is primary key? Differentiate between a database table and a database record, What is foreign Key? And how does it relate in a database. What is Domain in database? Explain the role of clause in query of SQL commands. What is Aliasing? Explain char, varchar and int datatype in SQL with example. . Differentiate between candidate key and alternate key? . Differentiate between degree and cardinality of a table with the help of example. . What are database keys? Explain all the database keys. What are constraints in SQL? Explain the wildcards used with like operator. What are joins in SQL? . Differentiate between Natural Join and Equi Joit ). Explain any two aggregate function in SQL. What is a cursor? . What is the role of commit() function in SQL? . What is Cartesian product? What will be the number of rows in output table if we apply Cartesian product on two tables T1 and T2 with 9 and 10 rows respectively? - Explain alter table command with the help of example. Differentiate between fetchall() function and fetchmany() function in SQL. . In SQL, Define aggregate function and write the name of the aggregate function which will display the cardinality of a table. 215|Pave Assertion-and-Reason Type In the following questions, Assertion (A) and Reason (R). Choose the correct choice as: (a) Both Assertion (A) and Reason (R) are the true and Reason (R) is a correct explanation of Assertion (A). (b) Both Assertion (A) and Reason (R) are the true but Reason (R) is not a correct explanation of Assertion (A), (c) Assertion (A) is true and Reason (R) is false. (4) Assertion (A) is false and Reason (R) is true. 1. Assertion (A}: COUNT function can be work with distinct keyword. Reason (R): DISTINCT keyword can only be used with COUNT function. 2. Assertion (A): HAVING clause can only be used with GROUP BY statement. Reason _(R): WHERE clause can be used in place of HAVING clause in GROUP BY statement. 3. Assertion (A): LIKE operator is used for pattern matching in WHERE clause. Reason (R): % and _ wildcard is used in LIKE operator for making a pattern. 4. Assertion (A): The primary key is applied on a column of a table. Reason _(R): NOT NULL constraint restricts NULL values in a column, 5. Assertion (A): SUM and COUNT are aggregate functions. Reason (R): Aggregate functions works on multiple tuples. 6. Assertion (A): Primary key constraints allows NULL values. Reason (R): The primary key constraints ensures that a column can contain unique Values for each row. 7. Assertion (A): Unique key constraint allows NULL values. Reason (R): The unique key constraints ensures that a column can contain unique Values. 8. Assertion (A): The HAVING clause is used to filter aggregated data in SQL queries. Reason (R): The HAVING clause is used to group rows with similar values in one or more column into result sets. 9. Assertion (A): Inner Join retrieves rows that have matching values in both tables being joined. Reason (R): Inner join excludes row with no matching values 10. Assertion (A): Between operator is used to filter data within a specified range. Reason (R): Where clause works exactly same as between operator 216 |Pave Long Answer Type Questions: 1. Write MySQL command to create the table ‘Employee’ with the following structure and constraint. Table: Employee Column_Name DataType(size) Constraint Emp_ID Int(20) Primary key Emp_Name. char(100) Not Null Salary int(20) Not Null Department char(30) Age int(a5) Not Null ‘Address Varchar(200) Unique 2. Write MySQL command to create the table ‘Student’ and structure and constraint. Table: Student ‘activities’ with the following Column_Name DataType(size) Constraint Student_ID varchar(20) Primary key Student_Name char(80) Not Null Gender char(20) Not Null Class varchar(30) Age int(20) Not Null ‘Address Varchar(150) Unique Phone Int(15) Not Null, unique Table: Activities Column_Name DataType(size) Constraint Student_ID varchar(20) Foreign key references t Student_ID of Employee| table Activity_Name_ char(80) Not Null Position char(30) Not Null 3. Anmol maintain that database of medicines for his pharmacy using SQL to store the data. The structure of the table PHARMA for the purpose is as follows: ‘* Name of the table-PHARMA ‘© The attributes of PHARMA are as follows: MID - numeric MNAME - character of size 20 PRICE - numeric UNITS - numeric EXPIRY ~ date 217 |Pape Table: PHARMA, MID__| MNAME PRICE UNITS EXPIRY, M1 PARACETAMOL 12 120 2022-12-25 m2 CETRIZINE 6 125 2022-10-12 M3 METFORMIN 14 150 2022-05-23 M4 VITAMIN B-6 12 120 2022-07-01 MS VITAMIN D3, 25, 150 2022-06-30 M6 TELMISARTAN 22 115 2022-02-25 (a) Write the degree and cardinality of the table PHARMA. (b) Identify the attribute best suitable to be declared as a primary key. (c) Anmol has received a new medicine to be added into his stock, but for which he does not know the number of UNITS. So he decides to add the medicine without its value for UNITS. ‘The rest of the values are as follows: MID MNAME PRICE EXPIRY. M7 SUCRALFATE 7 2022-03-20 Write the SQL command which Anmol should execute to perform the required task. (d) Anmol wants to change the name of the attribute UNITS to QUANTITY in the table PHARMA. Which of the following commands will he use for the purpose? |. UPDATE ll DROP TABLE II CREATE TABLE IV. ALTER TABLE (e) Now Anmol wants to increase the PRICE of all medicines following commands will he use for the purpose? |. UPDATE SET Il, INCREASE BY Ul, ALTER TABLE Iv. INSERT INTO 4. For the following SQL Table named PASSENGERS in a database TRAVEL: TNO NAME START END. TL RAVI KUMAR, DELHI MUMBAI T2 NISHANT JAIN DELHI KOLKATA, 3 DEEPAK PRAKASH | MUMBAI PUNE A cursor named Cur is created in Python for a connection of a host which contains the database TRAVEL. Write the output for the execution of the following Python statements 218 | Pave for the above SQL Table PASSENGERS: Cur.execute(‘USE TRAVEL’) Cur.execute('SELECT * FROM PASSENGERS’) Recs=Cur-fetchall() For R in Recs: Print(R[4]) 5. Write SQL statements for the following queries (i) to (v) based on the relations CUSTOMER and TRANSACTION given below: Table: CUSTOMER ‘ACNO NAME GENDER BALANCE ca RISHABH M 15000 2] ‘AAKASH M 12500 3B INDIRA F 9750 ey TUSHAR. M 14600 cS ANKITA F 22000 Table: TRANSACTION ‘ACNO TDATE AMOUNT TYPE ca 2020-07-21 1000 DEBIT cS 2019-12-31. 1500 ‘CREDIT 3B 2020-01-01. 2000 ‘CREDIT 1. To display all information about the CUSTOMERS whose NAME starts with 2. To display the NAME and BALANCE of Female CUSTOMERS (with GENDER as 'F') whose TRANSACTION Date (TDATE) is in the year 2019. 3. To display the total number of CUSTOMERS for each GENDER. 4. To display the CUSTOMER NAME and BALANCE in ascending order of GENDER. 5. To display CUSTOMER NAME and their respective INTEREST for all CUSTOMERS where INTEREST is calculated as 8% of BALANCE. .. The IT Company XYZ has asked their IT manager Ms. Preeti to maintain the data of all the employees in two tables EMPLOYEE and DEPT. Ms. Preeti has created two tables EMPLOYEE and DEPT. She entered 6 rows in EMPLOYEE table and 5 rows in DEPT table. Table: DEPT [p_cope | D_NAME cry, Door INFRASTRUCTURE DELHI D002 MARKETING DELHI D003 MEDIA. MUMBAI OOS FINANCE KOLKATA, D004 HUMAN RESOURCE MUMBAI 219| Pave Note: DOJ refers to date of j ‘Table: EMPLOYEE ENO | NAME | DOJ DOB GENDER] D_CODE _| Salary 1001 | Vinay _| 2013-09-02 | 1991-09-01 [MALE | D001 250000 1002 | Ruby | 2012-12-11 | 1990-12-15 | FEMALE _| D003 270000 1003 _| Anuj 2013-02-03 | 1987-09-04 | MALE _ | DOOS 240000 1007 | Sunny _| 2014-01-17 | 1988-10-19 [MALE D004 250000 1004 [Rohit | 2012-12-09 [1986-11-14 [MALE _| D001 270000 1005 | Preeti__| 2013-11-18 | 1989-03-31 | FEMALE | D002 NULL ining and DOB refers to date of Birth of employees. Based on the above data, answer the following questions: 1 Identify the column which can be consider as primary key in EMPLOYEE table, Identify the column which can be consider as primary key in DEPT table What is the degree and cardinality of EMPLOYEE table? ‘What is the degree and cardinality of DEPT table? Write SQL queries for the following: 1) Insert two new row in Employee table with following data: 1006 | Rahul_| 2019-11-06 | 1992-01-04 [MALE | D003 _| 156000 1008 [Sonam [ 2022-01-06 [1991-04-06 | FEMALE [D005 | 167000 2) To display E_NO, NAME, GENDER from the table EMPLOYEE in descending order of E_NO. 3) To display the NAME of all the ‘FEMALE’ employees from the table EMPLOYEE. 4) To display the E_NO and NAME of those employees from the table EMPLOYEE who are born between ‘1987-01-01’ and ‘1991-12-01 5) To display NAME and CITY of those employees whose DEPARTMENT is either ‘MEDIA’ or ‘FINANCE’ 6) To display the NAME of those employees whose name starts with letter ‘R’ 7) To display NAME of those employees whose name contains letter‘ 8) To display NAME of those employees whose name has exact 5 letters. 9) To display D_NAME and CITY from table DEPT where D_NAME ends with letter and CITY is ‘DELHI’ 10) To display the maximum SALARY of EMPLOYEE table. 11) To delete data of all those employees whose age is less than 25, 112) To update SALARY to 230000 of those employee whose E_NO is 1004. 13) To change the sequence of DOB column in employee table and move it before DOJ column. 14) To add a new column MOBILE int(20) before column SALARY in employee table. 15) To set SALARY to 300000 of all those employees whose age is NULL. 16) To Increase the salary of all employees by 30000 in EMPLOYEE table. 17) To display the average SALARY of EMPLOYEE table. 18) To display name of employees who have SALARY more than 200000 in ascending order of NAME 19) To display department wise average salary of employees. 20) To display total number of departments in XYZ company, 21) To delete data of all the employees whose D_CODE is not ‘D001’ 22) To display E_NO, NAME and SALARY of all those employees who don’t live in ‘DELHI’ 220| Pape 23) To change column name CITY to D_CITY in DEPT table. 24) To delete EMPLOYEE table. 25) To delete D_NAME column from DEPT table. 7. Agarment store is considering to maintain their inventory using SQL to store the data. as a database administrator, Mr.Rohit has decided that: ‘+ Name of the database - STORE ‘© Name of the table - GARMENT ‘© The attributes of GARMENT table are as follows: = GCODE - numeric = DESCRIPTION ~ character of size SO = PRICE numeric = FCODE - varchar of size 10 Table: GARMENT GCODE DESCRIPTION PRICE FCODE 10023 JEANS 1150 FOL 10001 SHIRT 750 FO2, [a004a—«dsHoRTs=—“‘é|KOO!!}!}©™©™©€6UFOSUUCO@ fyoo0s—=«<«dTESC*é“‘(CS3(SW;:#C«CAOO”*O”#*#~#~#~#~;7;«;©2%: Cd [aooo2~—«uackeT=—s—“‘é CcttO”;!”!#!}!}FUFORDUUOOC~;~C@d 10022 150 NULL 1. Categorize the following commands as DDL or DML: ALTER, INSERT, UPDATE, CREATE, DROP, DELETE Identify the attribute of Garment table to be declared as primary key. Write the degree and cardinality of the table GARMENT Write SQL query to create database STORE, Write SQL query to display list of available databases. Write SQL query to use database STORE. Write SQL query to display list of available tables in database STORE. Write SQL query to create table GARMENT with aforementioned attributes. Obtain the output of following SQL queries based on the data given in table GARMENT: (i) SELECT MAX(PRICE), MIN(PRICE) FROM GARMENT; (ii) SELECT GCODE, DESCRIPTION FROM GARMENT; (iii) SELECT FCODE,GCODE FROM GARMENT WHERE PRICE BETWEEN 500 AND 800; (iv) SELECT * FROM GARMENT WHERE DESCRIPTION NOT IN (JEANS!/TIE"); (v)_ SELECT GCODE FROM GARMENT WHERE DESCRIPTION LIKE ‘%4S%’; (vi) SELECT GCODE,PRICE FROM GARMENT WHERE DESCRIPTION LIKE ‘ (vil) SELECT DISTINCT FCODE FROM GARMENT; 221| Pace (vill) SELECT SUM(PRICE) FROM GARMENT; (ix) SELECT * FROM GARMENT WHERE DESCRIPTION LIKE ‘%T%' AND. FCODE!='F02'; (x) SELECT * FROM GARMENT ORDER BY PRICE DESC; (xi) SELECT PRICE*10 FROM GARMENT; (xii) SELECT COUNT(DISTINCT FCODE) FROM GARMENT; (xii) SELECT * FROM GARMENT WHERE FCODE NOT IN (‘FO1’/F02’) AND PRICE<500; (xiv) _ SELECT GCODE, PRICE FROM GARMENT WHERE FCODE IS NULL; (xv) SELECT * FROM GARMENT WHERE PRICE >S00 AND PRICE <1000; 8. Write the output of the following SQL queries based on table TRANSACTION given below: Table: TRANSACTION T_NO__|M_NO AMOUNT | CARD_TYPE | DATE ‘STATUS 1 ii 5000. CREDIT 2019-10-11 | SUCCESS 2 i 170 CREDIT 2019-10-14 | FAILURE 3 3 800 DEBIT 7201-10-24 _| FAILURE 4 2 90 CREDIT 2019-11-10 | SUCCESS 5 3 1400 DEBIT 2019-11-11 | SUCCESS 6 cry 500 DEBIT 2019-11-18 | SUCCESS 7 B 1600 DEBIT 2019-11-27 | FAILURE Table: COMPANY TNO ‘QTY_ISSUED ‘COMPANY 1 15 SBI 3 50. ICICl 4 34 HDFC (i) (i) (iii) (wv) Ww) (vi) (vii) (viii) (x) &) SELECT M_NO, MIN(AMOUNT) FROM TRANSACTION GROUP BY M_NO HAVING. COUNT(*)>2; SELECT T_NO,AMOUNT FROM TRANSACTION WHERE CARD_TYPE=’CREDIT’; SELECT * FROM TRANSACTION WHERE M_NO>12 AND STATUS=’FAILURE’; SELECT CARD_TYPE, SUM(AMOUNT) FROM TRANSACTION GROUP BY CARD_TYPE; SELECT T_NO, AMOUNT*10 AS PAYMENT FROM TRANSACTION WHERE STATUS IN (‘success’); SELECT COUNT(*) FROM TRANSACTION WHERE STATUS=’SUCCESS’; SELECT T_NO, AMOUNT, CARD_TYPE FROM TRANSACTION WHERE T_NO>S; SELECT DISTINCT M_NO FROM TRANSACTION; SELECT T_NO, M_NO,CARD_TYPE, COMPANY FROM TRANSACTION T, COMPANY C WHERE T.T_NO=C.T_NO AND AMOUNT>1000; SELECT T-T_NO AS TRANS_NO FROM TRANSACTION T, COMPANY C WHERE TT_NO=CT_NO; 222 |Pape 9. The code given below reads the records from the table employee and displays only those records of employee table who don’t lives in city ‘Delhi’: EID —varchar(50) E_Name ~ char(50) Salary —int(15) City —char(20) Note the following to establish connectivity between Python and MySQL- > Username is root > Password is 12345 > The table exists in a MySQL database named company. > The table has four attributes (E_ID, E_Name, Salary, City). Write the following statements to complete the code: Statement 1- to import the desired library. Statement 2- to create a cursor Statement 3- to write a sql query that fetches records of all those employees who don’t lives in delhi Statement 4- to execute the query Statement 5- to print all the records fetched in statement 4 Import as mysql Statement 1 def print(): yysql.connect (host="localhost", user “root” passwd=12345, database= “company") be Statement 2 query = Statement 3 Statement 4 for z inc: Statement 5 10. The code given below deletes the records from the table employee which contains following record structure: EID —varchar(S0) E_Name — char(50) Salary —int(15) City —char(20) Note the following to establish connectivity between Python and MySQL: > Username is root > Password is 12345 > The table exists in a MySQL database named company. > The table has four attributes (E_ID, E_Name, Salary, City) Write the following statements to complete the code: Statement 1- to import the desired library. Statement 2- to connect to the database 223 | Pave 1. 12. 13. Statement 3- to create a cursor Statement 4- to write a query that deletes the record with E_ID=’A101’ and E_Name starts with letter ‘D’ Statement 5- to remove the record permanently from the database. Import as mysql #Statement 1 def del() (host="localhost", user "root",passwd=12345, database= company") #Statement 2 ‘#Statement 3 #Statement 4 #Statement 5 query print(‘Data deleted’) Write a python program to delete all the tuples from Student table whose age>14 Note the following to establish connectivity between Python and MySQL: Username is root Password is 12345 The table exists in a MySQL database named school. ‘The table has five attributes (Stu_ID, Stu_Name, age, Address) Write a python program to insert 5 records in Employee table. Take these 5 records as an input from the user (One record at a time) Note the following to establish connectivity between Python and MySQL: Username is root Password is 12345 The table exists in a MySQL database named company. The table has five attributes (Emp_ID, Emp_Name, DOJ, Gender, Salary) ‘Write a python program to update name of employee in Employee table whose employee id is E1001’ (Take updates name as an input from the user). Note the following to establish connectivity between Python and MySQL: Username is root Password is 12345 The table exists in a MySQL database named company. The table has five attributes (Emp_ID, Emp_Name, DOJ, Gender, Salary) 224|Pape

You might also like