Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

UNIT-3 : Data Management

Chapter-11 : Relational Databases


Chapter-12 : Simple Queries in SQL
Chapter-13 : Table Creation & Data Manipulation commands
Chapter-14 : Grouping Records , Joins in SQL

Data refers to the raw facts and figures, it is unorganized, unstructured and difficult to
understand.
Information refers to the raw facts and figures, it is unorganized, unstructured and difficult to
understand.
DATABASE A collection of data is referred as database. Databases are designed to offer an
organized mechanism for storing, managing and retrieving information. They do so
through the use of tables. It is an well-organized collection of information about an
entity or organization.
Data Base A database system is basically a computer based record keeping system. It
System contains a repository of data which is needed for information processing in an
organization. It allow the user to access and manipulate the data contained in the
database in convenient and effective manner.
DBMS A database management system is basically a computer based record keeping
system. The software that takes care of database. It maintains creation, addition,
deletion, modification of files.
Relational Data It is a data model proposed by E.F. Codd for database management. In this model,
Model the data is organized into tables (i.e. rows & columns). These tables are called
relations because each row in a table represents a relationship among a set of
values.
Domain A domain is a pool of values from which the actual values appearing in a given
column are drawn.
Degree The number of attributes in a relation determines the degree of a relation.
Cardinality The number of rows in a relation is known as Cardinality.
RDBMS RDBMS stands for Relational Database Management System. RDBMS is the
basis for SQL, and for all modern database systems like MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
Entity It is an object/thing which can be distinctly identified. It may be person or thing or
item.
Relation The table in a database is called relation where the records are stored.
Tuple The records in a relation are called tuples. It can also be called records or rows.
Attribute The column or field in a relation is called attribute.
Cardinality The number of records present in a table.
Degree/Arity The number of fields in a table.

Conventional File Processing System for Data Storage (used in old days)
➢ In a typical file processing system, permanent records are stored in various files. A no. of different
application programs are written to add and extract data from these files. But this scheme has a no. of
limitations such as :
• Data Redundancy (duplication of data)
• Data inconsistency (multiple data copies which do not match)
• Non-sharable data
• Non-standardized data
• Insecure data
• Incorrect data
➢ DBMS provides solution to all these problems by providing a centralized control of data.

Advantages of Data Base


➢ Centralized control of data
➢ Reduced data redundancy
➢ Greater data integrity
➢ increased data consistency
➢ Improved data security
➢ Reduced data entry, storage, and retrieval costs
➢ Reduced updating errors
➢ independence from application programs
➢ Improved data access to users through use of host and query languages
➢ Facilitated development of new applications program

Disadvantages of Data Base


➢ Database systems are complex, difficult, and time consuming to design
➢ Substantial hardware and software start-up costs
➢ Damage to database affects virtually all applications programs
➢ Extensive conversion costs in moving from a file-based system to a database system
➢ Initial training required for all programmers and users.

Relational Data Base System


✓ A relational database organizes data in tables (or relations).
✓ A table is made up of rows and columns.
✓ A row is also called a record (or tuple).
✓ A column is also called a field (or attribute).
✓ A database table is similar to a spreadsheet. However, the relationships that can be created among
the tables enable a relational database to efficiently store huge amount of data, and effectively
retrieve selected data.

KEYS in database tables


To distinguish every row from the other row in a table, database provides the concept of keys in every
table. Following are the types of keys:

1. Primary Key
➢ It is a field or combination of fields through which a record can be uniquely identified in a table.
➢ The primary key field(s) should not be null.
➢ In some tables, combination of more than one attribute provides a unique value for each row. In
such tables, group of these attributes is declared as primary key. Such a primary key that
constitutes of more than one attribute is called a Composite Primary Key.
➢ There can be only one primary key in a table.

2. Candidate Key
➢ All attribute combinations in a table that can serve as primary key are called candidate key.
➢ They behave the candidates for the primary key.

