You are on page 1of 34

1

DATABASE AND SQL

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.

1.DDL(data definition language)


Create , drop and alter commands are used in DDL language.
Using create and drop commands , we can create and drop database,table,view and
index.
Using alter command , we can add and remove columns in table; we can apply
constraints on columns; we can modify the data types of columns and we can add
default values to a column.
Creating a database
Create database statement is used to create a database in mysql
Syntax:- create database database_name;
To create a school database ,wi will type the following command at mysql prompt.
Create database school;
A dbms may have multiple databases on one computer. We use show databases
statement to know the names of existing databases.
Eg. Show databases;
School
College
Hospital
From the list of databases we can use the desired database.
4

To use a database we will use ‘use database statement’.


Eg. Use school;
Database changed

CREATE TABLE Command: it is used to create a table in SQL. It is a DDL type of


command. Syntax :
CREATE TABLE <table name>
(column name1 data type constraint,
column name2 data type constraint,
.
.
.
Column name n data type constraint);

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

This command shows the list of tables in a database.


Describe table
to view the structure of already created table , we use the ‘describe table’ statement.
Syntax:-
Describe table_name;
Eg describe student;
5

Field Type Null Key Default Extra


Rollno Int No PRI NULL
Sname Varchar(20) Yes NULL
Class Char(5) Yes NULL
dob date yes NULL

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

deleting an column from a table


alter table table_name drop column column_name;
eg. Alter table student drop column age;
modifying data type of a column
we can change the data type of an existing column .
syntax: alter table table_name modify column_name data type;
alter table guardian modify g_address varchar(40);
adding default value to a column
syntax: alter table table_name modify column_name data type default default_value;
eg: alter table employee modify sal int default 10000;

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)
);

Removing primary key from the table


Sometimes there may be requirement to remove primary key from the
table.

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.

Syntax of foreign key.

Alter table table_name add foreign key(column_name)

references referenced_table_name(column_name)

on delete cascade on update cascade;

Look at the following two tables:

Example of Foreign Key


Let's discuss an example to understand the working of a foreign key.

Consider two tables Student and marks having their respective attributes as shown in the
below table structure:

student

Rollno Sname Class age


101 Ram XII 17
102 Shyam XII 16
103 Mohan XII 18

Marks

Rollno Sub Marks


101 Accounts 75
101 Computer 85
102 Accounts 80
102 computer 88

Ex

Alter table marks

Add foreign key(Rollno) references student(Rollno);


9

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.

Creating Foreign Key constraint


On creating table
Below is the syntax that will make us learn the creation of a foreign key in a table:

CREATE TABLE Marks (


Rollno int ,
Sub char(20),
Marks int
FOREIGN KEY (Rollno) REFERENCES Student (Rollno) );

So, in this way, we can set a foreign key for a table in the MYSQL database.

SQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a
column.

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.

SQL CHECK on CREATE TABLE


The following SQL creates a CHECK constraint on the "Age" column when the "Persons"
table is created. The CHECK constraint ensures that the age of a person must be 18, or
older:

MySQL:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

CREATE TABLE Persons(


ID int NOT NULL,
FirstName varchar(255),
LastName varchar(255) NOT NULL,
Age int CHECK (Age>=18)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
FirstName varchar(255),

LastName varchar(255) NOT NULL,


Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='jaipur')
);

SQL CHECK on ALTER TABLE


To create a CHECK constraint on the "Age" column when the table is already created,
use the following SQL:
11

ALTER TABLE Persons


ADD CHECK (Age>=18);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:

ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

ALTER TABLE Persons


DROP CONSTRAINT CHK_PersonAge;

MySQL:

ALTER TABLE Persons


DROP CHECK CHK_PersonAge;

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

102 Shyam finance


103 Dinesh Finance
104 amit Sales

Select distinct(department)
from department;
department
Sales
finance

Data Manipulation in SQL DML Commands are as under:


Data Manipulation Language (DML) commands in SQL deals with manipulation of data records
stored within the database tables.

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

