50
LUCKNOW PUBLIC SCHOOL SESSION-2019-20 STUDY MATERIAL FRAGMENT -2 PART-2 SUBJECT: COMPUTER SCIENCE (283) CLASS-XII CHAPTERS INCLUDED: Chapter-:BOOLEAN ALGEBRA Chapter-RELATIONAL DATABASE AND SQL

LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

LUCKNOW PUBLIC SCHOOL

SESSION-2019-20

STUDY MATERIAL

FRAGMENT -2 PART-2

SUBJECT: COMPUTER SCIENCE (283)

CLASS-XII

CHAPTERS INCLUDED:

Chapter-:BOOLEAN ALGEBRA Chapter-RELATIONAL DATABASE AND SQL

Page 2: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 1 |11

CHAPTER 13 : BOOLEAN ALGEBRA

Boolean algebra is an algebra that deals with Boolean values((TRUE and FALSE). In Boolean algebra we

use 1 for true and 0 for false which are known as truth values.

Truth table: A truth table is composed of one column for each input variable (for example, A and B), and one final

column for all of the possible results of the logical operation that the table is meant to represent. Each row of

the truth table therefore contains one possible configuration of the input variables (for instance, A = true B =

false), and the result of the operation for those values.

Logical Operators: In Algebraic function we use +,-,*,/ operator but in case of Logical Function or Compound statement we use

AND,OR & NOT operator. Example: He prefers Computer Science NOT IP.

There are three Basic Logical Operator:

1. NOT

2. OR

3. AND

NOT Operator—Operates on single variable. It gives the complement value of variable.

OR Operator -It is a binary operator and denotes logical Addition operation and is represented by ”+”

symbol

AND Operator – AND Operator performs logical multiplications and symbol is (.) dot.

Basic Logic Gates A logic gate is an physical device implementing a Boolean function, that is, it performs a logical operation

on one or more logic inputs and produces a single logic output. Gates also called logic circuits.

Or

Page 3: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 2 |11

A gate is simply an electronic circuit which operates on one or more signals to produce an output signal.

NOT gate (inverter):The output Q is true when the input A is NOT true, the output is the inverse of the

input:

Q = NOT A A NOT gate can only have one input. A NOT gate is also called an inverter.

AND gate The output Q is true if input A AND input B are both true: Q = A AND B An AND gate can have two or

more inputs, its output is true if all inputs are true.

OR gate The output Q is true if input A OR input B is true (or both of them are true): Q = A OR B An OR gate can

have two or more inputs, its output is true if at least one input is true.

Basic postulates(rules) of Boolean Algebra: Boolean algebra consists of fundamental laws that are based on theorem of Boolean algebra. These

fundamental laws are known as basic postulates of Boolean algebra. These postulates states basic relations

in boolean algebra, that follow:

i) If X != 0 then x=1 and If X!=1 then x=0

ii) OR relations (logical addition)

iii) AND relations (logical multiplication)

iv) Complement rules 0’=1, 1’=0

Page 4: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 3 |11

Duality Principle This principal states that we can derive a Boolean relation from another Boolean relation by performing

simple steps. The steps are:-

1. Change each AND(.) with an OR(+) sign

2. Change each OR(+) with an AND(.) sign

3. Replace each 0 with 1 and each 1 with 0

e.g

0+0=0 then dual is 1.1=1

1+0=1 then dual is 0.1=0

Basic theorem of Boolean algebra

Basic postulates of Boolean algebra are used to define basic theorems of Boolean algebra that provides all

the tools necessary for manipulating Boolean expression.

Page 5: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 4 |11

DeMorgan’s Theorem:

Derivation of Boolean expression:-

Minterm : Minterm is a Product of all the literals within the logic System.

Step involved in minterm expansion of Expression

1. First convert the given expression in sum of product form.

2. In each term if any variable is missing (e.g. in the following example Y is missing in first term and X is

missing in second term), multiply that term with (missing term + complement (missing term)) factor e.g. if

Y is missing multiply with Y+Y”)

3. Expand the expression.

4. Remove all duplicate terms and we will have minterm form of an expression.

Example: Convert X+Y

X+Y=X.1+Y+1

=X.(Y+Y’) + Y.(X+X’)

=X.Y + X.Y’ + Y.X +Y.X’

=X.Y + XY’ + X’Y

Shorthand Minterm notation: Since all the letters must appear in every product, a shorthand notation has been developed that saves

actually writing down the letters themselves. To form this notation, following steps are to be followed:

1. First of all, Copy original terms

2. Substitute 0s for barred letters and 1s for nonbarred letters

3. Express the decimal equivalent of binary word as a subscript of m.

Rule1. Find Binary equivalent of decimal subscript e.g.,for m6 subscript is 6, binary equivalent of 6 is 110.

Rule 2. For every 1s write the variable as it is and for 0s write variables complemented form i.e., for 110 t is

XYZ”. XYZ’ is the required minterm for m6.

Maxterm: A maxterm is a sum of all the literals (with or without the bar) within the logic system.

Page 6: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 5 |11

Example: Convert X.Y

X.Y= (X+0).(0+Y)

= (X+YY’).(XX’+Y)

= (X+Y).(X+Y’).(X+Y).(X’+Y)

= (X+Y).(X+Y’).(X’+Y)

For maxterms, 0 means the variable is “Not complemented” and 1 means the variable is “complemented”.

Canonical Form:

Boolean Expression composed entirely either of Minterms or Maxterms is referred to as Canonical

Expression.Canonical expression can be represented is derived from

(i) Sum-of-Products(SOP) form

(ii) Product-of-sums(POS) form

Sum of Product (SOP)

A Boolean function may be represented algebraically from a given truth table by forming a minterm for each

combination of the variables that produces a 1 in the function and then taking the OR of all those terms.

Product of Sum (POS) A Boolean function may be represented algebraically from a given truth table by forming a maxterm for

each combination of the variables that produces a 0 in the function and then taking the AND of all those