3. Alternate Key
➢ From the different group of candidate key, the user has to decide one group as primary key.The
other groups are called alternate key.

4. Unique Key
➢ The domain of the field will be unique.
➢ One value can be NULL.
➢ We can have more than one unique keys in a table.

5. Foreign Key
➢ A non key attribute of a table whose value derives from primary key of another table .
Examples of RDBMS Software
• Microsoft SQL Server
• MySQL
• Oracle
• SQLite
• IBM DB2
• Teradata
• PostgreSQL
SQL
➢ SQL is a standard language for accessing and manipulating relational databases.
➢ SQL stands for Structured Query Language
➢ SQL lets you access and manipulate databases
➢ SQL is an ANSI (American National Standards Institute) standard
➢ SQL is not case sensitive
➢ Some database systems require a semicolon at the end of each SQL statement.

Features of SQL
SQL can
➢ create new databases
➢ create new tables in a database
➢ retrieve data from a database
➢ insert records in a database
➢ update records in a database
➢ delete records from a database

Advantages of SQL
➢ Ease of use: It is easy to learn and use
➢ Large volume of data handled easily
➢ No specific code required. Only commands to be remembered
➢ Easily link to most of other high level language
➢ Portable. It is available with all type of DBMS and RDBMS
➢ Not case sensitive
➢ Powerful language
➢ Reliable
➢ Freedom of data abstraction
➢ Complete language for the database

SQL commands can be classified as :


1. Data Definition Language (DDL) : commands related to databases, table etc
2. Data Manipulation Language (DML) : commands Related to record operations
3. Data Control language (DCL) : commands specifying access rights to relations
4. Transaction Control Language (TCL) : commands related to transaction controls
Data Definition Language (DDL)
➢ The DDL part of SQL permits database tables to be created or deleted.
➢ It also defines indexes (keys), specifies links between tables, and imposes constraints between
tables.
➢ The most important DDL statements in SQL are:
✓ CREATE DATABASE - creates a new database
✓ DROP DATABASE - modifies a database
✓ CREATE TABLE - creates a new table
✓ ALTER TABLE - modifies a table
✓ DROP TABLE - deletes a table
✓ CREATE INDEX - creates an index (search key)
✓ DROP INDEX - deletes an index

Data Manipulation Language (DML)


➢ The DML provides statements to enter , update, delete data and perform complex queries on
tables.
➢ Following commands come under DML :
✓ SELECT - extracts data from a database
✓ UPDATE - updates data in a database
✓ DELETE - deletes data from a database
✓ INSERT INTO - inserts new data into a database

Data Control Language (DCL) Grant and Rovoke


✓ GRANT - to give permission to other user/login to
work on another database/table in a client_server system
permissions includes insert/delete/ modify/ view etc.
✓ REVOKE - to revert the permissions

Transaction Control Language (TCL)


✓ COMMIT - saves all transactions to the database
✓ ROLLBACK - to undo all transactions that have not saved
✓ SAVEPOINT - to save/undo to a certain point of transaction
Consider the following table Student (initially):
RollNo NAme

1 Ashi
2 Santanu
4 Bhumika

Insert into student values(5,’Gagan’)


Commit;
Update student set name=‘Arshi’ where rollno=4;
Savepoint A;
Insert into student values(6,’Sahil’);
Savepoint B;
Insert into student values(7,’Babita’);
Savepoint C;
Rollback to B;

When the following commands are executed in sequence, the end result produced is shown
below:

RollNo NAme

1 Ashi
2 Santanu
4 Arshi
5 Gagan
6 Sahil
MySql
It is the most popular open source RDBMS. It works on client - server architecture.

Advantages of MySQL
➢ Reliable and high performance
➢ Modifiable
➢ Multi-platform support
➢ Powerful processing capabilities
➢ Integrity checks
➢ authorization

MySQL Data Types


