Database Management and MySQL Part - 1

You might also like

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

Database Management

What is Database?
► A database system is basically a computer based record system
which can be defined as a collection of logically related data
items stored together to be manipulated by multiple applications.
► The intention of a database is that all related data of any
organization will be stored in a central place and all applications
will use the data for different purpose.
► In other words, a database is used by an organization as a method
of storing, managing and retrieving information. Databases are
managed using a database management system (DBMS).
Need of database systems
► 1. Databases reduce the data redundancy:

The database system do not maintain separate copies of the same data,
rather all the data are kept at one place and all application that require
data refer to the centrally maintained database. If any change is to be
made it will be made at just one place and the changed information will
be available to other applications.

► 2. Databases can control data inconsistency:

When data redundancy is not controlled, there may be occasions on which


out of the two entries of the same data , one of them stores the updated
version and the other does not. In that case the database is said to be
inconsistent. By controlling the data redundancy, inconsistency is also
controlled.
Need of database systems
► 3. Database facilitates sharing of data:
In a database system all the users handling different related applications
refer and share the same data stored in a central location.

► 4. Database enforces standards


Database management system can ensure that all the data follow the
applicable standard laid by the organization.

► 5. Integrity can be maintained:


When a database contains data to be used by many users, it is important
to keep integrity to check to insure that data values satisfy to certain
specified rules.

► 6. Database can ensure security:


A database ensures security and privacy by ensuring that only the
authorized person can access the database.
Database Management System(DBMS)
DBMS is a set of programs that enables the user to create, maintain and
manage the database. A DBMS provides the facilities of :
 Creates structure of data storage in a database
 Provides query mechanism to retrieve specified data according to a
condition.
 Updating of database i.e. addition of new records, editing and deleting
data items etc.
 Organize the data in the database i.e. arranging it ascending or
descending order
Examples of popular DBMSs are MySQL, PostgreSQL, Microsoft Access,
Oracle etc
RDBMS Terminology
Relation or Table
A relation refers to the collection of
logically related data items stored in
rows and columns (Tabular form)
Domain
A domain is a set of values from which
one or more attribute (column) draw
their actual values.
Tuple
The rows or records of tables are
referred as a Tuple.
Attributes
The columns or fields of tables are
generally referred to as attributes.
RDBMS Terminology

Degree
The number of attributes
(columns) in a relation is called
the degree of a relation.

Cardinality
The number of tuples (rows) in a
relation is called the cardinality
of the relation.

Degree – 5 Cardinality - 5
RDBMS Terminology
Keys : Keys refers to fields of a table which are
used to
► To maintain uniqueness of a tuple (row) in a
table.
► To create relationships between two tables.

Primary Key: A primary key is a set of one or more


attributes that can uniquely identify the rows
within a table. The primary key column stores
unique values and can not be empty
Composite Key: In certain tables, when
combination of two or more attributes is used as
Primary Key. Such keys are called Composite Keys.
Candidate Key: All attributes in a table that can
become Primary Key are called candidate keys.
Alternate Key: A candidate key that is not the
Primary key is called an Alternate key.
Features Of Relation/Table
► Each relation in a database must have a distinct or unique
name which would separate it from the other relations in a
database.
► A relation must not have two attributes with the same name.
Each attribute must have a distinct name.
► Duplicate tuples must not be present in a relation.
► Order of tuple in a relation is irrelevant.
► A relation does not allow composite and multivalued attributes.
► if the value of any attribute of a tuple does not exist it is
denoted as having NULL values. Null value in MySQL is not same
as 0 or space. It is denoted as an undefined value
Advantages Of MySQL
► MySQL is a very reliable and high performance Relational
Database Management System.
► MySQL provides the user with a rich set of features that
support a secure environment for storing, maintaining and
accessing data.
► Being an open-source software, MySQL is easily modifiable
► MySQL supports several different platforms like UNIX, Linux,
Mac OS X and Microsoft Windows.
► MySQL is a powerful, easy, compatible and fast Relational
Database Management System. It can handle complicated
applications and processing requirements.
► Integrity (Checks): MySQL provides various integrity checks in
order to restrict the user input and processing.
Assessment
What is the full Form of SQL
a. Standard Query Language
b. Structured query Language
c. Simple query Languange
d. Sequential Query Language

Answer : b. Structured query Language

RDBMS is a type of ____________ Software


a. System Software
b. Application Software
c. General Software
d. Utility Software

Answer : b. Application Software


Assessment
Mr X created a table with 5 columns and 10 records. He removed 3 records from
the table. What is the cardinality and degree of the table
a. 5 and 10
b. 5 and 7
c. 7 and 10
d. 7 and 5

Answer : d. 7 and 5

Which of the following refers to copies of the same data stored multiple times
a. Data Inconsistency
b. Data integrity
c. Data Redundancy
d. Data Mining

Answer : c. Data Redundancy


Assessment
A record of a relation is known as
a. Degree
b. Tuple
c. Attribute
d. Cardinality

Answer : b. Tuple

Mr X finds data of one of his student stored in two different tables not matching
with each other. Which issue is discussed here
a. Data Redundancy
b. Data Integrity
c. Data reference
d. Data Inconsistency

Answer : d. Data Inconsistency


Assessment
.................. are words that have a special meaning in SQL
a. Reserved Word
b. Literal
c. Relation
d. Domain

Answer : a. Reserved Word

All data items describing of an entity are grouped to form a


a. Tuple
b. Attribute
c. Relation
d. Degree

Answer : c. Relation
Assessment
An advantage of RDBMS is
a. Data is dependent on application
b. It increases data Redundancy
c. Data can be accessed by multiple application
d. Data is Platform Dependent

Answer : c. Data can be accessed by multiple application

An attribute which can uniquely describe each tuple of a table is


a. Foreign key
b. Candidate Key
c. Degree
d. Primary Key

Answer : d. Primary Key


Assessment
An advantage of RDBMS is
a. Data is dependent on application
b. It increases data Redundancy
c. Data can be accessed by multiple application
d. It is Platform Dependent