terms.

X Y Z F

0 0 0 0

0 0 1 1

0 1 0 0

0 1 1 0

1 0 0 1

1 0 1 0

1 1 0 0

1 1 1 1

For result F(SOP form is)= X’Y’Z + XY’Z’ + XYZ

For result F(POS form is)=(X+Y+Z).(X+Y’+Z).(X+Y’+Z’).(X’+Y+Z’).(X’+Y’+Z)

Minimization of Boolean expressions:-

After obtaining SOP and POS expressions, the next step is to simplify the Boolean expression.

There are two methods of simplification of Boolean expressions.

1. Algebraic Method

2. Karnaugh Map :

1.Algebraic method:This method makes use of Boolean postulates, rules and theorems to simplify the

expression.

Example: Simplify X’Y’+X’+XY

Solution: X’Y’ + X’ + XY = (X’+Y’)+X’+XY (Demorgan’s 2nd theorem)

= X’+X’+Y’+XY

= X’+Y’+XY (since X’+X’=X’ AS X+X=X)

= X’+XY+Y’

= (X’+(X’)’Y)+Y’=(X’+XY)+Y’ (putting X=(X’)’

= X’+Y+Y’ (X+X’Y=X+Y)

=X’+1 (putting Y+Y’=1)

=1 (putting X’+1=1 AS 1+X=1)

Page 7: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 6 |11

2. Using Karnaugh Map :

Karnaugh Maps: Karnaugh map or K Map is a graphical display of the fundamental product in a truth table.

For example:

Put a 1 in the box for any minterm that appears in the SOP expansion.

Basic idea is to cover the largest adjacent blocks you can whose side length is some power of 2.

Blocks can “wrap around” the edges.

Remember, group together adjacent cells of 1s, to form largest possible rectangles of sizes that are powers

of 2. Notice that you can overlap the blocks if necessary.

Page 8: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 7 |11

For reducing the expression first mark Octet, Quad, Pair then single.

• Pair: Two adjacent 1’s makes a pair.

• Quad: Four adjacent 1’s makes a quad.

• Octet: Eight adjacent 1’s makes an Octet.

• Pair removes one variable.

• Quad removes two variables.

• Octet removes three variables.

Reduction of expression: When moving vertically or horizontally in pair or a quad or an octet it can be

observed that only one variable gets changed that can be eliminated directly in the expression. For Example

In the above Ex

Step 1 : In K Map while moving from m7 to m15 the variable A is changing its state Hence it can be

removed directly, the solution becomes B.CD = BCD. This can be continued for all the pairs, Quads, and

Octets.

Step 2 : In K map while moving from m0 to m8 and m2 to m10 the variable A is changing its state. Hence

B’ can be taken similarly while moving from m0 to m2 and m8 to m10 the variable C is changing its state.

Hence D’ can be taken; the solution becomes B’.D’ The solution for above expression using K map is BCD

+ B’D’.

Example1: Reduce the following Boolean expression using K-Map:

F(P,Q,R,S)=Σ(0,3,5,6,7,11,12,15)

Soln:

This is 1 quad, 2pairs & 2 lock

Quad(m3+m7+m15+m11) reduces to RS

Pair(m5+m7) reduces to P’QS

Pair (m7+m6) reduces to P’QR

Block m0=P’Q’R’S’

M12=PQR’S’

hence the final expressions is F=RS + P‟QS + P‟QR + PQR‟S‟ + P‟Q‟R‟S‟

Page 9: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 8 |11

Example2: Reduce the following Boolean expression using K-Map:

F(A,B,C,D)=Π(0,1,3,5,6,7,10,14,15)

Soln:

Reduced expressions are as follows:

For pair 1, (A+B+C)

For pair 2, (A‟+C‟+D)

For Quad 1, (A+D‟)

For Quad 2, (B‟+C‟)

Hence final POS expression will be

More about Gates:

NAND gate (NAND = Not AND) This is an AND gate with the output inverted, as

shown by the 'o' on the output. The output is true if

input A AND input B are NOT both true: Q = NOT

(A AND B) A NAND gate can have two or more

inputs, its output is true if NOT all inputs are true.

NOR gate (NOR = Not OR) This is an OR gate with the output inverted, as

shown by the 'o' on the output. The output Q is true

if NOT inputs A OR B are true: Q = NOT (A OR B)

A NOR gate can have two or more inputs, its output

is true if no inputs are true.

Page 10: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 9 |11

EX-OR (EXclusive-OR) gate The output Q is true if either input A is true OR input

B is true, but not when both of them are true: Q = (A

AND NOT B) OR (B AND NOT A) This is like an

OR gate but excluding both inputs being true. The

output is true if inputs A and B are DIFFERENT.

EX-OR gates can only have 2 inputs.

EX-NOR (EXclusive-NOR) gate This is an EX-OR gate with the output inverted,

as shown by the 'o' on the output. The output Q

is true if inputs A and B are the SAME (both

true or both false):

Q = (A AND B) OR (NOT A AND NOT B)

EX-NOR gates can only have 2 inputs.

NAND gate equivalents The table below shows the NAND gate equivalents of NOT, AND, OR and NOR gates:

Low Order Thinking Questions

a) State and verify absorption law in Boolean algebra.

Ans. Absorption Law states that :

a) X+XY=X b) X(X+Y)=X

b) Verify X’.Y+X.Y’=(X’+Y’).(X+Y) algebraically.

Ans. LHS= X’Y + XY’

= (X’+X) (X’+Y’) (Y+X) (Y+Y’)

= 1.(X’+Y’) (X+Y).1

= (X’+Y’) (X+Y)

= RHS, hence proved

Page 11: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 10 |11

c) Write the equivalent Boolean Expression F for the following circuit diagram :

Ans.: A’B+AB+B’C

d) If F(P,Q,R,S) = Π (3,4,5,6,7,13,15) , obtain the simplified form using K-Map.

