You are on page 1of 129

Unit II

Academic Year : 2018-19


Database Management Systems

1
UNIT II DATABASE DESIGN AND SQL
 R1: Silberschatz A., Korth H., Sudarshan S., "Database System Concepts", 6thEdition, McGraw
Hill Publishers, ISBN 0-07-120413-X
 R2: S.K.Singh, “Database Systems : Concepts, Design and Application”, 2nd Edition, Pearson,
2013, ISBN 978-81-317-6092-5
 R3: Jiawei Han, Micheline Kamber, Jian Pei, “Data Mining: Concepts and Techniques”, Elsevier
 R4: Kristina Chodorow, Michael Dirolf, “MangoDB: The Definitive Guide” ,O’Reilly
Publications
 R5. Tom White, “Hadoop: The Definitive Guide”, O’Reilly Publications
 R6: Ivan Bayross, “SQL, PL/SQL The Programming Language of Oracle”, Amazon India.

Sr.
Topic Reference book
No.

1 Database Design: functional Dependencies R1


2 Normalization:1NF, 2NF, 3NF R1
3 Normalization: 4NF, 5NF R1
4 Introduction to SQL R1/R6
5 Introduction to SQL: Tables and views R1/R6
6 SQL Queries: Select Queries, Clauses R1/R6
7 SQL Queries: Set operations and Join R1/R6
2 8 SQL Queries: Aggregate Function R1/R6
RDBMS
 RDBMS stands for Relational Database Management System.
 RDBMS is the basis for SQL, and for all modern database
systems such as MS SQL Server, IBM DB2,, and Microsoft
Access.
 The data in RDBMS is stored in database objects called
tables.
 A table is a collection of related data entries and it consists of
columns and rows.
 It is called Relational Data Base Management System
(RDBMS) because it is based on relational model introduced
by E.F. Codd.

3
History of RDBMS
 During 1970 to 1972, E.F. Codd published a paper to
propose the use of relational database model.
 RDBMS is originally based on that E.F. Codd's relational
model invention.
How it works?
 Data is represented in terms of tuples (rows) in RDBMS.
 Relational database is most commonly used database. It
contains number of tables and each table has its own primary
key.
 Due to a collection of organized set of tables, data can be
accessed easily in RDBMS.

4
Introduction to RDBMS
 Table: The RDBMS database uses tables to store data. A table is a
collection of related data entries and contains rows and columns to
store data.
 Field: Field is a smaller entity of the table which contains specific
information about every record in the table. In the above example,
the field in the student table consist of id, name, age, course.
 Rows or records: A row of a table is also called record. It
contains the specific information of each individual entry in the
table. It is a horizontal entity in the table.
 Column: A column is a vertical entity in the table which contains
all information associated with a specific field in a table. For
example: "name" is a column in the above table which contains all
information about student's name.
5
Introduction to RDBMS
 Database Objects:
• Table/Entity: Table is a database Object that hold data in the
form of rows and columns.
• It is represented by set of attributes.
• Attributes are descriptive property possessed by each member
of entity set.
• Domain: set of same value in the column
• Primary Key: An attributes which uniquely defines the
records.
• Tuple: It is single row or record in the table.
• Database Objects: It includes Table, Synonym, sequence, view
and Index.
6
No. DBMS RDBMS
DBMS applications store data as RDBMS applications store data in a
1)
file. tabular form.

In DBMS, data is generally stored In RDBMS, the tables have an identifier


2) in either a hierarchical form or a called primary key and the data values
navigational form. are stored in the form of tables.

Normalization is not present in


3) Normalization is present in RDBMS.
DBMS.

RDBMS defines the integrity


DBMS does not apply any
constraint for the purpose of ACID
4) security with regards to data
(Atomocity, Consistency, Isolation and
manipulation.
Durability) property.

in RDBMS, data values are stored in the


DBMS uses file system to store
form of tables, so a relationship
5) data, so there will be no relation
between these data values will be
between the tables.
stored in the form of a table as well.

7
No. DBMS RDBMS

RDBMS system supports a tabular


DBMS has to provide some
structure of the data and a relationship
6) uniform methods to access the
between them to access the stored
stored information.
information.
DBMS does not support RDBMS supports distributed
7)
distributed database. database.
DBMS is meant to be for small
RDBMS is designed to handle large
organization and deal with
8) amount of data. it supports multiple
small data. it supports single
users.
user.
Examples of DBMS are file Example of RDBMS are mysql, postgre,
9)
systems, xml etc. sql server, oracle etc.
RDBMS system supports a tabular
DBMS has to provide some
structure of the data and a relationship
6) uniform methods to access the
between them to access the stored
stored information.
information.

8
History of SQL
 IBM Sequel language developed as part of System R project at the
IBM San Jose Research Laboratory
 Renamed Structured Query Language (SQL)
 ANSI and ISO standard SQL:
 SQL-86
 SQL-89
 SQL-92
 SQL:1999 (language name became Y2K compliant!)
 SQL:2003
 Commercial systems offer most, if not all, SQL-92 features, plus
varying feature sets from later standards and special proprietary
features.
 Not all examples here may work on your particular system.

9
Introduction to SQL
 SQL (Structured Query Language) is used to perform
operations on the records stored in database such as updating
records, deleting records, creating and modifying tables,
views etc.
 SQL is an ANSI (American National Standards Institute)
standard
 SQL is just a query language, it is not a database.
 To perform SQL queries, you need to install any database for
example Oracle, MySQL, PostGre SQL, SQL Server, IBM
DB2, microsoft access and MS SQL server etc.

10
What Can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

11
Why SQL is required?
SQL is required:
 To create new databases, tables and views
 To insert records in a database
 To update records in a database
 To delete records from a database
 To retrieve data from a database

12
What SQL can do?
 With SQL, we can query our database in a numbers of ways, using
English-like statements.
 With SQL, user can access data from relational database
management system.
 It allows user to describe the data.
 It allows user to define the data in database and manipulate it
when needed.
 It allows user to create and drop database and table.
 It allows user to create view, stored procedure, function in a