In MySQL there are three main types : text, number, and Date types.
Data type Description

CHAR(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255
characters

VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255
characters. Note: If you put a greater value than 255 it will be converted to a
TEXT type

INT(size) The maximum number of digits may be specified in parenthesis. it is used to


store whole numbers. By default, size is 11

DECIMAL(M,N) It stores the number with or without the fractional part. M denotes ( number of
digits before and after the decimal +1 for decimal point) and n denotes the
digits to the right side of the decimal point.

DATE() A date. Format: YYYY-MM-DD


Note: The supported range is from '1000-01-01' to '9999-12-31'
SQL COMMANDS
CREATING A DATABASE
To create a database in MySQL, we issue the following query :
Create database demo;

To avoid error in case the database already exists in the system , we can write the following query :
Create database if not exists demo;

FOR OPENING THE DATABASE


To start working in a database, we should first open it with help of following query:
use demo;

TO DISPLAY DATABASE LISTS AVAILABLE


To display a list of all the databases already present in the system, we need to issue the following query :
show databases;

TO CLOSE DATABASE
If we want to close an already opened database, then we write :
close databases;

TO DELETE A DATABASE
To remove a database completely from the memory, we write:
Drop database demo;

TO SEE THE TABLE LIST INSIDE A DATABASE


If we want to view the list of tables that are present in a database, then we write:
Show tables;

TO SEE THE NAME OF CURRENT DATABASE WHICH IS OPEN


Select database();

The CREATE TABLE Statement


The CREATE TABLE statement is used to create a table in a database.

SQL CREATE TABLE Syntax


CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
.... );
Example : Create a table student with the following specifications :
Field Name Datatype
RollNo integer , it is a primary key
Name string
Class integer
Percentage floating value
Grade character of length 2
City string

create table student


( rollno integer primary key,
name char(20),
class integer(2),
percentage decimal(5,2),
grade char(2),
city char(20) );

The table may be created from an existing table.


CREATE TABLE STD SELECT * FROM STUDENT;
// std will be created from student
Create table std3 select std1.fieldname, std2.fieldname from std1,std2;
// std3 will be created from std1 and std2

SQL Constraints / Integrity Constraints


➢ Restrictions imposed to table or column or between tables.
➢ Constraints are used to enforce rules at table level when ever a row is inserted/ updated/ deleted.
➢ Used to prevent invalid data entry.
➢ Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the
table is created (with the ALTER TABLE statement).
➢ Constraints can be defined at one of two levels
1. Column level
2. Table level
The different constraints are
1. NOT NULL only column level
2. Default only column level
3. Unique only column level
4. Primary key both column and table level
5. Check both column and table level
6. Foreign key both column and table level
1. NOT NULL CONSTRAINT
This constraint ensures that null values(empty value) are not permitted for a specified column.
This constraint can be used only at column level.

Create table student


(
roll int(4) not null, or constraint t1 not null,
sname varchar(20),
saddress varchar(30),
percentage decimal(6,2)
);

2. DEFAULT CONSTRAINT
This constraint ensures that a column may be given a default value.
This prevents nulls from occurring in a row, if a row is inserted without a value for any particular field.
This constraint can be used at column/table level.

Create table student


(
roll int(4) not null,
sname varchar(20),
saddress varchar(30),
percentage decimal(6,2) default 33
);

3. UNIQUE CONSTRAINT
This constraint enforces every value in a column or set of columns to be unique.
No two rows in a table can have same value for that column.
Column value may be NULL.
We can apply this constraint on more than one columns.
This constraint used at column/table level.

Create table student


(
roll int(4) unique not null, // more than one constraint possible
sname varchar(20),
saddress varchar(30),
per decimal(6,2) default 33
);
4. PRIMARY KEY CONSTRAINT
This constraint enforces every value in a column or set of columns to be unique.
No two rows in a table can have same value for that column.
It cannot be NULL value and only one primary key is possible in a table
This constraint used at column/table level.

