Xii Dbms SQL Notes
Xii Dbms SQL Notes
Data :- Raw facts and figures which are useful to an organization. We cannot take
decisions on the basis of data.
Information:- Well processed data is called information. We can take decisions on the
basis of information
Field:
Set of characters that represents specific data element.
Record:-
Collection of fields is called a record. A record can have fields of different data types
.File:
Collection of similar types of records is called a file.
Table:
Collection of rows and columns that contains useful data/information is called a
table. A table generally refers to the passive entity which is kept in secondary
storage device.
Relation: Relation (collection of rows and columns) generally refers to an active
entity on which we can perform various operations.
Database: Collection of logically related data along with its description is termed as
database.
Tuple:
A row in a relation is called a tuple.
Attribute:
A column in a relation is called an attribute. It is also termed as field or data item.
Degree:
Number of attributes in a relation is called degree of a relation.
Cardinality: Number of tuples in a relation is called cardinality of a relation.
Domain
A domain is a set of all unique values permitted for an attribute.
Ex. A domain of day_of_week is Monday,Tuesday………….Saturday.
Database schema.
It is the logical design of a database.
It is the skeleton of a database that represents the structure of the database
(table names,column names),data types of the columns,constraints applied on
the columns and the relationships among the tables.
2
Database schema is a visual or logical architecture that tells how the data are
organized in a database.
Primary Key: Primary key is a field in a table which can uniquely identifies each record/tuple
in a relation.
Primary key must contain unique values.
A primary key column can not have null values.
A table can have only one primary key which may consists of single or mulutiple fields.
Foreign Key: Foreign Key is a key that is defined as a primary key in some other relation. This
key is used to enforce referential integrity in RDBMS.
Candidate Key: Set of all attributes which can serve as a primary key in a relation.
Alternate Key: All the candidate keys other than the primary keys of a relation are alternate
keys for a relation.
DBA: Data Base Administrator is a person (manager) that is responsible for defining
the data base schema, setting security features in database, ensuring proper
functioning of the data bases etc.
Data types of SOL
Just like any other programming language, the facility of defining data of various types
is available in SQL also. Following are the most common data types of SQL.
1) NUMERIC 2) CHAR 3) VARCHAR/VARCHAR2 4) DATE 5) LONG 6) RAW/LONG RAW
1. NUMERIC
it is Used to store a numeric value in a field column. It may be decimal, integer or a
real number .
General syntax NUMERIC (n.d),
Where n specifies the number of digits and d specifies the number of digits to the right
of the decimal point. eg marks numeric(3) declares marks to be of type numeric with
maximum value 999.
2. CHAR
It is Used to store character type data in a column. General syntax is Char (size)
where size represents the maximum number of characters in a column. The CHAR type
data can hold at most 255 characters. Eg. name char(25) declares a data item name of
type character of upto 25 size long.
3 . VARCHAR/VARCHAR2
This data type is used to store variable length alphanumeric data.
General syntax is varchar(size) /varchar2 (size) where size represents the
maximum number of characters in a column.
The maximum allowed size in this data type is 2000 characters.but the actual
allocated bytes will depend on the entered string. eg city varchar(50) , if the
entered city is Jaipur than it will occupy 6 bytes in memory.
3
4. DATE
Date data type is used to store dates in columns. SQL supports the various date
formats other that the standard DD-MON-YY. eg dob date; declares dob to be of
type date
SQL can be divided in three languages.
1. Data Definition Language (DDL)
DDL contains commands that are used to create and drop the tables, databases,
indexes, views, sequences and synonyms etc. eg. Create table, create view, create
index, alter table etc.
2. Data Manipulation Language (DML)
DML contains command that can be used to manipulate the data base objects and to
query the databases for information retrieval. Eg.
Select, Insert, Delete, Update etc.
3. Data Control Language:
This language is used for controlling the access to the data. Various commands.
. like GRANT,REVOKE etc are available in DCL
4. Transaction Control Language (TCL)
TCL include commands to control the transactions in a data base system. The
commonly used commands in TCL are COMMIT, ROLLBACK etc.
Eg.
Create table student
(rollno number(2),
sname varchar2(20),
class char(5),
age int);
A database may have multiple tables in it. To know the list of tables in a database , we can use
‘show tables’ statement.
Show tables;
Tables_in_school
student
teacher
marks
fees
Alter table
After creating a table , we can add and remove columns in table,modify the data type of an
existing column and add constraint on column.
Add primary key to a relation
syntax
Alter table table_name
add primary key(column_name);
eg. Alter table student add primary key(rollno);
Dropping a database
To delete a database , we use drop database statement.
Syntax:-
Drop database database_name;
Eg. Drop database school;
Dropping a table
To delete a table from the database , we use drop table statement.
Syntax:
Drop table table_name;
Eg. Drop table student;
Adding an column to an existing table.
to add an attribute in a relation we use add column statement.
Syntax:
Alter table table_name
add column column_name data type;
eg: alter table guardian add income int;
we can add multiple columns in a table using the following syntax.
Alter table table_name
add column column_name1 data type, column_name2 data type………… column_name n
data type;
eg :
alter table student add column age int ,dob date;
6
Constraints: Constraints are the conditions that can be enforced on the attributes of a relation.
The constraints come in play when ever we try to insert, delete
or update a record in a relation. They are used to ensure integrity of a relation, hence named
as integrity constraints.
1. NOT NULL 2. UNIQUE
3. PRIMARY KEY 4. FOREIGN KEY 5. CHECK 6. DEFAULT
Not Null constraint: It ensures that the column cannot contain a NULL value. This enforces a
column to always contain a value, which means that you can not insert a new record without
adding a value to this column.By default a column can hold null values.
Alter table student
Modify age int not null;
Unique constraint: the unique constraint ensures that all values in a column are different . we
can have many unique constraints in a table.
Alter table student
add unique(mob_no);
default constraint
syntax: alter table table_name modify column_name data type default default_value;
eg: alter table employee
modify sal int default 10000;
Primary Key :A primary key is a column in a table which uniquely identifies each row in a
database table. Primary key must contain unique values. A primary key column can not have
null values.
A table can have only one primary key,which may consist of single or multiple columns.
When multiple columns are used as a primary key,they are called a composite key.
7
Eg.
Create table student
( rollno int primary key,
Sname char(20),
Class char(5),
Age int);
syntax
Alter table table_name
add primary key(column_name);
eg. Alter table student add primary key(rollno);
Here is the syntax to define the ID attribute as a primary key in a CUSTOMERS table.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Syntax:
Alter table table_name drop primary key;
Ex: Alter table student drop primary key;
Foreign Key :
The foreign key is used to represent the relationship between two relations.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to
the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
To create a foreign key ,at least one column must be common in parent and child
table. In the parent table it is created as a primary key and in the child table it is
created as a foreign key.
8
If we delete any record from parent table , related records are automatically
deleted from child table.
references referenced_table_name(column_name)
Consider two tables Student and marks having their respective attributes as shown in the
below table structure:
student
Marks
Ex
In the tables, one attribute, you can see, is common, that is Rollno but it has different key
constraints for both tables.
In the Student table, the field Rollno is a primary key because it is uniquely identifying all
other fields of the Student table.
On the other hand, Rollno is a foreign key attribute for the Marks table because it is acting
as a primary key attribute for the Student table. It means that both the Student and Marks
table are linked with one another because of the Rollno attribute.
In the below-shown figure, you can view the following structure of the relationship
between the two tables.
Note: Referential Integrity in DBMS is developed from the concept of the foreign key. It is
clear that a primary key is an alone existing key and a foreign key always reference to a
primary key in some other table, in which the table that contains the primary key is known as
the referenced table or parent table for the other table that is having the foreign key.
So, in this way, we can set a foreign key for a table in the MYSQL database.
If you define a CHECK constraint on a column it will allow only certain values
for this column.
10
If you define a CHECK constraint on a table it can limit the values in certain
columns based on values in other columns in the row.
MySQL:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
MySQL:
IN operator:-
The ‘IN’ operator checks a value within a set of values separated by commas and
retrieve the rows from the table which are matching.
Ex. Select * from student
where rollno in(1201,1203);
Rollno Sname Class Age Marks
1201 Ram XIII 18 85
1203 sunil XII 19 70
Distinct clause
The select distinct statement is used to return only distinct(different) values from a
column.
Inside a table ,a column often contains many duplicate values . if we want to list the
different values ,then we can use the distinct statement.
Syntax:-
Select distinct column1,column2…………….column n
from table_name;
department
Id Name Department
101 Ram Sales
12
Select distinct(department)
from department;
department
Sales
finance
It does not deal with changes to database objects and its structure. The commonly known
DML commands are INSERT, UPDATE and DELETE,SELECT.
Command Description
INSERT Used to insert new data records or rows in the database tab
DELETE Used to remove one or more rows from the database table
Commands of DML
Now let us try to understand each of the above mentioned DML commands in detail one by
one.
1. INSERT
13
INSERT commands in SQL are used to insert data records or rows in a database table. In
an INSERT statement, we specify both the column_names for which the entry has to be
made along with the data value that has to be inserted.
Here we have tried to insert a new row in the student table using the INSERT
command. The query accepts two sets of arguments, namely field names or column names and
their corresponding values.
Suppose if we have to insert values into all the fields of the database table, then we need not
specify the column names, unlike the previous query. Follow the following query for further
illustration.
Student
In this example, we have successfully inserted all the values without having to specify
the fieldnames.
2. SELECT
SELECT command or statement in SQL is used to fetch data records from the
database table and present it in the form of a result set. It is usually considered as a
DQL command but it can also be considered as DML.
table_name: Specify the name of the database table from which these results
have to be fetched.
condition_expression: Specify the condition expression for filtering records
for the final result set.
output
3. DELETE
DELETE statement in SQL is used to remove one or more rows from the database
table. It does not delete the data records permanently. We can always perform a
rollback operation to undo a DELETE command. With DELETE statements we can use
the WHERE clause for filtering specific rows.
Having learnt the syntax, we are all set to try an example based on the DELETE
command in SQL.
Where Rollno=1203;
The record of the Rollno 1203 will be deleted from the table.
4. UPDATE
UPDATE command or statement is used to modify the value of an existing column in
a database table.
UPDATE table_name
SET column_name_1 = value1, column_name_2 = value2, ...
WHERE condition;
Having learnt the syntax, let us now try an example based on the UPDATE statement
in SQL.
ORDER BY Clause
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. Some databases sort the query results in an ascending order by
default.
Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you
are using to sort that column should be in the column-list.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
17
It is often used with aggregate functions like COUNT( ), SUM( ), MIN( ), MAX( ), AVG( ) etc. to
group the result set by a column.
Syntax:
from table_name
group by column_name
having condition; .
To write the condition using aggregate function in group by clause , we use having clause.
Sometimes a query may have both where and having clauses but where clause is applied first
and then having clause.
The where keyword can not be used with aggregate function .
from employee
group by Emp_name ;
Emp_name Total_working_hours
Ajay 24
ayan 22
from employee
group by Emp_name
having sum(working_hours)>22;
19
Emp_name Total_working_hours
Ajay 24
LIKE Operator
It is used for pattern matching in any string .
Sname
Ram
Que -2 display the name of the students having ‘i’ as second character.
Sname
dinesh
Que-3 display the name of the students having ‘t’ as last character.
Sname
Amit
Sname
shyam
Operations on relations :-
Music Dance
union
Union
Id Name
1 Abhi
2 Mahi
3 mohit
Intersect :-
Music Dance
Intersect
Select * from Dance ;
Output
Minus :-
This operation is used to get tuples which are in the first table but not in the
second table . The operation is represented by the minus(-) symbol.
account depositor
Acc_no Branch balance Cus_name Acc_no
101 x 500 Anil 101
102 y 600 sunil 102
Sql function
Inthis section, we will understand how to use single row functions, multiple row functions, group
records based on some criteria, and working on multiple tables using SQL.
25
Math Functions accept numeric value as input and return a numeric value as a result.
String Functions accept character value as input and return either character or numeric values as
output.
Date and Time functions accept date and time value as input and return numeric or string or Date and
Time as output.
(A) Math Functions Three commonly used numeric functions are POWER(), ROUND() and MOD(). Their
usage along wit
26
(B) String Functions String functions can perform various operations on alphanumeric data which are
stored in a table. They can be used to change the case (uppercase to lowercase or vice-versa), extract a
substring, calculate the length of a string and so on. String functions and their usages.
27
(C) Date and Time Functions :-There are various functions that are used to perform operations on date
and time data. Some of the operations
include displaying the current date, extracting each element of a date (day, month and year),
displaying day of the week and so on.
28
Example 9.21 Let us use the EMPLOYEE table of CARSHOWROOM database to illustrate the working of some of
the date and time functions.
a) Select the day, month number and year of joining of all employees
mysql> SELECT DAY(DOJ), MONTH(DOJ), YEAR(DOJ) FROM EMPLOYEE;
b) If the date of joining is not a Sunday, then display it in the following format "Wednesday, 26, November,
1979."
mysql> SELECT DAYNAME(DOJ), DAY(DOJ), MONTHNAME(DOJ), YEAR(DOJ) FROM EMPLOYEE WHERE
DAYNAME(DOJ)!='Sunday';
29
student
Rollno Sname marks
1201 Amit 10
1202 Mohit 8
1203 sunil 6
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) counts duplicate and Null also.
30
Syntax
Where condition;
Count(*)
3
2. sum( )
It is used to calculate the sum of the values of a column.
Syntax:-
Where condition;
Total_marks
24
3. AVG function
The AVG function is used to calculate the average of the numeric values. AVG function returns
the average of all non-Null values.
Syntax
Where condition;
Example:
Avg_marks
8
4. MAX Function
MAX function is used to find the maximum value of a column.
from student;
output
Maximum_marks
10
5.MIN Function
This function returns The minimum value of a column.
Syntax:- select min(column_name) from table_name;
Ex. Select min(marks) as “minimum_marks” from student;
Minimum_marks
6
Join in dbms
Join clause is used to combine rows from two or more tables based on related .
columns between them.
Join is used with select statement.
While using the join clause, we specify conditions on related columns of two
tables within the from clause.
Usually such attribute is the primary key in one table and foreign key in the
another table.
uniform
Ucode Uname ucolor
1 Shirt White
32
2 Pant Gray
3 Tie Blue
cost
Ucode Size price
1 L 580
1 M 500
2 L 890
2 M 810
Que . list the ucode ,uname,ucolor,size and price of related tuples of tables uniform and
cost.
Select* from uniform,cost
where uniform.ucode=cost.ucode;
Ucode Uname Ucolor Ucode Size price
1 Shirt White 1 L 580
1 Shirt White 1 M 500
2 Pant Grey 2 L 890
2 pant grey 2 M 810
Here we have used join clause explicitly along with condition in from
clause.so no condition needs to be given in where clause.
Explicit use of natural join clause.
The natural join remove the duplicate column from the output relation.
Select* from uniform natural join cost;
Ucode Uname Ucolor Size price
1 Shirt White L 580
33
Ans: it is the pool or collection of data from which the actual values appearing in
a given column are drawn.