database.
 It allows user to set permission on tables, procedure and view.

13
Characteristics and Advantages of SQL
• SQL is a structure Query Language.
• Every commercial database supports SQL.
• SQL is not case sensitive. Generally SQL keywords are written in
uppercase.
• SQL uses a combination of relational algebra and relational calculus
constructs.
 Objectives of SQL
1. create, delete and modify database and relational structures.
2. Perform basic data management tasks, such as:
 i. Insertion of a new tuple.
 ii. Deletion of a tuple
 iii. Modification of tuple
 3. Perform both simple and complex queries
14
Advantages of SQL
1. SQL is an easy language to learn and use
2. SQL is non-procedural language – we specify only what to get
and not how to get.
3. SQL is a free format language and it is case insensitive.
4. Command of SQL consist of simple English words like
SELECT,INSERT, DELETE.
5. SQL can be use by a diverse range of users:
 1. Application Developer
 2. DBA
 3. End – User.

15
SQL Data Types
1. Boolean data type
2. Character data type
3. Numeric data type
4. Date-time data type
5. Bit-string data type
6. Interval data type

16
Boolean data type
 A Boolean data is declared using the reserve word
BOOLEAN. x BOOLEAN Data type of x is declared as
Boolean
 A Boolean data consist of the distinct truth values TRUE
and FALSE.

17
Character data type
 A character data type can be either a fixed length character string or
a varying length character string.
 empno CHAR (4)
 empno CHARACTER(4)
 AddressVARCHAR(80)
 CHARACTER can be abbreviated to CHAR
 A string may be declared of fixed length using CHAR(n). If a string
is defined as of fixed length and fewer characters are stored in it
then the string is padded with blanks on its right.
 A string may be declared of varying length usingVARCHAR(n).

18
String Data Types
Data Type Syntax Maximum Size Explanation

Where size is the number of characters to store.


Maximum size of 255
CHAR(size) Fixed-length strings. Space padded on right to
characters.
equal size characters.

Maximum size of 255 Where size is the number of characters to store.


VARCHAR(size)
characters. Variable-length string.

TINYTEXT(size) Maximum size of 255 characters. Where size is the number of characters to store.

Maximum size of 65,535


TEXT(size) Where size is the number of characters to store.
characters.
Maximum size of 16,777,215
MEDIUMTEXT(size) Where size is the number of characters to store.
characters.
Maximum size of 4GB or
LONGTEXT(size) Where size is the number of characters to store.
4,294,967,295 characters.

Where size is the number of binary characters to store.


BINARY(size) Maximum size of 255 characters. Fixed-length strings. Space padded on right to equal size
characters.

Where size is the number of characters to store. Variable-


VARBINARY(size) Maximum size of 255 characters. length string.

19
Numeric Data Type
1. Int
2. Smallint
3. Numeric(p,d);
4. Real
5. Double precision
6. float

20
Numeric data type
 1. Exact numeric data
 2. Approximate numeric data
 1.Exact numeric data gives an exact representation of number. A number
contains:
 1.Digits
 2.Optional sign
 3.Optional decimal point
 xNUMBER (6,2), declares x to be of Numeric type with 6 digits. Out of 6
digits, 2 digits are after decimal point.
 -12.436,15.69 etc. are numeric literals.
 2.Approximate numeric data are used for defining of real numbers. Real
numbers may not have exact representation. It is similar to float of C-language

21
Data Type Syntax Explanation
TINYINT(m)
SMALLINT(m)
MEDIUMINT(m)
INT(m)
INTEGER(m) This is a synonym for the INT datatype.
BIGINT(m)
DECIMAL(m,d) Where m is the total digits and d is the number of digits after the decimal.
Where m is the total digits and d is the number of digits after the decimal. This is a
DEC(m,d)
synonym for the DECIMAL datatype.
Where m is the total digits and d is the number of digits after the decimal. This is a
NUMERIC(m,d)
synonym for the DECIMAL datatype.
FIXED(m,d) Where m is the total digits and d is the number of digits after the decimal.
FLOAT(m,d) Where m is the total digits and d is the number of digits after the decimal.
DOUBLE(m,d) Where m is the total digits and d is the number of digits after the decimal.
DOUBLE Where m is the total digits and d is the number of digits after the decimal.
PRECISION(m,d) This is a synonym for the DOUBLE datatype.
Where m is the total digits and d is the number of digits after the decimal.
REAL(m,d)
This is a synonym for the DOUBLE datatype.
FLOAT(p) Where p is the precision.
Treated as a boolean data type where a value of 0 is considered to be FALSE and any other
BOOL
value is considered to be TRUE.
Treated as a boolean data type where a value of 0 is considered to be FALSE and any other
22 BOOLEAN
value is considered to be TRUE.
Date & Time Data Types
Data Type Syntax Maximum Size Explanation

Values range from '1000-01-01' to '9999-12-


DATE Displayed as 'YYYY-MM-DD'.
31'.

Values range from '1000-01-01 00:00:00' to '9999- Displayed as 'YYYY-MM-DD


DATETIME
12-31 23:59:59'. HH:MM:SS'.

Values range from '1970-01-01 00:00:01' UTC to Displayed as 'YYYY-MM-DD


TIMESTAMP(m)
'2038-01-19 03:14:07' UTC. HH:MM:SS'.

TIME Values range from '-838:59:59' to '838:59:59'. Displayed as 'HH:MM:SS'.

YEAR[(2|4)] Year value as 2 digits or 4 digits. Default is 4 digits.

23
Date/Time Types in SQL
 date. Dates, containing a (4 digit) year, month and date
 E.g. date ‘2001-7-27’
 time. Time of day, in hours, minutes and seconds.
 E.g. time ’09:00:30’ time ’09:00:30.75’
 timestamp: date plus time of day
 E.g. timestamp ‘2001-7-27 09:00:30.75’
 Interval: period of time
 E.g. Interval ‘1’ day
 Subtracting a date/time/timestamp value from another gives an interval value
 Interval values can be added to date/time/timestamp values
 Can extract values of individual fields from date/time/timestamp
 E.g. extract (year from r.starttime)
 Can cast string types to date/time/timestamp
 E.g. cast <string-valued-expression> as date