Answer : c. Data can be accessed by multiple application

An attribute which can uniquely describe each tuple of a table is


a. Foreign key
b. Candidate Key
c. Degree
d. Primary Key

Answer : d. Primary Key


Assessment
Which one of them is invalid for MySQL
a. MySQL is required to be purchased from a vendor
b. It is a RDBMS
c. In MySQL Data can be stored in a table
d. It is Platform independent

Answer : a. a. MySQL is required to be purchased from a vendor

Which one of them is NOT valid for Primary Key of a table


a. It can not have duplicated entry
b. It can not have Null values
c. It can not be duplicated but can be empty
d. It can not be duplicated and can not be empty

Answer : c. It can not be duplicated but can be empty


Assessment
The columns which are suitable to be Primary Key are known as
a. Candidate key
b. Alternate Key
c. Foreign Key
d. Composite Key

Ans a. Candidate key


wer
:
Which one is NOT valid for Alternate Key is
a. It can be a Primary Key
b. It is one of the Candidate key
c. It can not have duplicate value but can be empty
d. It can not be duplicated and can not be empty

Answer : c. It can not be duplicated but can be empty


Assessment
The Vertical Subset of a relation is known as
a. Tuple
b. Attribute
c. Cardinality
d. Composite Key
Answer : b. Attribute

The set of values from which attribute of a relation can draw their values is known
as :
_____________

Answer : domain
Assessment
For the table trainer
TID ACCT_NO CITY HIREDATE SALARY
101 A001 MUMBAI 1998-10-15 90000
102 S003 DELHI 1994-12-24 80000
103 A004 DELHI 2001-12-18 20000
The attributes which can become primary keys are:
a. TID, City
b. TID, HIREDATE
c. TID, ACCT_NO
d. None of the above

Answer : c TID, ACCT_NO


Assessment
For the table trainer
TID ACCT_NO CITY HIREDATE SALARY
101 A001 MUMBAI 1998-10-15 90000
102 S003 DELHI 1994-12-24 80000
103 A004 DELHI 2001-12-18 20000
The attributes which can become primary keys are:
a. TID, City
b. TID, HIREDATE
c. TID, ACCT_NO
d. None of the above

Answer : c TID, ACCT_NO


Assessment
For the table trainer
TID ACCT_NO CITY HIREDATE SALARY
101 A001 MUMBAI 1998-10-15 90000
102 S003 DELHI 1994-12-24 80000
103 A004 DELHI 2001-12-18 20000
When TID, ACCT_NO are suitable to be primary keys, these columns are known as
a. Composite key
b. Candidate key
c. Alternate key
d. Foreign key

Answer : b Candidate key


Assessment
For the table trainer
TID ACCT_NO CITY HIREDATE SALARY
101 A001 MUMBAI 1998-10-15 90000
102 S003 DELHI 1994-12-24 80000
103 A004 DELHI 2001-12-18 20000
The attribute TID is selected as the Primary key, then Acct_No will be referred as:
a. Composite key
b. Secondary key
c. Alternate key
d. Foreign key

Answer : c. Alternate key


MySQL - RDBMS
MySQL is a relational database management system (RDBMS)
which:
 MySQL is a freely available open source Relational Database
Management System (RDBMS) that uses SQL (Structured query
language).
 It is downloadable from site www.mysql.org
 A single MySQL Relational database can contain many
tables at once and store thousands of individual records.
 It has easy to use interface and is an easy to install
RDBMS .
 It is platform independent which works on many
operating systems like Windows, UNIX, LINUX etc.
MySQL
To use MySQL
• Download MySQL from www.mysql.org
• Click on MySQL Command Line Client to load the software.
• Once it is loaded the password screen of MySQL appears.
Once password is entered, the MySQL prompt appears,
where SQL commands need to be typed,
To come out of MySQL application, quit to be given in front of
the mysql> command prompt.
Data types in MySQL
A data type specifies the possible values for that type, the
operations that can be performed on that type and the way
the values of that type are stored.
In SQL, each column of the table is assigned a datatype
which conveys the kind of value that will be stored in the
column.
SQL supports 3 basic types of Data Type
► Character Data Type
► Numeric Data Type
► Date and Time
Data types in MySQL
Character data type :
Char (w)
► represents fixed length character data of the specified length "w"
where w can be any integer.
► The maximum size is 255 characters.

► If the number of characters entered in a CHAR data type column is


less than the declared column length, spaces are appended to it to
fill up the whole length.
Varchar(w)
► represents variable length character data of the specified length
"w" where w can be any integer
► The maximum size is 65,535 characters.

► Unlike CHAR data type, for VARCHAR the length of the field is the
actual length in bytes of the data entered.
All character data items of MySQL should be enclosed within single or
double quotes.
Difference Between Char and Varchar
Data types in MySQL
Numeric data type
Numeric data type represents data which can be used for calculation
➢ Int/ Integer(w):
int/integer data type represents integer data (signed or unsigned) of
width w. By default it is 11 digits
➢ Decimal(m,d)
Decimaldata type represents floating point numbers. m is the length
and the number of decimals is represented by d

Date datatype
Date type Represents all valid dates in the format of YYYY-MM-DD. The
date data items should be enclosed in single or double quotes.

Time datatype
Time - represents time. Format: HH:MM:SS
MySQL commands
MySQL commands are basically the instructions given to SQL
database for to manipulate and manage data stored in
different tables through commands.

MySQL commands are combination of Keyword/ Reserved


Word and clause

The SQL commands use the following formats -:


► Every SQL command starts with the keywords/Reserved
words followed by clause.

► Every SQL statement ends with a semicolon (;)

► SQL commands are not case sensitive.


Categories of SQL commands
Data definition language (DDL)
This category of commands are
► used to create database and tables

► define the physical characteristics of a table like determining

each field’s name, its data type and its length within a table
► modifications of table structure like changing the length of a

field, adding a new field etc.