Create table student


(
roll int(4) primary key, // by default it is not null
sname varchar(20),
saddress varchar(30),
percentage decimal(6,2) default 33
);

5. CHECK CONSTRAINT
This constraint explicitly defines a condition that each row must satisfy. A single column may have more
than one conditions and more number of check constraints are possible in a table.
This constraint used at column/table level (when compared between two columns).

Create table student


(
roll int(4) primary key,
sname varchar(20),
saddress varchar(30),
percentage decimal(6,2) check (percentage between 0 and 100)
);

6. FOREIGN KEY CONSTRAINT


This constraint used at column/table level.
Foreign key is the non key attribute of one table which was a primary key for another reference table.

Create table department


( dept_no char(4) primary key ,
deptname varchar(15)
);
Create table teacher
(
tid int(4) primary key ,
tname varchar(20),
taddress varchar(30),
dept_no char(4) references department(dept_no),
or
foreign key(dept_no) references department(dept_no)
);

✓ Constraints can be added after creating table


Constraints can be added to existing table by alter table command
SYNTAX : Alter table table_name
add constraint constraint_name;

EXAMPLE: Alter table student


add constraint p1 primary key(roll);
(p1 is optional)

✓ Constraints can be deleted after creating table:


Constraints can be deleted from existing table by alter table command
SYNTAX : alter table table_name
drop constraint_name;

EXAMPLE: alter table student


drop primary key;

SQL CREATE TABLE Syntax with constraints


CREATE TABLE table_name
(
column_name1 data_type(size) constraint name,
column_name2 data_type( size) constraint name,
....
);

The data type specifies what type of data the column can hold and size denotes the space required for it.
Constraint names to be provided as per requirement.
Example :

CREATE TABLE Persons


(
P_Id int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
PRIMARY KEY (P_Id),
CHECK (P_Id>0)
)

VIEWING TABLE STRUCTURE:


It is used to view the structure of the table, i.e. the column name, datatype, size and the constraint imposed
on the column.
Syntax : Desc tablename;
Example : desc student;
or
show columns from student;

The INSERT INTO Statement


The INSERT INTO statement is used to insert a new row in a table.

The corresponding values are to put within braces. If the datatype of field is char or date, the value should
be placed within single quotes(‘) otherwise value should be put as it is.

SQL INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name


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

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...) ;
SQL INSERT INTO Example
Insert the following records in the table student created above.

rollno name class percentage grade city


1 aman 12 89.5 A2 delhi
2 rohan 12 92 A1 delhi
3 ria 12 93 A1 mumbai
4 Shreya 12 88 A2 chennai
5 swati 12 89 A2 mumbai
6 Suhani 12 delhi
7 prisha 12 delhi

mysql> insert into student


-> values (1 , 'aman' , 12 , 89.5 , 'A2' , 'delhi' );

mysql> insert into student


-> values (2 , 'rohan' , 12 , 92 , 'A1' , 'delhi' );

mysql> insert into student


-> values (3 , 'ria' , 12 , 93 , 'A1' , 'mumbai' );

mysql> insert into student


-> values (4 , 'shreya' , 12 , 88 , 'A2' , 'chennai') ,
-> (5 , 'swati' , 12 , 89 , 'A2' , 'mumbai') ;

mysql> insert into student


-> values (6 , 'suhani' , 12 , null , null , 'delhi');

mysql> insert into student (rollno , name , class , city)


-> values (7 , 'prisha' , 12 , 'delhi') ;

The SQL SELECT Statement


The SELECT statement is used to select data from a database.
SQL SELECT Syntax

SELECT column_name(s)
FROM table_name

and
SELECT * FROM table_name

Note: SQL is not case sensitive. SELECT is the same as select.

Example : To select the content of the columns name and class from table student

SELECT name , class from student ;

Example : To select all the columns from the student table.