Ans.:

Reduction of groups following the reduction rule :

Quad1 = M4.M5.M6.M7

= P+Q’

Quad2 = M5.M7.M13.M15

= Q’+S’

Pair = M3.M7

= P+R’+S’

Therefore POS of F(P,Q,R,S) = (P+Q’)(Q’+S’)(P+R’+S’)

e) F(a,b,c,d)=Σ(0,2,4,5,7,8,10,12,13,15)

F(a,b,c,d)=B1+B2+B3

B1=m0+m4+m12+m8==c’d’

B2=m5+m7+m13+m15=bd

B3=m0+m2+m8+m10=b’d’

F(a,b,c,d)=c’d’+bd+b’d’

Page 12: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

XII/CS(283)/Notes Sumit Srivastava, Lucknow Public School, Unnao

Chapter 13: Boolean Algebra 11 |11

Assignment

Q1. State and prove Demorgan Law using Truth Table.

Q2. State and prove Absorption Law algebraically.

Q3. State and prove Distributive Law algebraically.

Q4. Write the equivalent Expression for the following Logic Circuit.

Q5. Write the equivalent Boolean Expression F for the following circuit diagram

Q6. Write the equivalent Boolean Expression F for the following circuit diagram

Q7. Convert the following Boolean expression into its equivalent canonical Sum of Product form (SOP)

(X’+Y+Z’).(X’+Y+Z).(X’+Y’+Z).(X’+Y’+Z’)

Q8. Convert the following Boolean expression into its equivalent canonical Product of Sum form (POS)

A.B’.C+A’.B.C+A’.B.C’

Q9. Draw a Logical circuit diagram for the following Boolean expression:

A.(B+C’)

Q10. Design (A+B).(C+D) using NOR gate.

Q11. If F(a,b,c,d)=∑(0,3,4,5,7,8,9,11,12,13,15) obtain the simplified form using K-map.

Q12. Obtain a simplified form for a Boolean expression

F(U,V,W,Z)=∏(0,1,3,5,6,7,10,14,15)

Page 13: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 1

Chapter- Relational Databases

Database: A database is a collection of interrelated data stored together to serve multiple application.

OR A database is an organized collection of data, generally stored and accessed electronically from a computer system. Advantages of database: i) It reduces data redundancy (duplication of data). ii) It controls data inconsistency. iii) It provides global sharing of data. iv) It provides integrity of data. Data Redundancy: Duplication of data is known as Data Redundancy. Data Models Data model is a set of concepts to describe the structure of database and constraints that database should obey. Note: Basically it is a type of some rules for database which should have to be followed by database. Database models are of four types:

1- The Relational Data Model In relational data model, the data is organized into tables.

2-The Network Data Model In a network database, the collections of records are connected to one another by means of links. Links means that it is an association between precisely two records.

3-The Hierarchical Data Model In this model, data records are organized in tree structure format.

4-Object Oriented Data model Object oriented data model is based upon real world situations. These situations are represented as objects, with different attributes. All these objects have multiple relationships between them. DBMS: A database management system (DBMS) is a software package designed to define, manipulate, retrieve and manage data in a database.

Page 14: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 2

Components Of a table: The following image shows the various components of a table-

Table: Part

Some important terminologies:- Relation: Relation is sometimes used to refer to a table in database but is more commonly used to describe the relationships that can be created between those tables in a relational database. Domain: A domain is defined as the set of all unique values permitted for an attribute. Example- A domain of date is the set of all possible valid dates, a domain of day-of-week is Sunday, Monday….Saturday. Tuple: A row of a table in a database is also known as tuple.

Page 15: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 3

Attribute: The headings of the column in a table are known as the attributes of the table. Degree: Number of attributes (Total numbers of columns present in a table) is known as the degree of the table. Cardinality: The number of tuples(rows) present in a table is known as cardinality of the table. Primary key: Primary key contains unique records and null value cannot be inserted in the primary key column. There will be only one column as a primary key in a table. Candidate Key: A candidate key can be any column or a combination of columns that can qualify as unique key in the database. There can be multiple candidate keys in a table. Alternate Key: If any table have more than one candidate key, then after choosing primary key from those candidate key, rest of candidate keys are known as an alternate key of that table. Foreign key: Foreign key are those keys which is used to define relationship between two tables. When we want to implement relationship between two tables then we use concept of foreign key. It is also known as referential integrity. Foreign key is generally a primary key from one table that appears as field in another where the first table has a relationship to the second table. In other words, if we had a table A with a primary key X that linked to a table B where X was a field in B, then X would be a foreign key in B. Operation in relational algebra: 1. Selection 2. Projection 3. Union 4. Cartesian Product

Selection in relational algebra returns those tuples(records) in a relation that fulfill a condition(Produce table containing subset of rows).

σ condition (relation) σ(rn>10)(student)

Projection in relational algebra returns those columns in a relation that given in the attribute list (Produce table containing subset of columns). Syntax:

∏attribute list(relation) Example:

Page 16: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 4

∏Adno,Name (S)

UNION The union operator is used to combine two or more tables. Each table within the UNION should have the same number of columns, similar data types and also the columns must be in the same order. In the union operation, duplicate records will be automatically removed from the resultant table. Select * from a union select * from b;

Cartesian product is a binary operation and is denoted by (x) Cartesian product returns a number of rows equal to number of records in the first table multiply by number of records in the second table. At the same time, number of columns equal to number of columns in the first table added by number of columns in the second table.

Select * from a,b;

JOIN: combining records of a two tables. Equi Join Equi Joins are used to give information in different tables. It is a special type of join in which we use only equality operator. For example SELECT * FROM product, customer WHERE product.product_no = customer. procuct_no; (or) SELECT * FROM product p, customer c WHERE p.product_no=c.procuct_no;

