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

Class XII-UNIT III - SQL and MySQL Notes_0 (1)

COMPUTER CLASS 12

Uploaded by

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

Class XII-UNIT III - SQL and MySQL Notes_0 (1)

COMPUTER CLASS 12

Uploaded by

aalokvr25872
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter 15

ADDING/REMOVING CONSTRAINTS TO A TABLE


ALTER TABLE statement can be used to add constraints to your existing table by using it in following manner:


TO ADD PRIMARY KEY CONSTRAINT
ALTER TABLE <table name>
ADD PRIMARY KEY (Column name);

e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command is :
ALTER TABLE EMPLOYEE
ADD PRIMARY KEY (ECODE) ;

TO ADD FOREIGN KEY CONSTRAINT

ALTER TABLE <table name>


ADD FOREIGN KEY (Column name) REFERENCES Parent Table (Primary key of Parent Table);

REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP PRIMARY KEY ;
- To remove foreign key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP FOREIGN KEY ;

ENABLING/DISABLING CONSTRAINTS
Only foreign key can be disabled/enabled in MySQL.
To disable foreign keys : SET FOREIGN_KEY_CHECKS = 0 ;
To enable foreign keys : SET FOREIGN_KEY_CHECKS = 1 ;

INTEGRITY CONSTRAINTS/CONSTRAINTS
- A constraint is a condition or check applicable on a field(column) or set of fields(columns).
- Common types of constraints include :

S.No. Constraints Description


1 NOT NULL Ensures that a column cannot have NULL value
2 DEFAULT Provides a default value for a column when none is specified
3 UNIQUE Ensures that all values in a column are different
4 CHECK Makes sure that all values in a column satisfy certain criteria
5 PRIMARY KEY Used to uniquely identify a row in the table
6 FOREIGN KEY Used to ensure referential integrity of the data

NOT NULL CONSTRAINT


By default, a column can hold NULL. It you not want to allow NULL value in a column, then NOT NULL constraint
must be applied on that column. E.g.

CREATE TABLE Customer


( SID integer NOT NULL ,
Last_Name varchar(30) NOT NULL ,
First_Name varchar(30) );
Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.

An attempt to execute the following SQL statement,


INSERT INTO Customer
VALUES (NULL , ‘Kumar’ , ‘Ajay’);
will result in an error because this will lead to column SID being NULL, which violates the NOT NULL constraint
on that column.

DEFAULT CONSTARINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not
provide a specific value. E.g.

CREATE TABLE Student


( Student_ID integer ,
Name varchar(30) ,
Score integer DEFAULT 80);

When following SQL statement is executed on table created above:


INSERT INTO Student
no value has been provided for score field.
VALUES (10 , ‘Ravi’ );

Then table Student looks like the following:

Student_ID Name Score


10 Ravi 80 score field has got the default value

UNIQUE CONSTRAINT
- The UNIQUE constraint ensures that all values in a column are distinct. In other words, no two rows can
hold the same value for a column with UNIQUE constraint.