► Commands to create table, drop table, alter table etc. come
under this category.
Data manipulation language (DML)
► This category of commands manipulates the data and perform

the operations like retrieval of information from database,


insertion of new record, deletion and modification of records
SQL commands
Create database command
Every table in MySQL should be included under a database. New
database in MySQL are created using the Create database command.
Syntax: Create database <database name>;
Example: Create database Emp;
Category : DDL
Show databases;

Use command
Once the database is created, it needs to be opened to work on it. Use
command is used to open the database. Once the database is opened,
any table created, will be stored under it.
Syntax: Use <database name>;
Example: Use Emp;
Category : DML
SQL commands
Create Table Command
After creating the database CREATE TABLE command creates an
empty table i.e a table with no rows. While creating the table the
table name, column name, data type and width of the column are
given.
Syntax:
Create Table <table-name>(<column name1><data type><size>,
<column name2><data type> [(<size>]
………………...);
Example:
Create table employee (empno char(6), name varchar(15),
basic decimal(8,2), dept varchar(10), dob date);
Category : DDL
SQL commands
SHOW TABLES command
This command helps to view names of all the tables contained
in the current database
Syntax : Show Tables;
Category : DML
Viewing Structure of the table
The DESCRIBE statement is used to see the structure of a
table. It displays the Column names, their data types, along
with its constraint like Primary key etc.
Syntax : DESCRIBE <table_name>;
OR DESC <table_name>;
Example : Desc employee;
Category : DML
SQL commands
Adding Records Using Insert Into
Insert into command adds new rows (records) to a table.
Syntax : Insert into <table name> values (<field
name1>, <field name2,....]);
Example : Insert into employee values (‘1’, ‘Raju’,
12000, ‘Acct’,’1979-01-12’);
► While providing data items for char and varchar fields, enclose

the data item in single/double quotes.


► For the date fields, the data item is given in the format of yyyy-

mm-dd and required to be enclosed in single/double quotes.


► One Insert Into command will insert a single record in the table.

For inserting multiple records in the table, multiple commands