SQL Non-equi joins The non-equi join is a type of join in which, we use only relational operators except equal operator. These include >, <, >=, >= and !=. For example SELECT * FROM product,customer WHERE product.product_no!=customer.procuct_no; OPERATORS: Arithmetic operator takes two operands and performs a mathematical calculation on them. However, they can be used only in SELECT command. The arithmetic operators used in SQL are: + Addition - Subtraction * Multiplication / Division Relational operators are used to implement comparison between two operands. These operators can be used only in 'where clause'. Relational operators are - < less than > greater than < = less than or equal to > = greater than or equal to

Page 17: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 5

= equal to < > not equal to Data types in MySQL: String datatypes: CHAR, VARCHAR Numeric datatype: NUMBER, NUMERIC, INT, FLOAT, DOUBLE Date: DATE

SQL (Structured Query Language): It is the language used to manipulate and manage databases and tables within them using an RDBMS.

Different Types of SQL Statements:

1. DDL (Data Definition Language): This is a category of SQL commands. All the commands which are used to create, destroy, or restructure databases and tables come under this category. Examples of DDL commands are -

CREATE TABLE: Used to create structure of the table. ALTER TABLE: used to modify structure of a table i.e to add or remove column,

constraints from a table DROP TABLE: To remove full structure. CREATE VIEW :to create a virtual table that takes data from existing table.

2. DML (Data Manipulation Language): This is a category of SQL commands. All the commands which are used to manipulate data within tables come under this category. Used for record maintenance. Examples of DML commands are –

INSERT INTO: To add record or row values. SELECT: To display row or column information. UPDATE :it is used to modify data or record in a table. DELETE : it is used to delete records in a table

3. DCL (Data Control Language): This is a category of SQL commands. All the commands which are used to control the access to databases and tables fall under this category. Examples of DCL commands are - GRANT, REVOKE. 4.Transaction control language(TCL):set of commands used to control a transaction like saving changes in a transaction, undo changes in a transaction etc. ROLLBACK,COMMIT, SAVEPOINT,START TRANSACTION MYSQL Database System: MySQL is an open-source relational database management system that works on many platforms. It provides multi-user access to support many storage engines and is backed by Oracle. The features of MySQL are as follows:

Page 18: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 6

Ease of Management – The software very easily gets downloaded and also uses an event scheduler to schedule the tasks automatically.

Robust Transactional Support – Holds the ACID (Atomicity, Consistency, Isolation, Durability) property, and also allows distributed multi-version support.

Comprehensive Application Development – MySQL has plugin libraries to embed the database into any application. It also supports stored procedures, triggers, functions, views and many more for application development.

High Performance – Provides fast load utilities with distinct memory caches and table index partitioning.

Low Total Cost Of Ownership – This reduces licensing costs and hardware expenditures.

Open Source & 24 * 7 Support –This RDBMS can be used on any platform and offers 24*7 supports for open source and enterprise edition.

Secure Data Protection – MySQL supports powerful mechanisms to ensure that only authorized users have access to the databases.

High Availability – MySQL can run high-speed master/slave replication configurations and it offers cluster servers.

Scalability & Flexibility– With MySQL you can run deeply embedded applications and create data warehouses holding a humongous amount of data.

Comments in MySQL: Comments in mysql are used for documentation purpose which is not get executed. Comments can be written in following three ways in MySQL-

i) It can be enclosed within /*…..*/ when we will have to assign multiline comments.

ii) It can be begin with hyphens followed by space(-- ) for single line comment. iii) It can begin with # symbol, it is also a single line comment.

----------------------------------------------------------------------------------------------------

Working with database and tables and executing various commands Creating database: Syntax: create database databaseName; Eg: create database dept;

Page 19: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 7

Using database Syntax: use databaseName; Eg: use dept;

Now after selecting or using a database , we can create table in that database as follows: Syntax for creating a table: create table tableName(column1 dataType,col2 dataType……..column N dataType); Que: Create the table ‘emp’ as the structure given below in the table:-

Column_name Datatype(size) Constraint

sNo Int Primary key

Name Varchar(34)

Address Varchar(45) --

Salary Int --

DOB Date --

Ans: create table emp ( sno int primary key, name varchar(34), address varchar(45), salary int, DOB date

Page 20: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 8

);

Inserting records in a table: Syntax: insert into tableName values(value1,value2,…..value n); Note: The values should be passed as matching columns in the created table. You cannot shuffle the values of different columns while inserting the records. Eg: insert into emp values(1, ‘harish’, ‘gomtinagar’,55000, ‘1990-12-28’);

Now in the similar way add few more records and display all records by using the select query:

Page 21: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 9

Displaying selected columns: Suppose if you want to display only the name and salary columns then the sql query will be as follows-

Distinct Keyword: This keyword removes all the duplicate entries present in the column at the time of output. Example is given below:

Note: Earlier when we used select command without the distinct clause it represented all seven records but this time it has removed all the duplicate entries of salary which were similar and represented only distinct (unique) records available in the salary column.

Page 22: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 10

All Keyword: This will display all the records of a column whether it is repeated or not.

Note: All the seven records are available now whether it is duplicate or not. Displaying all ready created Databases and Tables: In order to display already created databases and tables we will use ‘show’ command.

1) For displaying all databases available on your dbms use show databases; command.

2) For displaying all tables in a particular database use show tables; command.

Note: Here we had used dept database and then executed show tables command to view all tables available in this database. Describing table structure: Table structure means how many columns are there in that table, what are the data types and size assigned to them, what are the constraints and default values are used with them. For this we will use ‘desc’ or ‘describe’ command as follows:

Page 23: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 11

Performing Simple calculation using select command on MYSQL: We can done any simple calculation without selecting any database and table on mySql prompt. Some of the examples are-

Note: In the above examples we had not used any table name as we did earlier followed by ‘from’ clause. Column aliases:

Column aliases mean taking another name of a column at the time of output.

We will use ‘as’ keyword to make column alias.

Column aliases are the temporary name assigned to a column which will not reflected any physical changes on the table.