e.g.
CREATE TABLE Customer
( SID integer Unique ,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;

Column SID has a unique constraint, and hence cannot include duplicate values. So, if the table already
contains the following rows :

SID Last_Name First_Name


1 Kumar Ravi
2 Sharma Ajay
3 Devi Raj

The executing the following SQL statement,


INSERT INTO Customer
VALUES (‘3’ , ‘Cyrus‘ , ‘Grace’) ;
will result in an error because the value 3 already exist in the SID column, thus trying to insert another row
with that value violates the UNIQUE constraint.

CHECK CONSTRAINT
- The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the table will
only insert a new row or update an existing row if the new value satisfies the CHECK constraint.

e.g.
CREATE TABLE Customer
( SID integer CHECK (SID > 0),
Last_Name varchar(30) ,
First_Name varchar(30) ) ;

So, attempting to execute the following statement :


INSERT INTO Customer
VALUES (-2 , ‘Kapoor’ , ‘Raj’);

will result in an error because the values for SID must be greater than 0.

PRIMARY KEY CONSTRAINT


- A primary key is used to identify each row in a table. A primary key can consist of one or more fields(column)
on a table. When multiple fields are used as a primary key, they are called a composite key.

- You can define a primary key in CREATE TABLE command through keywords PRIMARY KEY. e.g.

CREATE TABLE Customer


( SID integer NOT NULL PRIMARY KEY,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;

Or

CREATE TABLE Customer


( SID integer,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (SID) ) ;

- The latter way is useful if you want to specify a composite primary key, e.g.

CREATE TABLE Customer


( Branch integer NOT NULL,
SID integer NOT NULL ,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (Branch , SID) ) ;

FOREIGN KEY CONSTRAINT


- Foreign key is a non key column of a table (child table) that draws its values from primary key of another
table(parent table).
- The table in which a foreign key is defined is called a referencing table or child table. A table to which a
foreign key points is called referenced table or parent table.

e.g.
Parent Table
TABLE: STUDENT
ROLL_NO NAME CLASS
Primary key
1 ABC XI
2 DEF XII
3 XYZ XI Child Table
TABLE: SCORE
ROLL_NO MARKS
1 55
2 83
3 90

Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its values from
Primary key (ROLL_NO) of STUDENT table.(Parent Key).

CREATE TABLE STUDENT


( ROLL_NO integer NOT NULL PRIMARY KEY ,
NAME VARCHAR(30) ,
CLASS VARCHAR(3) );

CREATE TABLE SCORE


( ROLL_NO integer ,
MARKS integer ,
FOREIGN KEY(ROLL_NO) REFERNCES STUDENT(ROLL_NO) ) ;

* Foreign key is always defined in the child table.

Syntax for using foreign key


FOREIGN KEY(column name) REFERENCES Parent_Table(PK of Parent Table);

Q: Create two tables


Customer(customer_id, name)
Customer_sales(transaction_id, amount , customer_id)
Underlined columns indicate primary keys and bold column names indicate foreign key.
Make sure that no action should take place in case of a DELETE or UPDATE in the parent table.

Sol : CREATE TABLE Customer (


customer_id int Not Null Primary Key ,
name varchar(30) ) ;

CREATE TABLE Customer_sales (


transaction_id Not Null Primary Key ,
amount int ,
customer_id int ,
FOREIGN KEY(customer_id) REFERENCES Customer (customer_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION );

Q: Distinguish between a Primary Key and a Unique key in a table.


S.NO. PRIMARY KEY UNIQUE KEY
1. Column having Primary key can’t contain Column having Unique Key can contain
NULL value NULL value
2. There can be only one primary key in Table. Many columns can be defined as Unique key

GROUPING RESULT – GROUP BY


The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a
group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
value for each group.
Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20

e.g. Calculate the number of employees in each grade.


SELECT JOB, COUNT(*)
FROM EMPL
GROUP BY JOB ;
Output
JOB COUNT(*)
CLERK 1
SALESMAN 2
MANAGER 1

e.g.2. Calculate the sum of salary for each department.


SELECT DEPTNO , SUM(SAL)
FROM EMPL
GROUP BY DEPTNO ;
Output
DEPTNO SUM(SAL)
10 2985
20 15513
30 8760
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiple fields in the GROUP BY
expression. e.g. To group records job wise within Deptno wise, you need to issue a query statement like :
SELECT DEPTNO , JOB , COUNT(EMPNO)
FROM EMPL
GROUP BY DEPTNO , JOB ;
Output
DEPTNO JOB COUNT(EMPNO)
10 CLERK 1
20 SALESMAN 1
20 MANAGER 1
30 SALESMAN 1

PLACING CONDITION ON GROUPS – HAVING CLAUSE


- The HAVING clause places conditions on groups in contrast to WHERE clause that places condition on individual
rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can do so.
- e.g. To display the jobs where the number of employees is less than 2,
SELECT JOB, COUNT(*)
FROM EMPL
GROUP BY JOB
HAVING COUNT(*) < 2 ;
Output
JOB COUNT(*)
CLERK 1
MANAGER 1
Join :- Join is a query that combines rows from two or more tables.

You might also like