24
Domain Types in SQL
• char(n). Fixed length character string, with user-specified length n.
• varchar(n). Variable length character strings, with user-specified maximum length
n.
• int. Integer (a finite subset of the integers that is machine-dependent).
• smallint. Small integer (a machine-dependent subset of the integer domain type).
• Numeric (p , d). Fixed point number, with user-specified precision of p digits, with
d digits to the right of decimal point.
• real, double precision. Floating point and double-precision floating point
numbers, with machine-dependent precision.
• float(n). Floating point number, with user-specified precision of at least n digits.
• Null values are allowed in all the domain types. Declaring an attribute to be not
null prohibits null values for that attribute.
• create domain construct in SQL-92 creates user-defined domain types
 create domain person-name char(20) not null

25
Component of SQL
1. Data Definition Language(DDL) : Relational schemas can be
created, modified and deleted using DDL.
2. Data Manipulation Language (DML): It is used for retrieving
and updating data.
3. View definition: SQL includes commands for defining views.
4. Transaction control : SQL includes commands for specifying
transaction boundaries.
5. Integrity constraints: SQL includes commands for specifying
integrity constraints.
6. Authorization: SQL includes commands for access control.

26
MySQL Installation
 Install mysql 6.0
 Open command prompt using start -> run-> cmd
 Find the address of mysql folder on C drive as like “C:\Program
Files\MySQL\MySQL Server 5.7\bin”
 On command Prompt
 C:\Users\-SONALI->cd..
 C:\Users>cd..
 C:\
 C:\>cd Program Files
 C:\Program Files>cd MySQL
 C:\Program Files\MySQL>cd MySQL Server 5.7
 C:\Program Files\MySQL\MySQL Server 5.7>cd bin
 C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p -h
localhost
 Enter password: ****
27
Installing MySQL On Ubuntu
 On terminal execute following commnads
 sudo apt-get update : It will ask for admin password.
 sudo apt-get install mysql-server
 sudo mysql_secure_installation
Here, It will ask for password set root. For all yes or no type
Questions, type ‘y’. Give user name root and password
=root.
 sudo mysql_install_db : onces the installation is done,
execute following command
 Mysql –u root –p –h localhost
 Password: root

28
What is Database?
 A database is an organized collection of data.
 Database handlers create database in such a way that only one
set of software program provide access of data to all the users.
 The main purpose of database is to operate large amount of
information by storing, retrieving and managing.
 There are many dynamic websites on the world wide web now
a days which are handled through databases. For example, a model
to checks the availability of rooms in a hotel. It is an example of
dynamic website that uses database.
 There are many database available like MySQL, Sybase, Oracle,
Mango DB, Informix, Postgre, SQL Server etc.
 A cylindrical structure is used to display the image of a database.

29
Create Database and Use Database
 This command is used to create a new user defined database

 mysql> create database student;


Query OK, 1 row affected (0.03 sec)

 Following command is used to set default database from the


list of databases.
 In MySQL database, you need to select a database first before
executing any query on table, view etc.

 mysql> use student;

30
 Database changed
SQL Commands
 There are four types of SQL commands as
 DDL: Data Definition Language
 DML: Data Manipulation Language
 DCL: Data Control Language
 TCL: Transaction Control Language

31
DDL (Data Definition Language)
 DDL(Data Definition Language) : DDL or Data Definition
Language actually consists of the SQL commands that can be used
to define the database schema. It simply deals with descriptions of
the database schema and is used to create and modify the structure
of database objects in database.
Examples of DDL commands:
 CREATE – is used to create the database or its objects (like table,
index, function, views, store procedure and triggers).
 DROP – is used to delete objects from the database.
 ALTER-is used to alter the structure of the database.
 TRUNCATE–is used to remove all records from a table, including
all spaces allocated for the records are removed.
 COMMENT –is used to add comments to the data dictionary.
 RENAME –is used to rename an object existing in the database.
32
DML(Data Manipulation Language)
 DML(Data Manipulation Language) : The SQL commands
that deals with the manipulation of data present in database belong
to DML or Data Manipulation Language and this includes most of
the SQL statements.
Examples of DML:
 SELECT – is used to retrieve data from the a database.
 INSERT – is used to insert data into a table.
 UPDATE – is used to update existing data within a table.
 DELETE – is used to delete records from a database table.

33
TCL(Transaction Control Language)

 TCL(transaction Control Language) : TCL commands deals


with the transaction within the database.
Examples of TCL commands:
 COMMIT– commits a Transaction.
 ROLLBACK– rollbacks a transaction in case of any error occurs.
 SAVEPOINT–sets a savepoint within a transaction.
 SET TRANSACTION–specify characteristics for the transaction.

34
DCL(Data Control Language)
 DCL(Data Control Language) : DCL includes commands such
as GRANT and REVOKE which mainly deals with the rights,
permissions and other controls of the database system.
Examples of DCL commands:
 GRANT-gives user’s access privileges to database.
 REVOKE-withdraw user’s access privileges given by using the
GRANT command.

35
Show Databases
 This command is used to display the list of databases.
 mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| database |
| database123 |
| db |
| mysql |
| performance_schema |
| sakila |
| student |
| sys |
| world |
+--------------------+
10 rows in set (0.22 sec)

36
Delete and rename Database
 This command is used to delete the database which was
created.

 mysql> drop database student123;


Query OK, 0 rows affected (0.16 sec)

 SQL rename database is used when you need to change the


name of your database.
 Mysql>rename database old_db_name to new_db_name;

37
DDL Commands includes
• DDL commands are the SQL commands used to
create, alter, drop truncate different database
objects in an Oracle Database
1. Create Table
2. Alter Table
3. Drop Table
4. Truncate Table
5. Rename table