Que. Now consider the above table ‘emp’ and display sNo as series, name column’s heading should be changed as FirstName and salary as sal.

‘%’ symbol will return remainder

‘/’ Symbol will return quotient

Page 24: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 12

Ans: select sno as 'series', name as 'FirstName',salary as 'sal' from emp;

Inserting NULL values in the table: Suppose you do not want to enter salary of certain employee then follow this query- Insert into emp(sno,name,address,DOB) values (8, ‘xyz’,‘abc’, ‘1991-2-2’); Note: Here we break down the above query into two, firstly we have taken the entire columns name where value has to be passed and secondly in a bracket we passed the values accordingly to the columns taken in first bracket. The salary column is not taken in the first bracket so the value of salary had not been passed where we will see NULL automatically appear in that place for this record.

‘Where’ clause: In MySQL ‘where’ clause is used to filter the record. We can use relational operators according to our need to filter the records from table.

Display all the records from emp table whose address is ‘gomtinagar’.

All the headings are temporary gets changed

Page 25: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 13

Display the name of those employees whose salary is less than 30000;

Display the name and salary of those employees whose address either is gomtinagar or nishatganj.

Range Based searching: There are ‘Between’ and ‘Not Between’ clause used for ranged based searching.

a) Between clause: It will search the range including starting and endpoint. b) Not Between clause: It will search the range excluding starting and ending

point passed in the query. Q. Display name and salary of those employees whose salary are greater than or equals to 10000 and less than or equals to 30000.

Page 26: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 14

Note: the above query can also be solved by using the logical operator ‘and’ in the following way:

Q. Display name and salary of those employees whose salary should not be in the range of 10000 to 30000.

Pattern Searching: Pattern searching is used to search several texts with starting or ending characters of words. There are two special characters use in pattern searching, ‘%’( modulo sign) and ‘_’ (underscore symbol). % sign search for the sub string whereas _ symbol is used for exact searching of characters. Let’s have an example for this:- Q. Display the name of those employees who are having the character ‘u’ at the end of their name.

Page 27: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 15

Q. Display the name and salary of those employees whose name starts with ‘h’.

Q. Display the name of those employees who are having character ‘a’ as their fourth character.

Note: In the above query for searching fourth character as ‘a’ , we had used 3 underscores symbol ‘_’ and after that any characters can be there in the name so ‘%’ symbol has been used. Conditional Searching: We will use ‘IN’ and ‘NOT IN’ clause for conditional searching. Conditional searching search just like ‘OR’ logical operator, means any of the condition holds true it will return some output. Let’s have an example- Q. Display name and address of those employees who either belongs to alambagh, gomtinagar or rajajipuram.

Page 28: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 16

Q. Display name and address of those employees whose address is not alambagh, gomtinagar or rajajipuram.

IS NULL CLAUSE: This clause is used to search NULL records in a table. As we had already inserted a null record in the original table as given below:

Now we will have a demonstration of ‘is null’ clause on this table:- Q. Display name, salary and address of those employees where salary is blank or not given.

IS NOT NULL CLAUSE: It will search all those values where NULL record is not found, means all the value will be filled in that column. Q. Display name, salary and address of those employees where salary is not blank.

Page 29: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 17

Note: In salary column there is no blank or NULL record has been extracted this time. ORDER BY CLAUSE: ‘Order by’ clause is used to arrange a column’s record either in ascending or in descending order. By default it will arrange the records in ascending order. Q. Display name and salary of the employees according to their name in ascending order.

Q. Display name and salary of the employees according to their name in descending order.

Note: ‘desc’ keyword is used after column name in order to arrange the records of name column in descending order.

Page 30: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 18

Multiple choice questions

Q1. Which of the following are not valid data types of MySQL? a) char b) String c) char d) DOB Ans: b and d Q2. Identify the DDL command from the following? a) commit b) insert c) select d) create Ans: d Q3. Which symbol is used for exact pattern searching of a string? a) % b) _ c) $ d) @ Ans: b Q4. Which clause is used to edit text where ever NULL record is found? a) NULL b) NOT NULL c) IS NULL d) IFNULL Ans: d Q5. Which is the valid comment according to MySQL platform? a) comment b)<!--> c) /*….*/ d) // Ans: c Q6. Degree of the table means number of ____ of the table? a) rows b) columns c) rows*column d) rows+columns Ans: b

Assignment for students Q1. Differentiate between char and varchar data types. Q2. Differentiate between DDL and DML commands. Q3. Write SQL query to create a table ‘Inventory’ with the following structure:

Page 31: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 19

Q4. Consider the following table ‘Furniture’. Write SQL commands for the statements (i)

to (vi) and write output for SQL queries (vii) .

Table : Furniture

i) To display FCODE ,NAME and PRICE of items that have PRICE less than 5,000. ii) To display NAMES and PRICE of those Furniture Items that have ‘table’ anywhere in their names. iii)To display WCODE of Furniture Items. There should be no duplicate values. iv)To display the NAMES and PRICE increased by 500.00 of all the furniture items. (Price should only be displayed as increased; there should be no increase in the data in the table) v) To display FCODE and NAME of each Furniture Item in descending order of FCODE. vi) To display the details of all the Furniture Items which have Manufacturing date( MANUFDATE ) between 01-JAN-2016 and 15-JUN-2017 (inclusive of both the dates). vii) Select name from furniture where name like ‘_ _ _ i%’; Q6. A table ‘Gym’ has 7 rows and 17 columns.5 rows added to this table and 5 columns were deleted from this table. What is the cardinality and degree of this table now? Q7. What is the purpose of SQL? Q8. Mr. Manav, a database administrator in “Global Educational and Training Institute” has created following table named “Training” for the upcoming training schedule:

Training

Page 32: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 20