SELECT * FROM student ;

Tip: The asterisk (*) is a quick way of selecting all columns!

DISTINCT Clause
In a table, some of the columns may contain duplicate values. This is not a problem; however, sometimes
you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.

SELECT DISTINCT column_name(s)


FROM table_name

Example : To select only the distinct values from the column named "City" from the table above.

SELECT DISTINCT City FROM STUDENT;

The result-set will look like this:


City
delhi
mumbai
chennai

The WHERE Clause


The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Example : To display the list of students who live in delhi

SELECT * FROM student


WHERE city = ‘delhi’

Quotes Around Text Fields


SQL uses single quotes around text values (most database systems will also accept double quotes).
Although, numeric values should not be enclosed in quotes.

Operators Allowed in the WHERE Clause


With the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

The AND & OR Operators


The AND operator displays a record if both the first condition and the second condition is true.
The OR operator displays a record if either the first condition or the second condition is true.

Example : To display the details of all the students who live in delhi and study in class 12

SELECT * FROM student


WHERE city = ‘delhi’
AND class = 12 ;

Example : To display the details of all the students who live either in delhi or mumbai

SELECT * FROM student


WHERE city = ‘delhi’
OR city = ‘mumbai’ ;
The LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.

SQL LIKE Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
SQL wildcards must be used with the SQL LIKE operator.

With SQL, the following wildcards can be used:


Wildcard Description

% A substitute for zero or more characters

_ A substitute for exactly one character

Example :
Condition Pattern
name starts with a a%
name ends with a %a
name contains a %a%
name contains ne %ne%
name is a 4 letter word ____
name is a 4 letter word and starts with n n_ _ _
name is a 4 letter word and ends with a ___a
name is a 4 letter word, starts with a and ends with n a__n
name has 2nd character as a _a%
name as 2nd last character as a %a_

select * from student;


The NOT LIKE Operator
Display the details of all those students whose name does not contain the alphabet a

SELECT *
FROM student
WHERE name NOT LIKE ‘%a%’ ;
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

Example : To select the students who live either in delhi or Mumbai

SELECT * FROM student


where city in (‘delhi’ , ‘mumbai’) ;

The NOT IN Operator


It is the reverse of IN clause

Example : Display the details of all those students who do not live in delhi and Mumbai.

SELECT * FROM student


where city NOT IN (‘delhi’ , ‘mumbai’) ;

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values (includes the boundaries). The values
can be numbers, text, or dates.

SQL BETWEEN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2

Example : To display the names of all those students whose percentage lies between 90 to 100

SELECT name
FROM student
WHERE percentage between 90 and 100 ;
The NOT BETWEEN Operator
Example : To display the student details whose percentage does not lie between 50 to 100

SELECT *
FROM student
WHERE percentage NOT BETWEEN 50 and 100 ;

The ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.

SQL ORDER BY Syntax

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC / DESC

Example : To display all records in ascending order of their names

SELECT * FROM student


ORDER BY name ;

Example : Display the name and percentage of all students in descending order of their percentage.

SELECT name , percentage FROM student


ORDER BY percentage desc ;

Example : Display the name and percentage of all students who live in Delhi in descending order of
their percentage.

SELECT * FROM student


WHERE city = ‘delhi’
ORDER BY percentage desc ;

Handling NULL Values


➢ NULL is something of a typeless value. It is used to mean no value.
➢ NULL value do not allow any arithmetic operation on them.
➢ A condition that compares column value to NULL, does not work properly.
➢ To handle such situation MySQL provides operators.
✓ IS NULL : It returns true of column value is NULL
✓ IS NOT NULL : It returns true of column value is not NULL

Example : Display the name and class of all students whose percentage field is blank.

SELECT name, class FROM student


WHERE percentage is null;

Example : Display the name and class of all students whose grade or percentage is not blank.

SELECT name, class FROM student