38
Data Definition Language (DDL)
Allows the specification of:
 The schema for each relation, including attribute types.
 Integrity constraints
 Authorization information for each relation.
 Non-standard SQL extensions also allow specification of
 The set of indices to be maintained for each relations.
 The physical storage structure of each relation on disk.

39
SQL Table
 Table is a collection of data, organized in terms of rows and
columns. In DBMS term, table is known as relation and row
as tuple.
 Note: A table has a specified number of columns, but
can have any number of rows.
 Table is the simple form of data storage. A table is also
considered as a convenient representation of relations.

40
Create Table Construct
 An SQL relation is defined using the create table command:
 Syntax:
mysql> create table r (A1 D1, A2 D2, ..., An Dn, (integrity-
constraint1),..., (integrity-constraintk));
 r is the name of the relation
 each Ai is an attribute name in the schema of relation r
 Di is the data type of values in the domain of attribute Ai
 Syntax:
create table table_name (column1 data type, column2
data type, column3 datatype,.... ,columnN datatype);

41
Create Table
 Example:
1. mysql>create table branch (branch-name char(15)
not null, branch-city char(30), assets integer);
2. mysql> create table student(rollno integer,name varchar
(10), marks integer);

Using create table command, we can design schema of a table.


Schema is overall design of a table or database.

42
Syntax of Create table
 mysql> create table stud(rollno int,name varchar(10),marks int);
 Query OK, 0 rows affected (0.80 sec)
 mysql> describe stud;
 +--------+-------------+------+-----+---------+-------+
 | Field | Type | Null | Key | Default | Extra |
 +--------+-------------+------+-----+---------+-------+
 | rollno | int(11) | YES | | NULL | |
 | name | varchar(10) | YES | | NULL | |
 | marks | int(11) | YES | | NULL | |
 +--------+-------------+------+-----+---------+-------+
 3 rows in set (0.09 sec)

43
Describe Table
 mysql> describe stud;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| rollno | int(11) | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
| marks | int(11) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.09 sec)
 mysql> desc stud;
 These command is used to describe the structure or schema of a
table.
44
Restrictions for creating a Table
 Table Name and column name
 Must begin with Letter
 Name can be 1 to 30 characters
 It contains Characters A-Z,a-z, 0to 9, _, $ and #
 Should not be same as the name of database objects.
 Should not be a oracle reserved words
 Column name should not be duplicate.

45
Alter Table
 It is used to add new attributes (column) or to modify or remove
the existing attributes (columns) in the table.
 Add new column
 Remove existing column
 Change column name, size and length.

 Syntax: to add new column/columns


 alter table table_name add (column_name datatype(size),
column_name datatype(size), .......);

 Example:
 alter table student add(dob date);
 alter table student add(dob date, mobile number);
46
Alter Table- add new column
 ALTER TABLE table_name Operations

mysql> alter table student add (mobno int);


Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> describe student;
+---------------+--------------------- +-------+------+----------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+----------------------+-------+------+----------+-------+
| student_ID | int(10) unsigned | | | NULL | |
| name | varchar(20) | | | NULL | |
| major | varchar(10) | YES | | NULL | |
| grade | varchar(5) | YES | | NULL | |
| mobno | int(11) | YES | | NULL | |
+---------------+----------------------+-------+------+-----------+-------+
47 5 rows in set (0.00 sec)
Adding new column to Table
 mysql> alter table stud add(address varchar(10));
 mysql> alter table stud add id int first;
 mysql> alter table stud add city varchar(10) after name;
 mysql> desc stud;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| rollno | int(11) | NO | PRI | NULL | |
| name | varchar(10) | YES | | NULL | |
| city | varchar(10) | YES | | NULL | |
| marks | int(11) | YES | | NULL | |
| address | varchar(10) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
48
Alter Table- to modify column
 To modify table structure
 Syntax:
 alter table table_name modify (column_name1
datatype(size), column_name2 datatype(size), ......);

 Example:
 alter table student modify(name varchar(50));

49
Alter- Modify, change and rename
 Modify: It is used to change data type of the existing column
 alter table table_name modify column_name datatype;
 alter table student modify name varchar(30);
 Change: used to change column name and datatype of the
existing column.
 alter table table_name change columnname new_columnname
datatype;
 Alter table student change name stud_name varchar(10);
 Rename: It is used to change the table name
 Alter table table_name rename to new_table_name;
 Alter table student rename to student123;
50
Defining and deleting integrity
constraint with alter
 Can add and drop primary key
 Syntax:
 alter table table_name add primary key(attribute);
 Alter table table_name add constraint constraint_name
primary key(attribute);
 alter table table_name drop primary key;

 Example:
 alter table student add primary key (rollno);
 Alter table student add constraint pk1 primary key(rollno);
 alter table student drop primary key;
51
Alter Table
 ALTER TABLE table_name Operations
mysql> alter table student add primary key (student_ID);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> describe student;


+---------------+--------------------- +-------+------+----------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+----------------------+-------+------+----------+-------+
| student_ID | int(10) unsigned | | PRI | 0 | |
| name | varchar(20) | | | | |
| major | varchar(10) | YES | | NULL | |
| grade | varchar(5) | YES | | NULL | |
+---------------+----------------------+-------+------+-----------+-------+
4 rows in set (0.00 sec)

52
Drop and Alter Table Constructs
 The drop table command deletes all information about the
dropped relation from the database.
 The alter table command is used to add attributes to an existing
relation:
alter table r add A D
where A is the name of the attribute to be added to relation r and
D is the domain of A.
 All tuples in the relation are assigned null as the value for the new
attribute.
 The alter table command can also be used to drop attributes of a
relation:
alter table r drop A
where A is the name of an attribute of relation r
 Dropping of attributes not supported by many databases

53
Alter Table
 ALTER TABLE table_name Operations

mysql> alter table student drop mobno;


Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> describe student;


+---------------+--------------------- +-------+------+----------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+----------------------+-------+------+----------+-------+
| student_ID | int(10) unsigned | | | NULL | |
| name | varchar(20) | | | NULL | |
| major | varchar(10) | YES | | NULL | |
| grade | varchar(5) | YES | | NULL | |
+---------------+----------------------+-------+------+-----------+-------+
54
4 rows in set (0.00 sec)
Alter with drop command
 To drop a single column
 mysql> alter table stud drop address;