Help him in writing SQL query for the following purpose: i. To display name of female candidates who are attending the training. ii. To display list of free trainings. iii. To display all the cities where Cyber Security training is scheduled along with its fee. Observe the table named “Training” given above carefully and predict the output of the following queries: iv. select city from training where topic = 'Cyber Security'; v. select name from training where email_id like '%gmail% '; vi. What is the degree and cardinality of the above given table named ‘Training’. Q9. Consider the following tables Library given below:

Library

i. Suggest the suitable data type for Issue_Date column. ii. Mention the significance of Bid column in table Library. iii. Suggest the suitable command to display a list of the books in a sequence so that first all the book’s name should be displayed which has been returned and after that all the book’s name which has not been returned should be displayed. Q10. Write SQL query to create a table “BOOKS” with the following structure:

Table: BOOKS

Page 33: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 21

Q11. Write the full forms of the following:

i. DDL ii. DML Q12. Archana, a class XI student has just started learning MySQL. Suggest her suitable command for the following purpose: i. To display the list of the databases already existing in MySQL. ii. To use the database named City. iii. To create a table named city. iv. To display the columns of city table.

xxxxxx

GROUPING RECORDS & TABLE JOINS.

Functions in My Sql:- MySql provides 2 types of functions which are listed below.

Page 34: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 22

1. Scalar/ Single row functions:- functions which work on a single row at a time,

called Single Row Functions. It returns result for every row of a queried table.

Example: length(), upper(), left(), instr() etc.

2. Aggregate/ Multiple row functions:- functions which work on more than one

row at a time, called Multiple Row Functions. It returns aggregated values.

Example: count(), max(), min(), average(), sum().

NOTE: While performing aggregate operations no other columns can be

selected except the column on which the operation is being performed.

Table :Marks

The above given table

will be used in following Sql Statement.

a. AVG():- It returns average of the given data as numeric parameter.

Example :- Select avg (hindi) from marks;

Output : 66

b. MAX():- It returns maximum value from a given column of a table.

Example :- Select max (english) from marks;

Output : 93

c. MIN():- It returns minimum value from a given column of a table.

Example :- Select max (maths) from marks;

Output : 69

d. SUM():- It returns the sum of values in given column.

Example :- Select sum (hindi) from marks;

Output : 330

SRNo Maths Hindi English

5439 85 70 93

77 60 67

3645 83 80 87

7553 69 60 84

3439 87 70 89

Page 35: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 23

e. COUNT():- It counts the number of rows in a given column or of the given

table..

Example :-

i. Select count (*) from marks;

The above mentioned query returns the total number of row or

tupples of table.

Output : 5

ii. Select count (srno) from marks;

The above mentioned query returns the total number of values

presented in column SRNO. It does not count the null.

Output : 4

iii. Select count (distinct hindi) from marks;

The above mentioned query returns 3 as output because distinct

keyword ensures that multiple entries of the same marks are

ignored.

Output : 3

Distinct :- it is used to eliminate the redundant data of mentioned column/

field of a table.

Example:- Select distinct (hindi) from marks;

Output :-

GROUPING RESULT – GROYP BY

Group by clause combines all those records that have identical values in

a particular field or a group of fields.

When we use any aggregate function on a table, it returns a single row and

column containing the result of used aggregate function. Many a times we need

to calculate some values in groups based on some columns i.e. we want to create

groups based on some column values and then to perform aggregate operations

separately on each group. i.g. in a table Student(SRNo, Name, Class, FeesPaid)

Hindi

70

80

60

Page 36: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 24

if we need to find out the total of fees paid by each class, we need to create

groups on columns class i.e. all records for a particular class will be kept in a

single group by using GROUP BY clause and then the total of this group will be

find out. As many groups will be used here as many class values are there in

table. So the result of this type of select statement will give us as many rows in

result as many class values are there in the table. Simply we will find out the class

wise total of FeesPaid column.

NOTE:

1. When using GROUP BY clause we can include the group column with the

select statement.

2.

2. GROUP BY clause can only be used if any aggregate function is being used in

select statement.

Table 1.1 : - STUDENT

SRNo Roll

No

Name Class Feespaid

5439 12105 Ajay 12 5000

6345 12110 Bharat 12 2000

3645 11230 Nitin 11 5000

7553 10323 Manisha 10 2000

2434 9134 Rajesh 11 5000

Example 1:-

Find the total of fees paid by each class from STUDENT Table given above.

Answer:

SELECT SUM (FEESPAID), CLASS FROM STUDENTS

Page 37: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 25

GROUP BY CLASS;

Output :-

Feespai

d

Class

2000 10

10000 11

7000 12

Example 2:-

Give the output of the following query.

SELECT CLASS, COUNT (FEESPAID), NAME FROM STUDENTS

GROUP BY CLASS;

Output :-

Class Count(feespai

d)

Name

Example 3:-

Find the total no. Of students of each class from STUDENT Table given above.

SELECT COUNT (*), CLASS FROM STUDENTS

GROUP BY CLASS;

Output :-

Page 38: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 26

Count(*

)

Class

1 10

2 11

2 12

Unsolved Question:-

1. Find the maximum fees paid by each class from STUDENT Table given above. 2. Find the minimum fees paid by each class from STUDENT Table given above. 3. Find the paid average fees of each class from STUDENT Table given above.

Having Clause:-

It is used to place the condition on groups of values of a column. Having clause can include the aggregate functions. Whereas WHERE clause is used to restrict in a query i.e. it is used to place the conditions on individual rows.

NOTE: HAVING clause can only be used if a GROUP BY clause is used.

Example:

(if we want to find out the classes for which total fees collection is more than Rs. 10000.00)

SELECT SUM(FEESPAID), CLASS FROM STUDENTS

Group By Class

Having SUM(FEESPAID)>10000;

DISPLAYING DATA FROM MULTIPLE TABLES

In real world the data of an organisation is kept in different tables based on its nature (that is studied under data modelling). When the data is scattered around many tables one may need to select the data for a particular query from more than one table so that a single table result can be generated.

Data from multiple tables can be selected after joining the tables. SQL SELECT statement is also used for combining data from more than one table. When we combine the data from more than one table, this is called joining of tables.