WHERE grade is not null OR percentage is not null ;

Putting text in the statement:


Select col1 ‘text1’ , col2 From tablename;

Example : To display the name and percentage of all students in formatted manner as
“Studentname scores per%” , display the data in descending order of their percentage.

SELECT name, “SCORES” , percentage , “%”


FROM student
order by percentage desc ;

COLUMN ALIAS:
We can change the heading of a particular column while printing the result of select query as below :

Example : To display the name and percentage of all students, change the heading name to student
name.

SELECT name as STUDENT_NAME , percentage


FROM student ;

or

SELECT name STUDENT_NAME , percentage


FROM student ;

Note : Alias name may or may not be written in quotes.


NOTE :
Space is not allowed in the alias name created, so the following query gives an error :
select name as student name from student;

The UPDATE Statement


The UPDATE statement is used to update existing records in a table.
Multiple fields can be updated. Multiple records can be updated also.

SQL UPDATE Syntax

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!

Example 1 : To change the city of all students as ‘mumbai’.

UPDATE student
SET city = ‘mumbai’;

Example 2 : To change the city as ‘mumbai’ and class as 12 for all the students.

UPDATE student
SET city = ‘mumbai’ , class = 12 ;

Example 3 : To change the city of all those students to Mumbai who currently live in chennai.

UPDATE student
SET city = ‘mumbai’
where city = ‘chennai’ ;

Example 4 : To change the percentage to 90 and grade to A2 for all those students, whose
percentage or grade field is blank.

UPDATE student
SET percentage = 90 , grade = ‘A2’
where percentage is null or grade is null ;
Example 5 : To change the city field to blank for all the students who currently live in delhi.

UPDATE student
SET city = null
where city = ‘delhi’ ;

The DELETE Statement


The DELETE statement is used to delete rows in a table.

SQL DELETE Syntax

DELETE FROM table_name


WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!

Example 1 : To delete all rows from the table student:

DELETE FROM student ;

Example 2 : To delete the record of all the students whose percentage is less than 90 from the table
student:

DELETE FROM student


where percentage < 90 ;

The DROP TABLE Statement


The DROP TABLE statement is used to delete a table from the memory of the system. It removes the
physical structure of the table.

Drop table tablename;


E.g. drop table student;

Drop table if exists tablename;


e.g. drop table if exists student;

The ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
It is used to make changes in the physical structure of the table.
To delete a column in a table:
ALTER TABLE table_name DROP COLUMN column_name ;
Or
ALTER TABLE table_name DROP column_name ;

To change the data type of a column in a table:


ALTER TABLE table_name MODIFY column_name datatype(size);

You can rename a field


Alter table student change per percentage decimal(6,2);
Or
Alter table student modify per to percentage decimal(6,2);

You can change the name of the table.


Alter table student rename to student_rec;
or
Rename table student to student_rec;

To add a column in a table:


ALTER TABLE table_name ADD column_name datatype(size);
e.g.
Alter table student Add gender char(1);
The field will be added at end of table by default. If you want to add the field at your choice, you can use
first/after existing column name.

Example 1 : To add a new column gender in the table student, datatype character, length 10

ALTER TABLE student


ADD gender char(10) ;

Example 2 : To remove the column gender from the table student

ALTER TABLE student


drop column gender ;

OR

ALTER TABLE student


drop gender ;
Example 3 : To change the datatype of column city to varchar(20)

ALTER TABLE student


modify city varchar(20) ;

Example 4 : To change the column name ‘percentage’ to per

ALTER TABLE student


change percentage per decimal(5,2) ;

Example 5 : To change the name of table student to students

ALTER TABLE student


rename to students ;

OR

RENAME table student to students ;

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
a) AVG() - Returns the average value
b) COUNT() - Returns the number of rows
c) MAX() - Returns the largest value
d) MIN() - Returns the smallest value
e) SUM() - Returns the sum

1. The AVG() Function