Query OK, 0 rows affected (0.81 sec)
Records: 0 Duplicates: 0 Warnings: 0

 To drop more than one column


 mysql> alter table stud drop id,drop city;
Query OK, 0 rows affected (0.60 sec)
Records: 0 Duplicates: 0 Warnings: 0

55
Restriction of alter Table
 The new column becomes last column by default.
 Width or precision of a numeric column can be increased.
 The width of a column can be decreased if the column
contains only null values or if the table has no rows.
 To change the existing datatype of the attributes it should not
be populated with the data.
 If it is having data then it should be explicitly truncated.

56
Drop Table
 The drop table command removes the data as well as
definition (structure) of an oracle table.
 The database loses all the data in the table and all the indexes
associated with it.

 Syntax:
 drop table table_name;

 Example:
 drop table student;

57
Truncate Table
 It is used to remove all rows from a table and to release the
storage space used by the table keeping in the table definition
intact.

 Syntax:
 truncate table table_name;

 Example:
 truncate table student;

58
Difference between drop and truncate
 When you use the drop statement it deletes the table's row
together with the table's definition so all the relationships of
that table with other tables will no longer be valid.
 When you drop a table:
1. Table structure will be dropped
2. Relationship will be dropped
3. Integrity constraints will be dropped
4. Access privileges will also be dropped
 On the other hand when we TRUNCATE a table, the table
structure remains the same, so you will not face any of the
above problems.

59
Rename Table
 It is used to rename a table, view, sequence, or a synonyms.

 Syntax:
 rename table old_table_name to new_table_name;

 Example:
 Rename table student to student123;

60
SQL Copy Table
 If you want to copy a SQL table into another table in the
same SQL server database, it is possible by using the select
statement.
 Syntax:
select * into <destination_table> from <source_table>;
 Example:
select * into employee from hr_employee;
For example, you can write following command to copy the
records of hr_employee table into employee table.

61
Display Table Structure
mysql> show tables;
+--------------------+
| Tables_in_MyDB |
+--------------------+
| student |
+--------------------+
1 row in set (0.00 sec)
mysql> describe student;
+---------------+----------------------+------+------+----------+--------+
| Field | Type | Null | Key | Default | Extra |
+---------------+----------------------+-------+-----+-----------+-------+
| student_ID | int(10) unsigned | | |0 | |
| name | varchar(20) | | | | |
| major | varchar(50) | YES | | NULL | |
| grade | varchar(5) | YES | | NULL | |
+---------------+----------------------+-------+------+----------+-------+
4 rows in set (0.00 sec)

62
DML
 It is Data Manipulation language.
 DML commands are the SQL commands used to select,
insert on different database objects in an oracle database.
1. INSERT for inserting a new tuple
2. UPDATE to modify data in a table
3. DELETE to delete some tuples from a table
4. SELECT for data retrieval

63
Insert Query Syntax:
 Syntax:
 insert into table_name values(value1, value2, …., valuen);
 Number values can be written as it is where as character
values are written in single Quotes ‘ Shree’.
 Example:
 insert into student values(101,’Shree’,97);
 insert into student values(102,’Sonali’,95),(103,’Tushar’,91);

64
INSERT Query
Insert following values into employee table
empno = 1
empname= ABC
age=66
insert into EMPLOYEE (empno, empname, age) values (3,’PQR’, 77);
insert into EMPLOYEE values(1, ‘ABC’, 66);
insert into EMPLOYEE values(2, ‘XYZ’, 68);
Note : Insertion fails if any integrity constraint is violated

65
Update Query
It is used to modify the contents of the tables.
Case 1: To update all rows of the table
Syntax:
update table_name set attribute_name = new_value
Example:
Update student set city=‘Pune’;

66
Update Query
 To update selective rows (Tuple/records) from the table where the
specifies condition gets satisfied.

 Syntax:
 Update table_name set attribute_name = new where condition;

 Example:
Update student set result=‘Pass’ where marks>=40;

67
Delete Query
 It is used to delete all or specific records from the table.
 Case 1: It is used to delete all rows from the table
 Syntax:
delete from table_name;
 Example:
delete from student;
 It is used to delete all records from student table
 Case 2: It is used to delete specific rows from the table those who satisfied
the given condition. Here we use where clause for condition.
 Syntax:
delete from table_name where condition;
 Example:
delete from student where marks <40;
68
Difference between delete and truncate
 There is a slight difference b/w delete and truncate
statement. The DELETE statement only deletes the rows
from the table based on the condition defined by WHERE
clause or delete all the rows from the table when condition is
not specified.
 But it does not free the space containing by the table.
 The TRUNCATE statement: it is used to delete all the
rows from the table and free the containing space.
 Truncate table is faster and uses lesser resources than
DELETETABLE command.

69
Select Query
 It is used to view the records from the tables. To view all
columns and rows “*” can be specified with select statements.

 Syntax:
select expressions from tables where conditions;
select * from tablename;

 Example:
Select * from student;

70
Select Query- selected columns
 To display selected columns from the table, following syntax
is used.

 Syntax:
 Select column1,column2…. From table_name;

 Example:
 Select rollno, name from student;

71
Select Query- selected rows
 To select the particular rows ‘where’ clause is used.
 Syntax:
 Select * from table_name where condition;
 Example:
 Select * from student where marks >=40;

72
Select Query: Selected rows & columns
 It is used to select specific rows and columns from the tables.

 Syntax:
 Select column1, column2.. From table_name where
condition;

 Example:
 Select name from student where marks>=40;

73
Select Query: Logical operator
 We can use logical operators like AND, OR and NOT.
 Syntax:
 Select * from table_name where condition1 AND condition 2;
 Example:
 Select * from student where marks>=40 AND city=‘Pune’;

74
The where Clause
 A WHERE clause in SQL is a data manipulation language