Page 39: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 27

JOIN: A join is a query that combines rows from two or more tables. In a join query, more than one table is listed in FROM clause.

TABLE - STUDENT

SRNo Roll

No

Name Class Section AvgMarks

5439 12105 Ajay 12 A 83.66

6345 12110 Bharat 12 A 69.67

3645 11230 Nitin 11 B 84

7553 10323 Manisha 10 C 73

2434 9134 Rajesh 9 A

Marks Table

Suppose we run following query on these tables:

SELECT

Student.*, Marks.* From

Student, Marks;

The result will be a single tabular structure that will contain all the columns from both the tables and all the possible combination of records from both the tables (This is the Cross Join or unrestricted join or Cartesian product of tables).

QUALIFIED NAMES:

Qualified name are useful in indentifying a field if the two joining tables have fields with same name.

<tablename>.<fieldname>

Select dept.dno, empl.dno from dept, empl;

TABLE ALIASES:- A table Alias is a temporary label given along with table name in FROM clause. It is used to cut down on the amount of typing required in the SQL queries.

SRNo Maths Hindi English

5439 85 73 93

6345 77 65 67

3645 83 82 87

7553 69 66 84

3439 87 76 89

Page 40: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 28

CROSS JOIN OR CARTESIAN PRODUCT:- It is a very basic type of join that simply matches each row from one table to every row from another table. It returns multiplied rows and added columns of both tables which specified in from clause.

But when a record of SR No 5439 (Ajay) from Students table is combined with a record of SR No 7553 (i.e. Manisha in students table),it makes no sense. Hence some extra condition with SELECT statement using where clause is specified:

SELECT Student.*, Marks.*

From Students, Marks

Where Students.SRNO = Marks.SRNo;

Give the output of the above query.

This will give only meaningful combinations of records from both tables.

Here we can easily understand that when multiple tables are joined they must have some column common in them and in select clause we can put an equality check with where clause to filter only a meaningful combination of records, called EQUI JOIN.

NON EQUI JOIN:- A non equi join is a query that specifies some relationship other than equality between the columns.

SELECT Student.*, Marks.*

From Students, Marks

Where avgmarks > English -------> (NON EQUI JOIN)

Give the output of the above query.

Page 41: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 29

NATURAL JOIN:- A non equi join is a query that gives the result as equi join but one of the identical columns get removed from output.

SELECT Student.*, Marks.* From Students natural join Marks;

Give the output of the above query.

JOINING MORE THAN ONE TABLES USING JOIN CLAUSE:

JOIN CLAUSE: It gives Cartesian product of 2 tables.

Example:- select * from student join marks;

NOTE:- With the help of JOIN clause equi and natural join can be also performed by using ON and USING sub clause.

Select * from student join marks on (student.srno = marks.srno) Above mentioned query produces EQUI JOIN.

Select * from student join marks using(srno);

Above mentioned query produces NATURAL JOIN.

NOTE:- Always remember that name of the columns must be same in both table when want to perform NATURAL JOIN with JOIN clause by using “USING” sub clause.

LEFT JOIN: It returns all the rows from the first table whether there are matches in the second table or not. Unmatched rows of first table, NULL is shown in columns of second table.

TABLE – EMPL

Page 42: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 30

TABLE – DEPT

Example :-

select dept.*, ename, mgr from dept left join empl on

dept.deptno = emp.deptno;

OUTPUT :-

Page 43: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 31

RIGHT JOIN: It returns all the rows from the second table whether there are matches in the first table or not. Unmatched rows of first table, NULL is shown in columns of second table.

Example :-

select dept.*, ename, mgr from dept right join empl on

dept.deptno = emp.deptno;

INTEGRITY CONSTRAINTS

1. In MySQL CONSTRAINT is used to define rules to allow or restrict what values can be

stored in columns (fields). The purpose of inducing constraints is to enforce the

integrity of a database.

2. MySQL CONSTRAINTS can be classified into two types –

Column Level Constraints

The column level constraints can apply only to one column. E.g. CHECK, NOT

NULL, UNIQUE.

Table Level Constraints

The table level constraints are applied to the entire table.

Page 44: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 32

Page 45: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 33

3. MySQL CONSTRAINTs are :

a. PRIMARY KEY

A PRIMARY KEY constraint for a table enforces the table to accept unique

data and NOT NULL for a specific column.

It can be applied only once in a table.

Example 1: When table has single field primary key it can be defined at Column

level.

CREATE TABLE author

(aut_id varchar(8) PRIMARY KEY,

aut_name varchar(50) NOT NULL,

country varchar(25) NOT NULL);

Example 2: when table has multiple field primary key(composite key)

CREATE TABLE author

(aut_name varchar(50) NOT NULL,

mobile_no int(10) NOT NULL,

country varchar(25) NOT NULL,

PRIMARY KEY(auth_name, mobile_no));

b. NOT NULL

NOT NULL constraint allows to specify that a column can not contain any NULL

value (cannot be left blank/entry in the field is must).

c. UNIQUE

The UNIQUE constraint does not allow inserting a duplicate value in a

column.

More than one UNIQUE column may be defined in a table.

d. FOREIGN KEY

A FOREIGN KEY in MySQL creates a link between two tables by one specific

column of both tables.

The specified column in one table must be a PRIMARY KEY and referred

by the column of another table known as FOREIGN KEY.

Example 1:

Page 46: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 34

CREATE TABLE book_master

( book_id varchar(15) PRIMARY KEY,

book_name varchar(50) UNIQUE,

isbn_no varchar(15) UNIQUE,

cate_id varchar(8),

aut_id varchar(8),

pub_id varchar(8),

FOREIGN KEY(aut_id) REFERENCES author(aut_id));

e. DEFAULT

In a MySQL table, while inserting data into a table, if no value is

supplied to a column, then the column gets the value set as DEFAULT.

f. CHECK