The AVG() function returns the average value of a numeric column.

SQL AVG() Syntax

SELECT AVG(column_name) FROM table_name

Example : To find the average of column percentage

SELECT AVG(percentage) FROM student ;


2. SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column:

SELECT COUNT(column_name) FROM table_name

SQL COUNT(*) Syntax


The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name

SQL COUNT(DISTINCT column_name) Syntax


The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:

SELECT COUNT(DISTINCT column_name) FROM table_name

Example 1 : To count the number of records in the table student,

SELECT COUNT(*) FROM student ;

Example 2 : To count the number of students who live in delhi

SELECT COUNT(*) FROM student


where city = ‘delhi’ ;

OR

SELECT COUNT(city) FROM student


where city = ‘delhi’ ;

Example 3 : To count the number of records which do not have grade field blank

SELECT COUNT(grade) FROM student ;

Example 4 : To count the number of distinct values in the column city.

SELECT COUNT(distinct city) FROM student ;


3. The MAX() Function
The MAX() function returns the largest value of the selected column.

SQL MAX() Syntax

SELECT MAX(column_name) FROM table_name

Example : To find the maximum percentage obtained in the class

SELECT MAX(percentage) FROM student ;

4. The MIN() Function


The MIN() function returns the smallest value of the selected column.

SQL MIN() Syntax

SELECT MIN(column_name) FROM table_name

Example : To find the minimum percentage obtained in the class

SELECT MIN (percentage) FROM student ;

5. The SUM() Function


The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax

SELECT SUM(column_name) FROM table_name

Example 1 : To find the sum of column percentage for all students

SELECT SUM(percentage) from student ;

Example 2 : To find the sum of column percentage for students who live in delhi

SELECT SUM(percentage) from student


where city = ‘delhi’;

The GROUP BY Statement


The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by
one or more columns.
SQL GROUP BY Syntax

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name

We have the following "Orders" table:


O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Example : To find the total sum (total order) of each customer.


We will have to use the GROUP BY statement to group the customers.

SELECT Customer, SUM(OrderPrice) FROM Orders


GROUP BY Customer

The result-set will look like this:


Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000

Let's see what happens if we omit the GROUP BY statement:

SELECT Customer, SUM(OrderPrice) FROM Orders

The result-set will look like this:


Customer SUM(OrderPrice)
Hansen 5700
Nilsen 5700
Hansen 5700
Hansen 5700
Jensen 5700
Nilsen 5700

The result-set above is not what we wanted.

The HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.

SQL HAVING Syntax

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

Example : To find if any of the customers have a total order of less than 2000.

SELECT Customer , SUM(OrderPrice) FROM Orders


GROUP BY Customer
HAVING SUM(OrderPrice)<2000

The result-set will look like this:


Customer SUM(OrderPrice)
Nilsen 1700

Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500.
We add an ordinary WHERE clause to the SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Orders


WHERE Customer='Hansen' OR Customer='Jensen'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500

The result-set will look like this:


Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000

Queries on Multiple Tables


Table : employee
No Name Salary Zone Age Grade Deptno
1 Mukul 30000 West 28 A 10
2 Kritika 35000 Centre 30 A 10
3 Naveen 32000 West 40 20
4 Uday 38000 North 38 C 30
5 Nupur 32000 East 26 20
6 Moksh 37000 South 28 B 10
7 Shelly 36000 North 26 A 30

Table : department
Deptno Deptname Minsal Maxsal
10 Sales 25000 32000
20 Finance 30000 50000
30 Admin 25000 40000

a) Display the details of all the employees who work in sales department.
select *
from employee , department
where deptname = ‘sales’
and employee.deptno = department.deptno ;

b) Display the salary, zone and grade of all the employees of Admin department;
select salary , zone , grade
from employee , department
where deptname = ‘Admin’
and employee.deptno = department.deptno ;

c) Display the name and department name of all the employees.