statement.
 WHERE clauses are not mandatory clauses of SQL DML
statements. But it can be used to limit the number of rows
affected by a SQL DML statement or returned by a query.
 Actually. it filters the records. It returns only those queries
which fulfill the specific conditions.
 WHERE clause is used in SELECT, UPDATE, DELETE
statement etc.
 WHERE clause uses comparison operator (<,>,<)

75
The where Clause
 Syntax:
 Select column1, column 2, ... column n from table_name
where [conditions];

76
The where Clause
 The where clause specifies conditions that the result must
satisfy Corresponds to the selection predicate of the relational
algebra.
 To find all loan number for loans made at the Perryridge
branch with loan amounts greater than $1200.
select loan_number
from loan
where branch_name = 'Perryridge' and amount >
1200
 Comparison results can be combined using the logical
connectives and, or, and not.

77
The select Clause
DistinctVs All

Distinct : if we want elimination of duplicates values for


given column then distinct is used.
Select distinct names from employee;

All: It includes duplicate values also.


Select all names from employee;

78
SQL SELECT UNIQUE
 Actually, there is no difference between DISTINCT and UNIQUE.
 SELECT UNIQUE is an old syntax which was used in oracle
description but later ANSI standard defines DISTINCT as the
official keyword.
 After that oracle also added DISTINCT but did not withdraw the
service of UNIQUE keyword for the sake of backward
compatibility.
 In simple words, we can say that SELECT UNIQUE statement is
used to retrieve a unique or distinct element from the table.
 Syntax:
select unique column_name from table_name;

79
The select Clause (Cont.)
 SQL allows duplicates in relations as well as in query results.
 To force the elimination of duplicates, insert the keyword
distinct after select.
 Find the names of all branches in the loan relations, and
remove duplicates
select distinct branch_name
from loan

 The keyword all specifies that duplicates not be removed.

select all branch_name


from loan

80
The select Clause (Cont.)
 An asterisk in the select clause denotes “all attributes”
select *
from loan;
 The select clause can contain arithmetic expressions
involving the operation, +, –, , and /, and operating on
constants or attributes of tuples.
 E.g.:
select loan_number, branch_name, amount  100
from loan;

81
Format of SELECT
Syntax:
SELECT (list of attributes)
FROM (list of tables)
WHERE (condition)
GROUP BY (attribute name)
HAVING (condition)
ORDER BY (asc/desc);

82
Select Query
 There are some optional clauses in SELECT statement:
 [WHERE Clause] : It specifies which rows to retrieve.
 [GROUP BY Clause] : Groups rows that share a property
so that the aggregate function can be applied to each group.
 [HAVING Clause] : It selects among the groups defined by
the GROUP BY clause.
 [ORDER BY Clause] : It specifies an order in which to
return the rows.

83
Format of SELECT
 Example
SELECT *
FROM student
WHERE roll no > 20
GROUP BY class
HAVING branch = ‘IT’
ORDER BY asc;

84
SQL SELECT TOP
 The SQL SELECT TOP Statement is used to select top data from a
table. The top clause specifies that how many rows are returned.
 If a table has a large number of data, select top statement
determines that how many rows will be retrieved from the given
table.
 MySQL supports the LIMIT clause to fetch limited number of
records while Oracle uses the ROWNUM command to fetch a
limited number of records.
 Syntax:
SQL> select * from table_name limit count;
count defines no. of topmost rows to be retrieved from table.
 Example:
SQL> select * from student limit 3;

85
SQL SELECT TOP
 SQL> SELECT * FROM CUSTOMERSLIMIT 3;This would
produce the following result −
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY
|+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+

86
SQL SELECT FIRST
 The SQL first() function is used to return the first value of
the selected column.
 Syntax:
select first(column_name) as column_name from
table_name;
 Example:
Select first(name) as student_name from student;
 Note: The SELECT FIRST statement is only supported by MS
Access. This statement doesn’t work with other databases like
Oracle, MySQL etc.

87
SQL SELECT Last
 The SQL last() function is used to return the last value of the
selected column.
 Syntax:
select last(column_name) as column_name from
table_name;
 Example:
Select last(name) as student_name from student;
 Note: The select last () statement is only supported by MS
Access. This statement doesn’t work with other databases like
Oracle, MySQL etc.

88
SQL SELECT RANDOM
 The SQL select random() function returns the random row.
It can be used in online exam to display the random
questions.
 There are a lot of ways to select a random record or row
from a database table.
 Syntax:
select column from table order by rand( ) limit1;

89
Use of ‘as’ clause SQL Alias
 we can rename a table or a column temporarily by giving
another name known as Alias.
 The use of table aliases is to rename a table in a specific SQL
statement.
 The renaming is a temporary change and the actual table
name does not change in the database.
 The column aliases are used to rename a table's columns for
the purpose of a particular SQL query.

90
Use of ‘as’ clause SQL Alias
 The basic syntax of a table alias is as follows
 SELECT column1, column2....FROM table_name AS
alias_nameWHERE [condition];
 Select s.rollno, s.name, s.marks, p.mobile from student as s,
parent as p where s.rollno=p.id;

91
Use of ‘as’ clause SQL Alias
 The basic syntax of a column alias is as follows.
 SELECT column_name AS alias_nameFROM
table_nameWHERE [condition];
 select day_of_order AS "Date" Customer As "Client", Prod
uct, Quantity, from orders;

92
Use of ‘as’ clause SQL Alias
 SQL AS is used to assign temporarily a new name to a table column.
 It makes easy presentation of query results and allows the developer to
label results more accurately without permanently renaming table
columns.
 SQL allows renaming relations and attributes using the as clause:
old-name as new-name
 E.g. Find the name, loan number and loan amount of all customers;
rename the column name loan_number as loan_id.
 select customer_name, borrower.loan_number as loan_id, amount
from borrower, loan
where borrower.loan_number = loan.loan_number

93
Use of “as” clause
 Tuple variables are defined in the from clause via the use of the as
clause.
 Find the customer names and their loan numbers and amount for all