have to be given.
Category : DML
SQL commands
INSERT INTO Command for specific filelds
If only specific fields of the new record to be filled with data item, the
column name for which data will be supplied with corresponding data values
are required to be given in the INSERT statement
Syntax : INSERT INTO <tablename> (<column1>,
<column2>, ..., <column n>)
VALUES (<value1>, <value2>, ... <value n>);
Example : INSERT INTO employee (Empno, Name, DOB) VALUES
(‘1’, ‘Raman’, ’2017-01-17’);
Rest of the field for which values are not supplied will have NULL stored in
it.
When some data fields of a record are not known, null can be written in
that place.
Example : Insert into employee values (‘1’, ‘Raju’, null, null,’1979-01-12’);
SQL commands
Select Command
Select command is used to specify query. A query is a command
that produces specific information from the table of a database.
Selecting the whole table
Syntax : Select * From<table name>;
Example : Select * from employee;
will display all the records from the table
Category : DML
Selecting specific columns
To display only few columns from the table, the names of the
columns can be specified after Select
Syntax : Select <Column name>, <Column name>.. From
<table name>;
Example : Select Empno, Name, Basic from employee;
will display empno, name and basic columns from the table
employee
SQL commands
Selecting specific rows using Where
The Where clause is used to display only those rows, which
satisfy the specified condition. You can use any relational
operator (>, <, >=, <=, <>, =) to form a condition.
Syntax : Select * from <table name> where
<condition>;
Example : Select * from employee where Dept =’Acct’;
select * from employee ehere dept<>’Acct’;
: Select empno, name from employee where
basic>12000;
: Select * from employee where dob>”1979-
01-01”;
SQL Commands
Example :
Selecting specific rows using Where WITH Logical Operators
Example with AND operator
Select * from employee where Dept =’Acct’ AND Basic>10000;
Select * from employee where basic>3000 and basic <6000;
Example with OR operator
Select * from employee where Dept =’Acct’ OR Dept =’Sys’;
Example with NOT operator
Select * from employee where NOT (Dept = ’Acct’);
SQL Commands
Selecting specific rows using Where WITH Logical Operators
Multiple conditions can be specified by using Logical operators
(And, Or and Not)
The AND operator displays a record and returns a true value if all
the conditions (usually two conditions) specified in the WHERE
clause are true.
The OR operator displays a record and returns a true value if either
of the conditions (usually two conditions) specified in the WHERE
clause is true.
NOT operator is also termed as a negation operator. Unlike the
other two operators, this operator takes only one condition and
gives the reverse of it as the result. It returns a false value if the
condition holds true and vice versa.
SQL commands
SELECT to using IN operator
The IN operator is used to specify a list of values. This operator
selects rows that match any value in a given list of values.
Example : SELECT NAME, dept, basic FROM employee
WHERE dept IN (‘accts’, "admn’, ‘marketing’);
This statement will display employee name, dept and basic of those
employees whose dept is either accts, admn or marketing from
table employee
Select name,dept,basic from employee where dept=‘accts’ or
dept=‘admn’ or dept=‘marketing’;
SELECT to using NOT IN operator
The NOT IN operator selects rows that do not match any value in a
given list of values.
Example : SELECT NAME, dept, basic FROM employee
WHERE dept NOT IN (‘accts’, "admn’,
‘marketing’);
SQL commands
SELECT using BETWEEN clause
BETWEEN defines a range of values that the column value can
fall in. The range includes both lower and upper values.
Example : SELECT name, basic FROM employee
WHERE basic BETWEEN 12000 AND 15000;
This statement will display names and basic of employees
whose basic is greater than or equal to 12000 and less than or
equal to 15000 select name,basic from employee where
basic>=12000 and basic<=15000;
SELECT using NOT BETWEEN clause
The operator NOT BETWEEN is reverse of BETWEEN operator,
that is the rows not satisfying the BETWEEN condition are
retrieved
Example1 : SELECT * FROM employee WHERE basic NOT
SQL commands
SELECT Using LIKE operator
Like operator of MySQL is used to retrieve data from a table which matches
the specified pattern from a table.
There are 2 wildcards used to represent the pattern:
► % is used to represent any sequence of 0 or more characters,
► _ is used to represent a single character
Example : SELECT * FROM employee WHERE Name like ‘G%’;
will display the records of all employees whose name starts with G.
Example : SELECT Empno, Name FROM employee WHERE Name
like ‘%SINGH%’;
will display records of employees whose name is containing SINGH.
Example : SELECT * FROM employee WHERE Name like ‘_ _%’;
will display the employee records of whose name is containing at least 2
characters
Example :SELECT * FROM employee WHERE Name like ‘%G’;
will display the details of all employees whose name is ending with G
SQL Commands
Selecting With IS NULL
The NULL value can be searched using IS NULL in the where clause .
Syntax : Select * from <table name> where
<column_name> IS NULL;
Example : Select * from employee where Dept IS NULL;
Select with Distinct
The DISTINCT keyword is used in the SELECT statement to eliminate
all the duplicate records and fetching only unique records. Distinct
clause can be specified only once in a Select statement
Syntax : Select DISTINCT <column Name> from <table
name>

Example : Select distinct dept from employee;


It will display all distinct department names.
SQL commands
Sorting the selected records by - Order By
In general, the rows displayed from a query do not have any order The
Order by clause allows sorting of query result by one or more columns in
descending or ascending order.
In a SQL statement the ORDER BY clause has to appear at the last.
Syntax : Select * from <table name>
WHERE <condition> ORDER BY <the column
<ASC/DESC>;
Example : Select * from employee WHERE Basic > 2500 order
by Name;
When <ASC/DESC> is not mentioned, by default MySQL will arrange the
table in ascending order
Sorting of records can also be performed on multiple attributes.
Example : Select * from employee order by dept asc, gross
desc;
SQL commands
Select For calculated result
Calculated result can also be displayed using expression with
mathematical operator in select statement
Example : SELECT empno, 0.12*basic from employee;
will display calculated values (12% of basic) with empno from employee
table.
Example : SELECT 12 + 10 % 3 as “calculated Value”;
SELECT using Column Alias
When displaying the result of a query the name of the selected column or
expression is usually displayed as column heading. To change the column
heading for a more descriptive name column alias can be used.
Example : SELECT empno, 0.12*basic Bonus from employee;
This statement displays the calculated result under the heading Bonus
which is given as Alias.
When alias has multiple words it has to be given in double quotes.
Example : SELECT empno As “Employee No”, 0.012*basic “Calculated
Bonus” from employee;
Assessment
Give Commands to do the following:
Create a database Teachers
Answer : CREATE DATABASE teachers;

Open the database Teachers


Answer : USE teachers;

Create a table teacher with Tid (int(4) Primary key, name


Varchar(20) Not null, sub Varchar(10), experience int(2),
salary Decimal(12,2)
Answer : CREATE TABLE teacher (tid int(4) PRIMARY KEY, name
VARCHAR(20) NOT NULL, subject VARCHAR(10), Exp
int(2), salary DECIMAL(12,2));
Assessment
Give Commands to do the following:
Insert a Record (1,Rajan, Maths, 12, 12000)
Answer : INSERT INTO teacher VALUES(1,”Rajan”, “Maths”, 12, 12000)

If the table has 5 more rows, what will be the degree and Cardinality of Teacher

Answer : Degree – 5, Cardinality - 6

The user tried to insert another record with values (1,Raji, Maths, 2, 7000). But
MySQL showed error for this. What can be the reason

Answer : Same t_id 1 cannot be entered as T_id is Primary Key


Assessment
Give Commands to do the following:
Display the structure of the table
Answer : DESCRIBE teacher;

Mr. X created a database students successfully. But when he tried to create a


table it resulted an error. What can be the reason
Answer : Database is not opened

The user tried to insert another record with values (Null, Raji, Maths,
2, 7000). But MySQL showed error for this. What can be the reason

Answer : Same t_id column cannot allow null value as it is a is


Primary Key
Assessment
Give Commands to do the following:
Which keyword is used to give a condition in SQL command

Answer : WHERE clause

Which keyword is used to match a field with a specified set of values

Answer : IN operator

Which command is used to show all tables stored under a given


database
Answer : SHOW TABLES
Assessment
Give Commands to do the following:
When a column is left empty, MySQL will automatically filled the column with
__________

Answer : NULL

________ key word can be used to search for a column to check whether it is
empty or not.

Answer : IS NULL

The equivalent of the command


SELECT * FROM student WHERE perc BETWEEN 90 and 100;

Answer : SELECT * FROM student WHERE perc>=90 and perc


<=100;
Assessment
Give Commands to do the following:
The like clause to represent Khan appearing anywhere in a name is ________

Answer : Name LIKE “%Khan%”

Command which will display the names of department existing in Emp table.
The Department names should appear only once

Answer : SELECT DISTINCT dept FROM employee;

The equivalent of the command


Select * from employee where dept<>’accts’ and dept<>’Fin’ and dept<>’sys’;

SELECT
Answer : * FROM SELECT
employee WHERE
* FROM Dept WHERE
employee NOT in(“accts”, “FIN”,or“SYS”)
Not (dept=“accts”
dept=“Fin” or Dept =“sys”);
Assessment
Consider a table BUS having fields – bus_no, Area, capacity,
tot_studs, distance, Transporter, charges, dt_of_cont. Give
commands to do the following
Display all the Bus details of those bus where no of students
travelled is more than 100.
Answer : SELECT * FROM Bus WHERE tot_studs>100;

Display Bus no and Area of those bus whose charges is more than
50000.
Answer : SELECT bus_no, area FROM Bus WHERE charges>50000;

Display the details of the Anand travels and Bhalla co. transporters
Answer : SELECT * FROM Bus WHERE transporter = “Anand travels”
OR transporter = “Bhalla co. “;
Assessment
Consider a table BUS having fields – Bus_no, Area, capacity,
tot_studs, distance, Transporter, charges, dt_of_cont. Give
commands to do the following
Display all the records arranged in descending order of Total
Students
Answer : SELECT * FROM Bus ORDER BY tot_studs DESC;

Display the name of transporters only once.


Answer : SELECT DISTINCT transporter FROM Bus;

Display the details all bus records which has the word travels in the
transporters field.

Answer : SELECT * FROM Bus WHERE transporter LIKE “%travels%;


Assessment
Consider a table BUS having fields – bus_no, Area, capacity,
tot_studs, distance, Transporter, charges, dt_of_cont. Give
commands to do the following
Display all the bus records whose distance is more than 20 and
Area is south
Answer : SELECT * FROM Bus WHERE distance>20 and Area=“South”;

Display bus_no and Transporter whose charges are between 50000


and 75000
Answer : SELECT bus_no, transporter FROM Bus WHERE charges
between 50000 and 75000;

Display the details all bus records whose area field not filled by
the user
Answer : SELECT * FROM Bus WHERE area is Null;
Assessment
Consider a table BUS having fields – Bus_no, Area, capacity,
tot_studs, distance, Transporter, charges, dt_of_ct. Give commands
to do the following
Display all Bus_no and Area whose Transporter name is starting with
Delhi and area is North
Answer : SELECT Bus_no, Area FROM Bus WHERE Tranporter like
“Delhi%” and Area=“North”;

Display all records whose charges are less than 10000 and tot_studs
are 50
Answer : SELECT * FROM Bus WHERE charges <10000 and tot_studs
=50;

Display theBus no, Area, Transporter and total amount (= tot_studs *


charges of all Buses) which are in East area
Answer : SELECT Bus_no, Area, Transporter. Tot_studs*charges “total
amount” FROM Bus WHERE area =“East”;
Assessment
Consider a table BUS having fields – Bus_no, Area, capacity,
tot_studs, distance, Transporter, charges, dt_of_ct. Give commands
to do the following
Display all Bus_no and Area have taken contract in the year 2020
Answer : SELECT Bus_no, Area FROM Bus WHERE dt_of_ct
BETWEEN “2020-01-01” and “2020-12-31”

Display all records arranged in ascending order of area and within it


descending order of charges
Answer : SELECT * FROM Bus ORDER BY area, charges DESC;

Display the Bus no and Transporter who have taken contract in the
month of January 2021
Answer : SELECT Bus_no, Transporter FROM Bus WHERE dt_of_ct
BETWEEN “2021-01-01” and “2021-01-31”;
SQL commands
Create Table Command with constraints
► While creating a table constraints can also be imposed on the

columns of a table.
► Constraints in a RDBMS are used to ensure validity of the data.

Examples of some constraints are:


► UNIQUE constraint when imposed on a column makes sure

that the values entered in that column is unique for each


row. A table can have unique constraint imposed on
multiple columns. A column with UNIQUE constraint can
have Null values in it
► NOT NULL Makes sure that NULLs are not accepted in the

specified column.
► Primary Key - Sets a column or a group of columns as the

Primary Key of a table. Once Primary Key constraint is


imposed NULLs and Duplicate values in this column are not
accepted. In a table There can be only one Primary Key
SQL commands
Create Table Command with constraints
Example: CREATE TABLE employee(empno CHAR(6) PRIMARY
KEY, name VARCHAR(20) NOT NULL, basic DECIMAL(8,2), dept
VARCHAR(10), dob DATE NOT NULL, Acct_no VARCHAR(10)
Unique);
Difference Between UNIQUE constraint and PRIMARY Key
Constraint
1. Primary key constraint can be imposed on only one
column or combination of columns.
Unique constraint can be imposed on multiple columns.
2. Column defined as Primary Key cannot store Null values.
Columns with Unique constraint can have null values
SQL commands
Update command
Update is the SQL command that changes or modifies data values
in a table. When UPDATE command is given with a condition, the
changes will reflect only for the records for which the condition is
True. Otherwise When no condition is specified UPDATE will
change all the records
Syntax
Update <tablename> SET <column1> = <expression>, <column2> =
<expression> WHERE <condition>;
Category : DML
Example
UPDATE employee SET gross = Basic + 2000 WHERE Department =
‘Acct’;
SQL commands
Delete command
DELETE command is used to remove rows from table. When DELETE
command is given with a condition it will remove only those records
which satisfy the condition. DELETE withot any condition will remove
all records
Syntax : DELETE FROM <tablename> WHERE <condition>;
Category : DML
Example : DELETE FROM employee WHERE dept=’Acct’;
will delete all the records of where dept has the value ‘Acct’
Example : DELETE FROM employee;
will delete all the rows of the table.
SQL commands
Altering an existing Table Alter Table command is used to modify the
structure of an existing table. Alter table command can be used to add,
modify and remove column in an existing table.
Category : DDL
ALTER TABLE to add new column
Syntax : Alter Table <table name> ADD <column name1> <data
type> <size> <constraint>, <column name2> <data type>
<size> <constraint>…;
will add new column(s) to the existing table with the given specifications
at the end of the table after all the fields . The new column is added
with NULL values for all the records/rows in the table
Example :
Alter Table employee ADD dept char(10), gross decimal(14,2) NOT NULL;
The above command will add columns dept and gross in employee table.
SQL commands
ALTER TABLE to remove a column
Syntax : Alter Table <table name > DROP column <column
name>;
Alter Table employee DROP COLUMN dept ;
The above command will remove the specified column.
ALTER TABLE to Modify a column specifications
The MODIFY clause used with ALTER TABLE command is used to
change the data type, size, constraint related to any column of the
table.
Syntax : Alter Table <table name> MODIFY <column name>
<data type><size>,..;
► When used with numeric data type the width can be increased or
decreased. The Decrease of the size is successful only when it is
sufficient to hold all data values currently in the column.
► For char/varchar data types, change of size can be only
to increase the length of the column.
SQL commands
ALTER TABLE to add Primary Key Constraint
Alter table command can be used to add Primary key constraint to a column
of an existing table
Syntax : ALTER TABLE <table name > ADD PRIMARY KEY(column name);
Example : ALTER TABLE emp ADD PRIMARY KEY(empno);
The above command will make the empno column as the primary key of the
table.
Example : ALTER TABLE fee ADD PRIMARY KEY(admno,dt_of_pay);
The above command will make combination of rollno and dt_of_pay as the
primary key of the table.
Note : As a table can have only one Primary key, It will result an error if the
above command is given for a table which has Primary key column already
defined
ALTER TABLE to Remove Primary Key Constraint
Alter table command can also be used to remove Primary key constraint from
a column of an existing table.
Syntax : ALTER TABLE <table name > DROP PRIMARY KEY;
Example : ALTER TABLE emp DROP PRIMARY KEY;
SQL commands

DROP TABLE to remove a table from the database


DROP TABLE command is used to remove/delete a table permanently.
Syntax : DROP TABLE <table-name>;
Example : DROP TABLE emp;
Category : DDL
Once the table is dropped, the table name is no longer recognized and
any command given to manipulate the table will result error
Assessment
Create a table Empdets with the following specification
Emp_No Char(4) Primary key
Emp_name VarChar(20) Not Null
Department VarChar (10)
Salary Decimal(10,2)
Experience Integer(2)
Doj Date

Create table Empdets


(Emp_No Char(4) primary key, Emp_name VarChar(20) Not Null,
Department VarChar(10), Salary Decimal(10,2), experience
integer(2), DOJ date ) ;
Assessment
Table: Empdets
Emp_no Emp_name Department Salary Experience DOJ
E01 Ahmed Hussain Accts 15000 3 2002-01-09
E02 Ravinder Singh System 35000 5 2005-01-09
E03 Jully Bhatt System 20000 5 2000-01-09
E04 Shiva Mathur Accts 15000 7 2010-01-09
E05 Sonia Jolly Accts 12000 3 2012-01-09
E06 Sumita Singh Purchase 18000 10 2004-12-04
Assessment
(i) To display all employee names in descending order of salary.

Select Emp_name from empdets order by salary desc;

(ii) Display all records from empdets whose salary > 15000 and experience > 5 years.
Select * from empdets where salary>15000 and experience>5;

(iii) Increase the salary of all employees of Accts Department by 1000.


Update empdets set salary=salary+1000 where department=’Accts’;

(iv) Delete the employee details whose experience is less than 3 yr.

Delete from empdets where experience<3;

(v) To display emp_name, 10% of salary .Label it as “Changed salary”

Select emp_name, 0.1 * salary “Changed salary” from empdets;


Assessment
(vi) Include a new column no_of_exp (int(2)) in empdets table

Alter table empdets add (no_of_exp int(2));

(vii) To display name of departments from empdets table

Select distinct department from empdets;

(viii) To display empno,emp_name of all employees whose name ends with ‘n’

Select empno,emp_name from empdets where emp_name Like ’%n’;


Assessment
Give the outputs for the following according to the tables given below:
Table: Empdets
Emp_no Emp_name Department Salary Experience DOJ
E01 Ahmed Hussain Accts 15000 3 2002-01-09
E02 Ravinder Singh System 35000 5 2005-01-09
E03 Jully Bhatt System 20000 5 2000-01-09
E04 Shiva Mathur Accts 15000 7 2010-01-09
E05 Sonia Jolly Accts 12000 3 2012-01-09
E06 Sumita Singh Purchase 18000 10 2004-12-04
a. Select distinct department from empdets;
DEPARTMENT
Accts
System
Purchase
b. Select emp_name ,0.1*salary “CHANGED SALARY” from empdets where experience >5;
EMP_NAME CHANGED SALARY
Shiva Mathur 1500
Sumita Singh 1800
Assessment

TABLE :TRAINER
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-18 20000
105 RICHA MUMBAI 1996-01-12 95000
Assessment
(i) Display the Trainer Name, City and Salary only for the trainers whose city is Delhi
in descending order of their Hiredate

Select Tname, City, Salary from trainer where city=‘Delhi’ order by Hiredate desc;

(ii) To display trainer name along with 10% of salary which is labelled as revised salary
for all trainers

Select tname,0.1*salary “Revised Salary” from trainer;


(iii) To increase the salary of all trainers by 5% whose name ends with A.
Update trainer Set salary =salary + 0.05*salary where tname like ‘%A’;
(iv) To add column designation with 20 characters
Alter table trainer add(designation char(20));
Assessment
(v) To delete all records whose hiredate is before the year 1996
Delete from trainer where hiredate < ‘1996-01-01’;
(vi) To increase the number of characters of tname to 30 characters.
Alter table trainer modify tname char(30);
(vii) To remove column designation
Alter table trainer drop column designation;
(viii) To delete all rows

Delete from trainer;

(ix) To remove table trainer.

Drop table trainer ;


Assessment
TABLE :TRAINER
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-18 20000
105 RICHA MUMBAI 1996-01-12 95000
Give the outputs for the following according to the tables given below:
a. SELECT TID,TNAME FROM TRAINER WHERE CITY IN (‘DELHI’,’MUMBAI’) AND SALARY >80000;
TID TNAME
101 SUNAINA
105 RICHA
b. SELECT DISTINCT CITY FROM TRAINER;
CITY
MUMBAI
DELHI
CHANDIGARH
Assessment
TABLE :TRAINER
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-18 20000
105 RICHA MUMBAI 1996-01-12 95000
Give the outputs for the following according to the tables given below:
c. SELECT TNAME FROM TRAINER WHERE HIREDATE BETWEEN ’ 1994-12-24’ AND ‘1996-01-12’ ;
TNAME
ANAMIKA
RICHA
d. SELECT TID, SALARY FROM TRAINER WHERE HIREDATE < ‘2000-12-18’ AND TNAME LIKE ‘%N%’ ;

TID SALARY
101 90000
102 80000
Assessment
Which of the following commands are used to define the structure of the relation?
a. DML
b. DDL
c. Query
d. Referential Integrity

Answer : b. DDL

Complete the command:


Insert Into Employee _________(101,’Kesar’,4000);
a. Table
b. Values
c. Relation
d. Field
Answer : b. Values
Assessment
Which operator performs pattern matching?
a. BETWEEN operator
b. LIKE operator
c. IN operator
d. None of the above

Answer : b. LIKE operator

To remove duplicate rows from the result of a query ,the following clause is used:
a. distinct
b. Unique
c. Primary key
d. Different

Answer : a. distinct
Assessment
Command to display all records whose ename is of 4 characters from table employee?
a. Select * from employee where ename like ‘- - - -’;
b. Select * from employee where ename like ‘%%%%’;
c. Select from employee where ename like ‘- - - -’;
d. Select * from employee where ename like ‘-%’;
Answer : a. Select * from employee where ename like ‘- - - -’;

Command to display all records whose ename is having ‘L’ as any alphabet of the name from
table employee
a. Select * from employee where ename like ‘ %L%’;
b. Select * from employee where ename like ‘ %L’;
c. Select * from employee where ename like ‘ L%’;

Answer : a. . Select * from employee where ename like ‘ %L%’;


Assessment
For the table trainer
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-18 20000
The degree and cardinality of the table are:
a. 5,3
b. 3,5
c. 5,4
d. None of the above

Answer : a 5,3
Assessment
For the table trainer
TID CITY HIREDATE SALARY
101 MUMBAI 1998-10-15 90000
102 DELHI 1994-12-24 80000
103 CHANDIGARH 2001-12-18 20000
The attributes which can become primary key are:
a. TID
b. HIREDATE
c. TID,CITY
d. None of the above

Answer : a TID
Assessment
The command to remove a table trainer from the database is
a. DELETE FROM TRAINER;
b. DROP TABLE TRAINER;
c. Remove trainer
d. None of the above

Answer : b DROP TABLE TRAINER

The _________ operators are used to combine more than 1 conditions in Select
command
a. Relational operator
b. Logical operator
c. Mathematical operators
d. None of the above
Answer : b logical operator
Assessment
The columns or fields of tables are generally referred to as __________
a. tuple
b. Attributes
c. Domain
d. None of the above

Answer : b Attributes

The _________ data type represents fixed length character data


a. CHAR
b. VARCHAR
c. Date
d. int
Answer : a char
Assessment
A ______key is a set of one or more attributes that can uniquely identify
the rows within a table
a. Alternate key
b. Primary key
c. Foreign key
d. None of the above
Answer : b Primary key

The _________ command is used to see the structure of a table.


a. Desc <tablename>
b. View <tablename>
Answer : a Desc <tablename>
Assessment
The ______clause with ALTER TABLE command is used to remove the column.
a. Modify
b. Drop
c. Add
d. None of the above
Answer : b Drop

The _________ clause with Select is used to sort the rows in a table .
a. Order by
b. Group by
c. Sort by
d. None of these

Answer : a Order by
Assessment
Which command is used to select a database to make it current?
a. Open databasename
b. Use databasename
c. Select databasename
d. None of the above
Answer : b Use databasename

Which keyword is used to put a condition in a query to select specific row?


a. from
b. where
c. None of these

Answer : b where
Assessment
Which of the following commands is used to define the structure of the relation?
a. DML
b. DDL
c. Query
d. Referential Integrity

Answer : b. DDL

Complete the command:


Insert Into Employee _________(101,’Kesar’,4000);
a. Table
b. Values
c. Relation
d. Field
Answer : b. Values
Assessment
Which operator performs pattern matching?
a. BETWEEN operator
b. LIKE operator
c. IN operator
d. None of the above

Answer : LIKE operator

To remove duplicate rows from the result of a query ,the following clause is used:
a. distinct
b. unique

Answer : a distinct
Assessment
Command to display all records whose ename is of 4 characters from table employee?
a. Select * from employee where ename like ‘- - - -’;
b. Select * from employee where ename like ‘%%%%’;
c. Select from employee where ename like ‘- - - -’;
d. Select * from employee where ename like ‘-%’;
Answer : a. Select * from employee where ename like ‘- - - -’;

Command to display all records whose ename is having ‘L’ as any alphabet of the name from
table employee
a. Select * from employee where ename like ‘ %L%’;
b. Select * from employee where ename like ‘ %L’;
c. Select * from employee where ename like ‘ L%’;

Answer : a. . Select * from employee where ename like ‘ %L%’;


Assessment
For the table trainer
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-18 20000
The degree and cardinality of the table are:
a. 5,3
b. 3,5
c. 5,4
d. None of the above

Answer : a 5,3
Assessment
The command to remove a table trainer from the database is
a. DELETE FROM TRAINER;
b. DROP TABLE TRAINER;
c. None of the above

Answer : b DROP TABLE TRAINER

The _________ operators are used to combine more than 1 conditions in Select command
a. Relational operator
b. Logical operator
c. None of the above

Answer : b logical operator


Assessment
The columns or fields of tables are generally referred to as __________
a. tuple
b. Attributes
c. Domain
d. None of the above

Answer : b Attributes

The _________ data type represents fixed length character data


a. CHAR
b. VARCHAR

Answer : a char
Assessment
A ______key is a set of one or more attributes that can uniquely identify the rows within a table
a. Alternate key
b. Primary key
c. Foreign key
d. None of the above
Answer : b Primary key

The _________ command is used to see the structure of a table.


a. Desc <tablename>
b. View <tablename>
c. ShOW <Table name>
d. ALTER TABLE
Answer : a Desc <tablename>
Assessment
The ______clause with ALTER TABLE command is used to remove the column.
a. Modify
b. Drop
c. Add
d. None of the above
Answer : b Drop

The _________ clause with Select is used to sort the rows in a table .
a. Order by
b. Group by
c. Sort by
d. None of these

Answer : a Order by
Assessment
Which command is used to select a database to make it current?
a. Open databasename
b. Use databasename
c. Select databasename
d. None of the above
Answer : b Use databasename

Which keyword is used to put a condition in a query to select specific row?


a. from
b. where
c. If
d. None of the above

Answer : b where
Assessment
Assessment
1. Create the database LOANS.
CREATE DATABASE loans;
2. Make the database LOANS as active.
USE loans;
3. Create the table Loan_Accounts and insert tuples in it.
CREATE TABLE loan_account (accno int(4) PRIMARY KEY, cust_name VARCHAR(20)
NOT NULL, loan_amount DECIMAL (14,2) NOT NULL, instalements int (3), int_rate
DECIMAL(5,2) NOT NULL, start_date DATE, interest DECIMAL(12,2));
INSERT INTO loan_accounts VALUES(1,”R.k.Gupta”,100000,36,12,”2009-07-
19”,null)
4. Display the details of all the loans.
SELECT * FROM loan_Accounts;
5. Display the AccNo, Cust_Name, and Loan_Amount of all the loans.
SELECT AccNo, Cust_Name, Loan_Amount FROM loan_Accounts;
Assessment
6. Display the details of all the loans with less than 40 instalments.
SELECT * FROM loan_Accounts WHERE instalements < 40;
7. Display the AccNo and Loan_Amount of all the loans started before 01- 04-
2009.
SELECT AccNo, Loan_Amount FROM loan_Accounts WHERE Start_date <
“2009-04-01”;
8. Display the Int_Rate of all the loans started after 01-04-2009.
SELECT int_rate FROM loan_Accounts WHERE Start_date > “2009-04-01”;
9. Display the details of all the loans whose rate of interest is NULL.
SELECT * FROM loan_Accounts WHERE interest IS NULL:
10. Display the details of all the loans whose rate of interest is not NULL.
SELECT * FROM loan_Accounts WHERE interest IS NOT NULL:
Assessment
11. Display the amounts of various loans from the table Loan_Accounts. A loan
amount should appear only once.
SELECT DISTINCT loan_amounts FROM loan_Accounts ;
12. Display the number of instalments of various loans from the table
Loan_Accounts. An instalment should appear only once.
SELECT DISTINCT insalement FROM loan_Accounts ;
13. Display the details of all the loans started after 31-12-2008 for which the
number of instalments are more than 36.
SELECT * FROM loan_Accounts WHERE start_date > “2008-12-31” AND instalements >
36;
14. Display the Cust_Name and Loan_Amount for all the loans which do not have
number of instalments is not 36.
SELECT Cust_Name,Loan_Amount FROM loan_Accounts WHERE instalements <> 36;
15. Display the Cust_Name and Loan_Amount for all the loans for which the loan
amount is less than 500000 or int_rate is more than 12.
SELECT Cust_Name,Loan_Amount FROM loan_Accounts WHERE loan_amount < 500000
OR int_rate > 12;
16. Assessment
Display the details of all the loans which started in the year 2009.
SELECT * FROM loan_Accounts WHERE start_date BETWEEN “2009-01-01” AND
“2009-12-31”;
17. Display the details of all the loans whose Loan_Amount is in the range 400000 to
500000.
SELECT * FROM loan_Accounts WHERE loan_amount BETWEEN 400000 AND 500000;
18. Display the details of all the loans whose rate of interest is in the range 11% to
12%.
SELECT * FROM loan_Accounts WHERE Int_rate Between 0.11 AAND 0.12;
19. Display the Cust_Name and Loan_Amount for all the loans for which the
number of instalments are 24, 36, or 48.
SELECT Cust_Name,Loan_Amount FROM loan_Accounts WHERE instalements IN
(24,36,48);
20. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name ends with 'Sharma'.
SELECT AccNo, cust_name,Loan_Amount FROM loan_Accounts WHERE cust_name LIKE
“%Sharma”;
Assessment
21. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name ends with 'a'.
SELECT AccNo, cust_name,Loan_Amount FROM loan_Accounts WHERE cust_name LIKE
“%a”;
22. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name contains 'a'
SELECT AccNo, cust_name,Loan_Amount FROM loan_Accounts WHERE cust_name LIKE
“%a%”;
23. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name does not contain 'P'.
SELECT AccNo, cust_name,Loan_Amount FROM loan_Accounts WHERE cust_name NOT
LIKE “%P%”;
24. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name contains 'a' as the second last character.
SELECT AccNo, cust_name,Loan_Amount FROM loan_Accounts WHERE cust_name
LIKE “%a_”;
Assessment
25. Display the details of all the loans in the ascending order of their
Loan_Amount.
SELECT * FROM loan_Accounts ORDER BY loam_amount;
26. Display the details of all the loans in the descending order of their
Start_Date.
SELECT * FROM loan_Accounts ORDER BY start_date DESC;
27. Display the details of all the loans in the ascending order of their
Loan_Amount and within Loan_Amount in the descending order of their
Start_Date.
SELECT * FROM loan_Accounts ORDER BY loam_amount, start_date DESC;
28. Put the interest rate 11.50% for all the loans for which interest rate is NULL.
UPDATE loan_accounts SET int_rate=11.5 WHERE int_rate IS NULL;
29. Increase the interest rate by 0.5% for all the loans for which the loan
amount is more than 400000.
UPDATE loan_accounts SET int_rate = int_rate + 0.5 WHERE loan_amount > 400000;
Assessment
30. For each loan replace Interest with (Loan_Amount * Int_Rate*
Instalments) *12/100.
UPDATE loan_accounts SET interest = Loan_Amount * Int_Rate* Instalments) *12/100;

31. Delete the records of all the loans whose start date is before 2007.
DELETE FROM loan_accounts WHERE start_date < “2007-010-01”34.

32. Delete the records of all the loans of 'K.P. Jain‘;


DELETE FROM loan_accounts WHERE cust_name = 'K.P. Jain‘;

32. Add another column Category of type CHAR(1) in the Loan table.
ALTER TABLE loan_accounts ADD category CHAR(1);

You might also like