SELECT Used to query or fetch selected fields or columns from a da

INSERT Used to insert new data records or rows in the database tab

UPDATE Used to set the value of a field or column for a particular re

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.

The basic syntax for writing INSERT statements in SQL is as follows :

INSERT INTO table_name (column_name_1, column_name_2, column_name_3,


...)
VALUES (value1, value2, value3, ...)

Here are a few examples to further illustrate the INSERT statement.

INSERT INTO student(rollno,sname,class,age,marks)


VALUES (1201,’Ram’,’XII’,18,85);

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.

INSERT INTO student


VALUES (1202,’Mohan’,’XII’,17,92);

INSERT INTO student


VALUES (1203,’Sunl’,’XII’,19,70;
14

Student

Rollno Sname Class Age` marks

1201 Ram XII 18 85

1202 Mohan XII 17 92

1203 Sunil XII 19 70

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.

The basic syntax for writing a SELECT query in SQL is as follows :

SELECT column_name1, column_name2, …


FROM table_name
WHERE condition_ expression;

The parameters used in the above syntax are as follows :

column_name1, column_name2, … : Specify the column_names which have to be


fetched or selected for the final result set.

 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.

Here are a few examples to illustrate the use of SELECT command.

Select* from student;


15

output

Rollno Sname Class Age` marks

1201 Ram XII 18 85

1202 Mohan XII 17 92

1203 Sunil XII 19 70

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.

The syntax for writing an DELETE statement is as follows :

DELETE FROM table_name WHERE condition;

Having learnt the syntax, we are all set to try an example based on the DELETE
command in SQL.

Delete from student

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.

The syntax for writing an UPDATE statement is as follows :


16

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.

Update student set matrks=marks+5;

This update statement will increase 5 marks of all students.

Arithmetic operators are used to perform simple arithmetic operations.


Relational Operators are used when two values are to be compared and Logical
operators are used to connect search conditions in the WHERE Clause in SQL.
Other operators :
Query:A query is a request to a database for obtaining information in a desired way. Query can
be made to get data from one table or from a combination of tables. To retrieve information
from a database we can query the databases. SQL SELECT statement is used to select rows
and columns from a database/relation.

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

| 2 | Khilan | 25 | Delhi | 1500.00 |


| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in an ascending order by
the NAME . −
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME;

This would produce the following result −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in the descending order
by NAME.
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

This would produce the following result −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

MySQL GROUP BY Clause


The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result
by one or more column. It is generally used in a SELECT statement.
18

It is often used with aggregate functions like COUNT( ), SUM( ), MIN( ), MAX( ), AVG( ) etc. to
group the result set by a column.

Syntax:

Select column_name, aggregate_function(column_name)

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 .

Emp_id Emp_name Working date Working hours


1 Ajay 2021-03-15 12
2 Ayan 2021-03-15 10
1 Ajay 2021-03-16 6
2 Ayan 2021-03-16 12
1 Ajay 2021-03-17 6

Select Emp_name ,sum(working_hours) as “total_working_hours”

from employee

group by Emp_name ;

Emp_name Total_working_hours
Ajay 24
ayan 22

Select Emp_name ,sum(working_hours) as “total_working_hours”

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 .

Pattern can be described by following two characters.

(1) percent (%) :- represents zero or more characters.

(2) Underscore(_) :- represents exactly 1 character.


In MySQL the syntax of the LIKE operator can be as follows.

Select column_name from table_name

where column_name like’wildcard character’;

Sname Rollno class

Ram 1201 XII

Shyam 1202 XII

Amit 1203 XII

dinesh 1204 XII

Que-1 display the name of the students having r as first character.


20

Select sname from student where sname like’r%’;

Sname

Ram

Que -2 display the name of the students having ‘i’ as second character.

Select sname from student where sname like’_i%’;

Sname

dinesh

Que-3 display the name of the students having ‘t’ as last character.

Sname

Amit

Que-4 display the name of the students having five characters.

Sname

shyam

Operations on relations :-

We can perform certain operatons on tables like union,intersect,set


difference to merge the tuples of two tables.

These operations are binary operations as they work on two tables.


21

1 union :- union is used to combine the result of two or more select


statements.

It eliminates the duplicate rows from its results.

Music Dance

Rollno Name class Rollno Name class


1101 Ajay 11 1201 Vijay 12
1201 Vijay 12 1205 Dinesh 12
select * from Music

union

select * from Dance;

Rollno Name Class


1101 Ajay 11
1201 Vijay 12
1205 Dinesh 12
22

Select* from first

Union

Select* from second;

Id Name

1 Abhi

2 Mahi

3 mohit

Intersect :-

Intersect operation is used to combine two select statements. But it


returns the records which are common from both select statements.

Music Dance

Rollno Name class Rollno Name class


1101 Ajay 11 1201 Vijay 12
1201 Vijay 12 1205 Dinesh 12

In intersect operation the no of columns and data type must be common.


Select * from Music
23

Intersect
Select * from Dance ;
Output

Rollno Name class


1101 Ajay 11

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.

Select* from Music


Minus
Select * from Dance;
Rollno Name class
1201 Vijay 12
Cartesian product
it joins each record of the first table to each record of the second table.
No of columns in resultant table is equal to no of columns in first and second
table.
Let the no of records in r1 relation = m
No of records in r2 relation= n
r1*r2 =m*n
let the no of columns in r1 relation be = x
let the no of columns in r1 relation be = y
let the no of columns in resultation relation= x+y
24

account depositor
Acc_no Branch balance Cus_name Acc_no
101 x 500 Anil 101
102 y 600 sunil 102

Select * from account ,depositor;


Acc_no Branch Balance Cus_name Acc_no
101 x 500 Anil 101
102 Y 600 Anil 101
101 X 500 Sunil 102
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

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple rows of a single column
of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

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

Select count(*) from table_name

Where condition;

Ex. Select count(*) from student ;

Count(*)
3

2. sum( )
It is used to calculate the sum of the values of a column.

Syntax:-

Select sum(column_name) from table_name

Where condition;

Select sum(marks) as “total_marks” from student;

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

Select avg(column_name) from table_name

Where condition;

Example:

Select avg(marks) as “Avg_marks” from student;


31

Avg_marks
8

4. MAX Function
MAX function is used to find the maximum value of a column.

Syntax :- select max(column_name) from table_name;

Ex. Select max(marks) as “maximum_marks”

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

Explicit use of join clause:-


Select * from uniform join cost on
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

1 Shirt White M 500


2 Pant Grey L 890
2 pant grey M 810

1&2 mark questions


Q2. Define the terms:
i. Database Abstraction ii. Data inconsistency iii. Conceptual level of database
implementation/abstraction iv. Primary Key v. Candidate Key vi. Relational
Algebra vii. Domain
Ans:. Define the terms:
1 Database Abstraction
Ans: Database system provides the users only that much information
that is required by them, and hides certain details like, how the data is
stored and maintained in database at hardware level. This concept
process is Database abstraction.
2 Data inconsistency
3 Ans: When two or more entries about the same data do not agree i.e. when
one of them stores the updated information and the other does not, it results
in data inconsistency in the database. iii. Conceptual level of database
implementation/abstraction
4 Ans: It describes what data are actually stored in the database. It also
describes the relationships existing among data. At this level the database is
described logically in terms of simple data-structures. iv. Primary Key
5 Ans: It is a key/attribute or a set of attributes that can uniquely identify tuples
within the relation.
------
v. Candidate Key
Ans: All attributes combinations inside a relation that can serve as primary key
are candidate key as they are candidates for being as a primary key or a part of
it.
vi. Relational Algebra Ans : It is the collections of rules and operations on
relations(tables). The various operations are selection, projection, Cartesian
product, union, set difference and intersection, and joining of relations.
vii. Domain
34

Ans: it is the pool or collection of data from which the actual values appearing in
a given column are drawn.

You might also like