customers having a loan at some branch.
 select customer_name, T.loan_number, S.amount from borrower as T, loan
as S where T.loan_number = S.loan_number
 Find the names of all branches that have greater assets than some
branch located in Brooklyn
 select distinct T.branch_name from branch as T, branch as S
where T.assets > S.assets and S.branch_city = 'Brooklyn'
 Keyword as is optional and may be omitted
borrower as T ≡ borrower T
 Some database such as Oracle require as to be omitted

94
Select queries
SELECT <list of attributes> FROM <list of tables> WHERE
<condition> (Optional)
1. List of full details of all employees:
SELECT * FROM employee;
2. List the all employees showing code, name and salary
detail:
SELECT code, name, salary FROM employee;
3. List the name, birth date and address of all employees with
a salary greater than 20000.
SELECT name, DOB, address FROM employee WHERE
salary>20000;
95
Order By Clause
 The result of a query can be ordered in ascending order using the clause
ASC or in descending order using the clause DESC.
 SELECT code, name, salary FROM employee ORDER BY salary
DESC;

Multiple column ordering:


 Produce a list of salaries of all employees, arranged in descending order
of salary and for the same salary in ascending order of employee code.
 SELECT code, name, salary FROM employee ORDER BY salary
DESC, code ASC;

96
Ordering the Display of Tuples
 List in alphabetic order the names of all customers having a
loan in Perryridge branch
select distinct customer_name
from borrower, loan
where borrower loan_number = loan.loan_number and
branch_name = 'Perryridge'
order by customer_name
 We may specify desc for descending order or asc for
ascending order, for each attribute; ascending order is the
default.
 Example: order by customer_name desc

97
Group by clause
 The GROUP BY statement is often used with aggregate functions
(COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or
more columns.
 It arranges data rows into groups according to the columns you
specify.
 It allows multiple columns to be grouped so aggregate functions may
be performed on multiple columns with one commands.

98
Group By Clause
 Syntax:
 select column_name(s) from table_name where condition
group by column_name(s) order by column_name(s);
 Example:
 Select count (customerID), country from customers
group by Country;

99
Having Clause
 The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.
 It is similar to where clause but processing is different.
 Where operates on individual row where as having operates on
groups
 E.g. Student (rno, name, class, branch)

Select * from student


group by class
having branch= ‘IT’;

100
Having clause
 Syntax:
 select column_name(s) from table_name where condition
group by column_name(s) having condition order by
column_name(s);

 Example:
 Select count(CustomerID), country from Customers group
by Country having count(CustomerID) > 5;

101
View Definition
 VIEWS are virtual tables .By virtual, we mean, the tables do
not store any data of their own but display data stored in other
tables.
 The difference between a view and a table is that views are
definitions built on top of other tables (or views).
 If data is changed in the underlying table, the same change is
reflected in the view. A view can be built on top of a single or
multiple tables.

102
View (Virtual Table) in SQL:
 CREATEVIEW view_name As query_expression;
 A view is a virtual table that is derived from other tables.
 It does not actually exist.
 It is made up of a query on other tables.
 A view can be used to restrict the user to certain rows and certain
columns.
 View does not exist as a stored table in a database.
 Only the definition of view is stored in the database; in case of a
reference to a view a virtual table is created.

103
Advantages of Views (Virtual Table)
1.Security  A view can be used to restrict the users to certain
rows/columns that concern them.
2. Data Integrity  The WITH CHECK OPTION clause is used to
enforce the query conditions on any updates to the view. If the view
shows data for a particular department the user can enter data for
that department.
3. Simplicity  Even if a view is a multi-table query, querying a view
will look like a single table query.
4. Protection from change  Even if the structure of the database
changes, the user’s view of data can remain the same.

104
Syntax of View
 CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

105
How to create Virtual Table (View)
 Consider employee table
 create table employee(eid int, ename varchar(25), dept
varchar(25), desg varchar(25), sal real(7,2));

Eid Ename Dept Desg sal

1 kedar IT Professor 60000

2 John comp Professor 60000

3 Smith Comp HOD 80000

 Create view emp_view as (select eid, ename, dept from


employee);
106
SQL CREATE OR REPLACE VIEW Syntax
 Syntax:
 CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
 Example:
 CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID, ProductName, Category
FROM Products
WHERE Discontinued = No;

107
View Updatability
 create view employee3 AS SELECT code, name, salary from
employee;

 insert into employee3VALUES (105,’abc’,2400);

 SQL DROP VIEW Syntax

 DROP VIEW view_name;


 drop view employee3;

108
Update of a View
 Create a view of all loan data in loan relation, hiding the amount attribute
create view branch-loan as
select branch-name, loan-number
from loan
 Add a new tuple to branch-loan
insert into branch-loan
values (‘Perryridge’, ‘L-307’)
This insertion must be represented by the insertion of the tuple
(‘L-307’, ‘Perryridge’, null)
into the loan relation
 Updates on more complex views are difficult or impossible to translate, and hence are
disallowed.
 Most SQL implementations allow updates only on simple views (without aggregates)
defined on a single relation
Indexes
 The CREATE INDEX statement is used to create indexes in tables.
 Indexes are used to retrieve data from the database very fast. The users
cannot see the indexes, they are just used to speed up
searches/queries.
 CREATE INDEX Syntax:
Creates an index on a table. Duplicate values are allowed:
Create index index_name ON table_name (column1, column2, ...);
 CREATE UNIQUE INDEX Syntax:
Creates a unique index on a table. Duplicate values are not allowed:
create unique index index_name on table_name (column1, column2, ...);

110
Index Creation
• create table student
(ID varchar (5),
name varchar (20) not null,
dept_name varchar (20),
tot_cred numeric (3,0) default 0,
primary key (ID))

• create index studentID_index on student(ID)


• Indices are data structures used to speed up access to records with specified values
for index attributes
– e.g. select *
from student
where ID = ‘12345’
can be executed by using the index to find the required record, without looking at
all records of student

111
Index
 Example:
Create index student_index on student (rollno,name,marks);

 Drop Index in mysql


 Alter table table_name drop index index_name;

112
Transaction control
 Transactions group a set of tasks into a single execution unit. Each
transaction begins with a specific task and ends when all the tasks in
the group successfully complete. If any of the tasks fail, the transaction
fails. Therefore, a transaction has only two results: success or
failure.
 Incomplete steps result in the failure of the transaction. A database
transaction, by definition, must be atomic, consistent, isolated and
durable.These are popularly known as ACID properties.
 TCL commands are used to control transactions. It is important to
note that these statements cannot be used while creating tables and
are only used with the DML Commands such as – INSERT, UPDATE
and DELETE.

113
 1. SET TRANSACTION: Places a name on a transaction.
Syntax:
 SET TRANSACTION [ READ WRITE | READ ONLY ];
 2. COMMIT: If everything is in order with all statements
within a single transaction, all changes are recorded together
in the database is called committed. The COMMIT
command saves all the transactions to the database since the
last COMMIT or ROLLBACK command.
 Syntax:
COMMIT;

114
 Example: Sample table 1
 Following is an example which would delete those records
from the table which have age = 20 and then COMMIT the
changes in the database.

 Queries:
 DELETE FROM Student WHERE AGE = 20; COMMIT;
115
 Queries:
DELETE FROM Student WHERE AGE = 20;
COMMIT;
Output:
Thus, two rows from the table would be deleted and the
SELECT statement would look like,

116
 3. ROLLBACK: If any error occurs with any of the SQL
grouped statements, all changes need to be aborted. The process
of reversing changes is called rollback. This command can only
be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.
 Syntax:
 ROLLBACK;
 Example: From the above example Sample table1, Delete
those records from the table which have age = 20 and then
ROLLBACK the changes in the database.

117
 Queries:
 DELETE FROM Student WHERE AGE = 20;
 ROLLBACK;
 Output:

118
 4. SAVEPOINT: creates points within the groups of transactions in
which to ROLLBACK. A SAVEPOINT is a point in a transaction in
which you can roll the transaction back to a certain point without
rolling back the entire transaction.
 Syntax for Savepoint command:
 SAVEPOINT SAVEPOINT_NAME;
 This command is used only in the creation of SAVEPOINT among all the
transactions.
 In general ROLLBACK is used to undo a group of transactions.
 Syntax for rolling back to Savepoint command:
 ROLLBACK TO SAVEPOINT_NAME;
 you can ROLLBACK to any SAVEPOINT at any time to return the
appropriate data to its original state.
 Example:
 From the above example Sample table1, Delete those records from
the table which have age = 20 and then ROLLBACK the changes in the
database by keeping Savepoints.

119
 Queries:
 SAVEPOINT SP1; //Savepoint created.
 DELETE FROM Student WHERE AGE = 20; //deleted
 SAVEPOINT SP2; //Savepoint created.
 Here SP1 is first SAVEPOINT created before deletion. In this
example one deletion have taken place. After deletion again
SAVEPOINT SP2 is created.
 Output:

120
 Deletion have been taken place, let us assume that you have
changed your mind and decided to ROLLBACK to the
SAVEPOINT that you identified as SP1 which is before
deletion.
deletion is undone by this statement ,
 ROLLBACK TO SP1; //Rollback completed.

 Notice that first deletion took place even though you rolled
back to SP1 which is first SAVEPOINT.
121
 5. RELEASE SAVEPOINT:- This command is used to
remove a SAVEPOINT that you have created.
 Syntax:
 RELEASE SAVEPOINT SAVEPOINT_NAME;
 Once a SAVEPOINT has been released, you can no longer
use the ROLLBACK command to undo transactions
performed since the last SAVEPOINT.

122
Authorization:
 Forms of authorization on parts of the database:
 Read :- allows reading, but not modification of data.
 Insert:- allows insertion of new data, but not
modification of existing data.
 Update: -allows modification, but not deletion of data.
 Delete:- allows deletion of data.

123
Authorization Specification in SQL
 The grant statement is used to confer authorization
grant <privilege list>
on <relation name or view name> to <user list>
 <user list> is:
 a user-id public, which allows all valid users the privilege
granted A role
 Granting a privilege on a view does not imply granting any
privileges on the underlying relations.
 The grantor of the privilege must already hold the privilege on the
specified item (or be the database administrator).

124
Authorization Specification in SQL
 Grant select on department to Kedar, Smith;

 Grant update(budget) on department to Kedar, Smith;

125
Revoking Authorization in SQL
 The revoke statement is used to revoke authorization. It takes back
privileges granted from user.
revoke <privilege list> on <relation name or view name> from <user
list>
 Example:
revoke select on branch from U1, U2, U3
 <privilege-list> may be all to revoke all privileges the revokee may hold.
 If <revokee-list> includes public, all users lose the privilege except those
granted it explicitly.
 If the same privilege was granted twice to the same user by different
grantees, the user may retain the privilege after the revocation.
 All privileges that depend on the privilege being revoked are also revoked.

126
Introduction to MySQL
 MySQL is the world's most popular open source database
software, with over 100 million copies of its software downloaded
or distributed throughout it's history.

 MySQL is a relational database management system ( RDBMS )


and which runs a server, providing multi-user access to a number
of databases.

 With its superior speed, reliability, and ease of use, MySQL has
become the preferred choice for IT in all sectors or domains.

127
Uses
 Many web applications use MySQL as the database component of a
LAMP (Linux (operating system), Apache HTTP Server, MySQL
(database software), and PHP, Perl or Python) software stack.

 Its popularity for use with web applications is closely tied to the
popularity of PHP , which is often combined with MySQL.

 Several high-traffic web sites includes: Flickr, Facebook, Wikipedia,


Google, Nokia and YouTube use MySQL for data storage and
logging of user data.

128
Client-Server Interaction
Make a request
(SQL query)

MySQL Client
Server Get results Program

Client program can be a MySQL command line client,


GUI client, or a program written in any language such as
C, Perl, PHP, Java that has an interface to the MySQL
server.
129

You might also like