Adding a CHECK CONSTRAINT on a column of a table, you can limit the

range of values allowed to be stored in that column.

Using IN operator

IN operator only accepts a value from a given list.

Using LIKE operator

LIKE operator allows entering a value matching with given pattern.

Using AND(&) and OR operator

AND and OR operators allow us to join two or more conditions and

returns true or false.

Example :

CREATE TABLE author

(aut_id varchar(8) PRIMARYKEY,

aut_name varchar(50) NOT NULL,

country varchar(25) NOT NULL,

home_city varchar(25) DEFAULT 'New Delhi',

Amt_paid decimal(7,2) CHECK(Amt_paid>5000 AND Amt_paid<50000),

DOB date NOT NULL,

);

4. Alter table command

Page 47: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 35

Sometimes we need to make changes in the definitions of existing table, and then

we use ALTER TABLE command.

ALTER TABLE command can be used many things, such as :

Adding columns to the table

Modifying column definitions of a table(changing data types of existing fields of

table)

Deleting columns of a table

Adding constraints to table

Enabling/disabling constraints

Deleting table from database

4.1. Adding columns to table

It is used to add a new field in an existing table.

ALTER TABLE empl ADD local_addr varchar(50) not null;

//adds 1 field

ALTER TABLE empl ADD( city varchar(30) not null, inc_name varchar(20) ); // adds

2 fields

4.2. Modifying column definition with MODIFY and CHANGE

Using MODIFY clause we can only change data type or constraint of column but

not the name of column.

Example 1: change the size of field ename from 30 to 40 and apply not

null.

ALTER TABLE empl

MODIFY ename varchar(40) NOT NULL;

Using CHANGE/RENAME clause column name need to be written twice, it can be

used to rename column.

Example 2: change the size of ename from 30 to 40.

ALTER TABLE empl

CHANGE ename ename varchar(40) NOT NULL;

Example 3: change the size of ename from 30 to 40 and rename ename to

ename1.

Page 48: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 36

ALTER TABLE empl

CHANGE ename ename1 varchar(40) NOT NULL;

4.3. Deleting columns of table

DROP COLUMN clause is used to remove a field from table definition along with

its data.

ALTER TABLE empl

DROP COLUMN ename; // this will remove ename field from

table empl

4.4. Adding constraints in table

ADD CONSTRAINT/ADD clause is used to add a constraint on field/table.

Example 1:

ALTER TABLE empl

ADD PRIMARY KEY(EMPNO); // this will make EMPNO field primary

key

Example 2:

ALTER TABLE empl

ADD CONSTRAINT pk1 PRIMARY KEY(EMPNO);

4.5. Removing constraints from table

DROP clause is used to remove a constraint from field/table.

Example 1:

ALTER TABLE empl

DROP PRIMARY KEY(EMPNO); // this will remove primary key from

EMPNO field

Example 2:

ALTER TABLE empl

DROP PRIMARY KEY pk1; // this will remove primary key from

EMPNO field

Very Short solved questions

Write SQL command for following:

1. To view the constraints of EMP table.

Ans. Show create table EMP;

2. To display the structure of table EMP.

Ans. Desc EMP;

3. To delete table emp_sal_detail

Ans. Drop table emp_sal_detail;

4. To delete a field contact2 from table EMP.

Page 49: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 37

Ans. ALTER TABLE EMP DROP COLUMN CONTACT2;

5. To change size of field ENAME from varchar(10) to varchar(30).

Ans. ALTER TABLE EMP MODIFY ENAME VARCHAR(30);

6. Name the Integrity term that following constraint implement-

(A) NOT NULL (B) PRIMARY KEY (C) FOREIGN KEY

Ans. (A) NOT NULL implements Domain Integrity.

(B) PRIMARY KEY implements Entity Integrity.

(C) FOREIGN KEY implements Referential Integrity.

Short questions

1. What do you mean by Integrity constraint?

2. Differentiate between PRIMARY KEY and FOREIGN KEY.

3. Differentiate between PRIMARY KEY and UNIQUE constraint.

4. Differentiate between PRIMARY KEY and NOT NULL constraint.

5. What do you call a multi-field PRIMARY KEY?

6. Differentiate between ALTER and DELETE commands in MySQL.

7. Differentiate between CASCADE and RESTRICT used in MySQL.

Long questions

1. Write a SQL statement to create a simple table countries including columns

country_id, country_name and region_id where entry in all fields is compulsory

and country_id should be unique and not null.

Ans. CREATE TABLE countries(

COUNTRY_ID varchar(2) primary key, COUNTRY_NAME varchar(40) not null, REGION_ID decimal(10,0) not null);

2. Write SQL commands to create given tables and also answer the given questions-

Table : TEST

TESTID TESTNAME COST

T101 Platelet count 200

T102 Hemoglobin 190

T301 Malaria 350

T502 Blood sugar 150

Table : PATIENT

PCODE NAME PHONE TDATE TESTID

6425 THAKU

R

9425695566 19-06-2016 T102

7546 JAY 8885654566 18-07-2015 T101

Page 50: LUCKNOW PUBLIC SCHOOLgomtinagar.thelps.edu.in/UploadedFiles/...XII_CS.pdf · Step involved in minterm expansion of Expression 1. First convert the given expression in sum of product

Relational Databases Page 38

i.

ii.

iii.

iv.

v.

vi.

i. Name primary key fields of both tables.

ii. Which one is foreign key in the given table?

iii. Write datatypes of COST and TDATE.

iv. What check can be applied on field COST?

v. What should be the size and type of PCODE and TESTID?

vi. Write SQL query to increase the COST of all tests by 50%.

vii. Write SQL query to display patient name got tested for “HEMOGLOBIN”.

viii. DELETE record of all patients got testes before year 2016.

5789 BEERU 9415094150 20-09-2016 T102

7766 KALIA 8111456365 31-01-2017 T502

7489 GABBA

R

9839012546 12-02-2016 T301