select name , deptname
from employee , department
where employee.deptno = department.deptno ;

STRING FUNCTIONS
1. CHAR()
Returns the character equivalent for integer passed
Char(65) gives A
65-90 A—Z
97-122 a---z
Select char(70,65,67,69) gives FACE

2. LENGTH()
Returns the length of the string
Select LENGTH(‘computer’) gives 8

3. CONCAT()
It joins second string to the end of first string
Select Concat(‘subroto’,’park’)
give you subrotopark

4. INSTR()
Returns the first occurrence of a character from the string
Select instr(‘computer’,’put’) gives 4

5. LOWER()/ LCASE()
Converts the string into lower case
Select LOWER(‘COMPUTER science’)
gives computer science

6. UPPER()/ UCASE()
Converts the string into upper case
SELECT UPPER(‘COMPUTER science’)
gives COMPUTER SCIENCE

7. LEFT()
Returns the specified number of characters from left side of the string
SELECT LEFT(‘COMPUTER’,3) gives COM

8. LTRIM()
Removes the leading spaces from the string
SELECT LTRIM(‘ COMPUTER’) gives COMPUTER

9. RTRIM()
Removes the trailing spaces from the string
SELECT RTRIM(‘COMPUTER ’) gives COMPUTER

10. TRIM()
Removes the spaces from the string both leading and trailing
SELECT TRIM(‘ COMPUTER ’) gives COMPUTER

11. SUBSTR()
Returns the substring as specified. It works same as MID()
SELECT SUBSTR(‘COMPUTER’,5) gives UTER
SELECT SUBSTR(‘COMPUTER’,3,4) gives MPUT

NUMERIC FUNCTIONS
1. power()/ pow()
Returns the argument raised to the specified power.
Select Pow(2,4) gives 16
Select Pow(2,-2) gives 0.25
Select Pow(-2,3) gives -8

2. Round()
Round(x) : rounds the argument upto 0 decimal place
Round(x, d) : rounds the argument up to ‘d’ decimal places
Select Round(1.23) gives 1
Select Round(1.58) gives 2
Select Round(-1.23) gives -1
Select Round(-1.58) gives -2
Select Round(3.789,1) gives 3.8
Select Round(1.298,0) gives 1
Select Round(23.298,-1) gives 20

3. Truncate()
Truncates the argument to specified number of decimal places
Select Truncate(7.29,1) gives 7.2
Select Truncate(27.29,-1) gives 20

4. mod()
Returns remainder when one number divisible by other number
Select mod(11,4) gives 3

5.sqrt()
Calculates the square root of a number
Select sqrt(16) gives 4.0

6. sign()
Returns sign(1,-1) of a number
Select sign(11) gives 1
Select sign(-11) gives -1
Select sign(0) gives 0

DATE FUNCTIONS
1. now()
Returns the current date and time
Select now()

2. Curdate()
Returns the current system date
Select curdate()

3. Sysdate()
select sysdate()
Returns the current system date and time when the command executes

4. DATE()
Extracts date part of date or datetime expression
Select DATE(‘2010-03-31 10:20:45’) gives 2010-03-31

5. MONTH()
Extracts month part of date passed
Select MONTH(‘2010-03-31’) gives 3

6. YEAR()
Extracts year part of date or datetime expression
Select year(‘2010-03-31 10:20:45’) gives 2010

7. DAYNAME()
Returns the name of the week day
Select DAYNAME(‘2019-11-27’) gives Wednesday

8. DAYOFMONTH()
Returns the day of the month( 1-31)
Select dayofmonth(‘2010-03-31’) gives 31

9. DAYOFWEEK()
Returns the day of week( 1-7)
Select DAYOFWEEK(‘2019-11-27’) gives 3

10. DAYOFYEAR()
Returns the day of the year( 1-365)
Select DAYOFYEAR(‘2019-11-27’) gives 321

You might also like