0% found this document useful (0 votes)
10 views121 pages

Chapter 3 - Review of Database Concepts and SQL - PPT

study

Uploaded by

abel.b.linson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views121 pages

Chapter 3 - Review of Database Concepts and SQL - PPT

study

Uploaded by

abel.b.linson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 121

UNIT 2

Database Query Using SQL


Unit 2
Chapter 3 – Review of Database Concepts and SQL
Chapter 4 – Database Query Using SQL

Total [Theory] Marks - 25


Topics Covered:
Database Concepts: Introduction to database concepts
and its need, Database Management System.
Relational data model: Concept of domain, tuple,
relation, candidate key, primary key, alternate key
Advantages of using Structured Query Language, Data
Definition Language, Data Query Language and Data
Manipulation Language, Introduction to MySQL, creating
a database using MySQL, Data Types
Data Definition: CREATE DATABASE, CREATE TABLE, DROP,
ALTER
Data Query: SELECT, FROM, WHERE with relational
operators, BETWEEN, logical operators, IS NULL, IS NOT
NULL
Data Manipulation: INSERT, DELETE, UPDATE
Learning Outcome
Understand database concepts and
Relational Database Management
Systems.

Retrieve and manipulate data in


RDBMS using Structured Query
Language
Introduction
• A database system is basically a computer
based record keeping system.
• The collection of data, usually referred to
as the database, contains information
about one particular enterprise.
• A database can also be defined as a
collection of interrelated data stored
together to serve multiple applications
DBMS – Database Management System
A DBMS is a software that can be used
to create and manage databases.

It is an electronic or computerized
record keeping system which maintains
various pieces of information in an
integrated and summarized form
instead of keeping them in separate
independent files.
Use of Database in Real-life Applications
 Banking
 Crop Loan
 Inventory Management
 Organization Resource Management
 Online Shopping
 Hospital Management
 Social Media
 Rail Transport
A DBMS is a general purpose software
system that facilitates the process
of defining, constructing and
manipulating databases for various
applications
Advantages of a DBMS
1. Control of Data Redundancy
2. Data Consistency
3. Sharing of Data
4. Reduced programming effort
5. Improved Data Integrity
6. Database enforces Standards
7. Improved Backup and Recovery
System
Relational Data Model
Different types of DBMS are
available and the most commonly
used data model is Relational Data
Model.
Other types include – Object
Oriented data model, entity
relationship data model, document
model, hierarchical data model
etc.
Relational Data Model

In this model, data is organized in two-


dimensional manner called tables/relations.

RDBMS – Relational Database Management


System. Its is an advanced version of DBMS
where data is stored in a tabular form
Eg: MySQL, PostgreSQL, MS-SQL Server, MS-
Access, Oracle, etc.
Basic Terminologies related to Relational
Database
7. Domain of
1. Entity
relation
2. Relation
8. Candidate Key
3. Attribute
9. Primary Key
4. Tuple
10. Alternate Key
5. Cardinality of
11. Foreign Key
relation
6. Degree of relation
Basic Terminologies related to Relational
Database

Entity – An entity is something that


exists and about which we can store
some information. It is an object
which can be distinctly identified.

Example: Student entity, Employee


entity, Book entity, etc.
Basic Terminologies related to Relational
Database
Relation – In general, a relation is a
table. i.e., data arranged in rows and
columns

Entity becomes the name of the table


Basic Terminologies related to Relational Database
Attributes – the columns of tables
(relations) are generally referred to as
attributes.

Tuple – The rows of tables (relations) are


generally referred to as Tuples.
Basic Terminologies related to Relational Database

A tuple is also called a row / record

An attribute is also known as a column / field


Basic Terminologies related to Relational Database

Degree – the number of columns or attributes is


known as degree of relation

Cardinality – the number of records or tuples is


known as cardinality of relation

Cardinality = 3 and Degree = 4


Customer

What will be the Degree and Cardinality of this relation?


Basic Terminologies related to Relational Database
Domain of relation – defines the kind of
data represented by the attribute.

RollNo Name Gender Stream


1001 Alex M Commerce
1002 Ben M Science
1003 Maya F Science
1004 Naomi F Humanities

 Domain of Gender attribute – [M, F]


 Domain of Stream attribute – [Science,
Commerce, Humanities]
Properties of a Relation

• The sequence / ordering of columns is


insignificant – columns can be retrieved
in any order and various sequences
• Each column has a unique name
• All data values in an attribute must be
from the same domain (same data type)
• Values are atomic – a row cannot contain
multiple values for a column.
Properties of a Relation

• The sequence of rows is insignificant –


rows can be retrieved in any order
• Each row – this property ensures that no
two rows in a relation are identical,
there is at least one column value which
uniquely identify each row in a table.
• A special value NULL is used to represent
values that are unknown or non-applicable
to certain attributes
Keys in a Database
The tuples within a relation must be
distinct. It means no two tuples in a
table should have same value for all
attributes. That is, there should be at
least one attribute in which data are
distinct (unique) and not NULL.
Primary Key
A primary key is a set of one or more
attributes that can uniquely identify
tuples within a relation.
Candidate Key
A candidate key is an attribute in a
relation that can serve as a Primary key.

GRNO RollNo FirstName LastName Email


12345 11 Tom Phills [email protected]
21904 12 Nick Wright [email protected]
87220 13 Diana Nathan [email protected]

Candidate Keys
Alternate Key
A candidate key that is not the Primary
key is called an Alternate Key

GRNO RollNo FirstName LastName Email


12345 11 Tom Phills [email protected]
21904 12 Nick Wright [email protected]
87220 13 Diana Nathan [email protected]

Primary Key Alternate Keys


Characteristics of Primary Key
• It cannot have NULL values
• Every value should be unique
(No duplicates allowed)
Foreign Key
A foreign key is used to represent the
relationship between two tables.

It is a non-key attribute, whose values


are derived from the primary key of some
other table.
Foreign Key - Example
Foreign Key - Example
Referential Integrity
• Referential Integrity is a property of
a RDBMS which ensures accuracy and
consistency between tables in stored
within the same database.

• It ensures that no entry can be made


in a foreign key column (child table)
unless it has a matching value in the
primary key column (parent table).
STRUCTURED QUERY LANGUAGE
TOPICS:
Introduction
Overview of SQL and MySQL
Classification of SQL statements – DDL, DML
MySQL
SQL Data Types
SQL Commands
SQL Query Processing
INTRODUCTION:
SQL, Structured Query Language was
developed in 1970s in an IBM
Laboratory.
It is a non-procedural language
that describes what all data is to
be retrieved or inserted or modified
or deleted rather than specifying
how to perform the entire operation
Brief history of MySQL

MySQL is a freely available open


source RDBMS that uses Structured
Query Language.
It can be downloaded from the site –
www.mysql.org
In a MySQL database, information is
stored in tables.
A single MySQL database can contain
many tables at once and store
thousands of individual records.
SQL enables the following:
 Creating and modifying the database's structure
 Permitting users for working on databases and
tables
 Querying database
 Inserting / Modifying / Deleting the database
contents
Some MySQL elements:
Some basic elements are:
 Literals
 Data Types
 NULL values
 Comments

Commands in SQL are not case


sensitive
Literals
Literals in general refer to a fixed
data value. They may be of character
type or numeric type or of other
data types.
Example:
"Synthia", "Raunak", 1200, 202.75
Data Types
MySQL data types can be classified
into three categories:
 Numeric
 String type
 Date and Time
Commonly used numeric data types:
Int – a normal sized integer can be signed
or unsigned. If unsigned, you can specify a
width up to 11 digits.

Decimal(M, D) – where M represents the


length and D the number of decimals.

Float(M, D) – where M represents the length


and D the number of decimals. The default
will be 10, 2, where 2 is the number of
decimals and 10 is the total number of
digits including decimals.
String / Text types:
Char(N) – A fixed length string between 1
to 255 characters in length. Default is 1
character

Varchar(N) – A variable length string


between 1 – 65535 in length. You must
define the length when creating Varchar
field.
Difference between Char / Varchar datatypes:
CHAR(N) VARCHAR(N)
Fixed length data type Variable length data type
Used to represent a field having fixed length of Used to represent a field having variable length
characters, where N could be any value from 1 of characters, where N could be any value from
to 255. 1 to 65535.
Declaring CHAR(10) implies to reserve spaces Declaring VARCHAR(30) implies maximum 30
for 10 characters. If the data does not have 10 characters can be stored but the actual allotted
characters, MySQL fills the remaining 6 bytes will depend on the length of the entered
characters with spaces padded on the right. string. (i.e. no spaces are added if the length is
shorter than the maximum length N)

Example: if the field CITY is defined as CHAR(10) Example: if the field NAME is defined as
and the value entered is ‘Mumbai’, the VARCHAR(20) and the value entered is ‘SHALU’,
remaining 4 characters are filled with spaces, the length is 5 bytes and for the value
making the size 10. ‘GURVINDER’, the length is 9 bytes.
Char(N) – represents fixed length data.

Varchar(N) – represents variable length


data. In variable length there is no
wastage of space, but processing is
complex as each value is of different
size.

All string values should be enclosed in quotes (single / double)


Date and Time types:
DATE – Used to represent date values in
the format YYYY-MM-DD
Eg:'2020-05-29', "1990-12-06"

TIME – used to represent time in the


format HH:MM:SS
Eg: '04:36:50', '21:20:10'

Both date and time values should be


enclosed in quotes (single / double)
NULL values
If a column in a row has no value, then
the column is said to be null or to
contain a null. Nulls can appear in
columns of any data type, provided they
are not restricted to NOT NULL or Primary
key constraints.

Never use NULL to represent a value of ZERO, because they are not equivalent.
Any arithmetic expression containing a null always evaluates to NULL.
Comments
A comment is a text that is not executed.
It is only for documentation purpose.
It can be used in 3 ways:
/*………………………….
………………………..*/ [Used with multiple lines]
-- followed by space [Used with single
line]
#text of comment [Used with single line]
CONSTRAINTS
Constraints are certain types of
restrictions on the data values that an
attribute can have. They are used to
ensure accuracy and reliability of data.

Commonly used SQL Constraints


PRIMARY KEY The column which can uniquely identify each row or record in a
table
NOT NULL Ensures that a column cannot have NULL values means missing or
unknown values
UNIQUE Ensures that all the values in a column are distinct / unique
SQL FOR DATA DEFINITION
SQL provides commands for defining the
relation schemas, modifying relation
schemas and deleting relations. These are
called Data Definition Language (DDL)
commands.
These commands can be used to define,
change or delete objects such as database,
tables, data type etc.
Examples – DDL commands
 Create Database
 Create Table
 Alter Table
 Drop Table
 Drop Database
 Rename Table
SQL FOR DATA MANIPULATION
By data manipulation we mean:
Retrieval of information stored in the
database.
Insertion of new information into the
database.
Deletion of information from the database
Modification of data stored in the database.
SQL FOR DATA MANIPULATION
DML (Data Manipulation Language) commands
enable users to access or manipulate data
in the database such are retrieving of
existing data, insertion of new data,
removal of existing data or modification
of existing data.
Examples – DML commands

 SELECT
 INSERT INTO
 UPDATE
 DELETE
Databases in MySQL
Before you start creating tables, you
need a database which is the container
of tables.
The actual data is stored in tables. To
create tables, either you can create a
new database or use an existing data
base.
Creating Databases
Syntax:
MYSQL>CREATE DATABASE <DATABASE NAME>;
To create a database called SCHOOL, we type
MYSQL>CREATE DATABASE SCHOOL;

All SQL commands should terminate with semicolon (;)


Opening Databases
Creating a database is not enough. Before
you create tables in it, you need to open
the database / or make it active to store
tables within it.
Syntax:
MYSQL> USE <databasename>; SQL commands are case
insensitive
Eg:
MYSQL> USE SCHOOL;
CREATE TABLE – DDL command
When a table is created, its columns, data
types and sizes are also mentioned.
Syntax:
MYSQL> CREATE TABLE <tablename>
(column name <data type>[size],
column name <data type>[size],……);

Each table must have at


least one column
CREATE TABLE - Example
To create a table STUDENT having attributes –
Roll No, Name, Class, DOB
MYSQL> CREATE TABLE STUDENT
(RollNo int(3) Primary Key,
Name Varchar(30) Not Null,
Class Char(3), DOB date);

Comma is used to
separate two attributes
Viewing the table structure
We can view the structure of an already created
table using the describe statement.
Syntax:
MYSQL> DESCRIBE <tablename>;
OR
MYSQL> DESC <tablename>;
DESCRIBE command
Example:
MYSQL> DESCRIBE Student;
OR
MYSQL> DESC Student;
To list all the tables in a database
To list the tables that are stored in a
database, we use the command:
SHOW TABLES;

Syntax / Example:
MYSQL> SHOW TABLES;

The database should be active before you issue the


command – show tables
INSERT INTO – DML command
Create Table command will create an empty
table with no data in it. To add records in
an existing table, we use INSERT INTO
command.
Syntax: Method #1
MYSQL>INSERT INTO <table name> VALUES
(<value>, <value>……<value>);
INSERT INTO – DML command
Example: To add a record into STUDENT table
MYSQL>INSERT INTO Student VALUES
(1,'Shankar','8A','2007-05-02');

The values should be in the same order


as the column names in the table.
INSERT INTO – DML command
Syntax: Method #2
MYSQL>INSERT INTO <table name> [Column list]

values (<value>, <value>……<value>);


Making simple SELECT queries
A powerful way of communicating with
databases is making queries. i.e., asking
the RDBMS to show your desired data in the
desired format. This is achieved through
SELECT command
SELECT – DML command
The SELECT command of SQL lets you make
queries on the database. It is used to
retrieve a subset of rows or columns from
one or more tables.
Syntax: Method #1 [To select all records
from the table]
MYSQL>SELECT * FROM <tablename>;
SELECT – DML command
The SELECT command of SQL lets you make
queries on the database. It is used to
retrieve a subset of rows or columns from
one or more tables.
Syntax: Method #1 [To select all records
from the table]
MYSQL>SELECT * FROM <tablename>;

Example
MYSQL>SELECT * FROM Student;
SELECT – DML command
Syntax: Method #2 [To select specific
columns]
MYSQL>SELECT <columnname>, <columnname>…..]
FROM <tablename>;
SELECT – Example
MYSQL>SELECT Name, DOB
FROM Student;

MYSQL>SELECT Class, Name, RollNo


FROM Student;

The order of selection determines the order of display


Eliminating redundant data
[with the keyword DISTINCT]
By default data is selected from all the
rows of the table, even if the data
appearing in the result gets duplicated.

The SELECT statement when combined with


DISTINCT clause, returns records without
repetition (distinct records).
Syntax:
MYSQL>SELECT DISTINCT <columnname>
FROM <tablename>;
Eliminating redundant data
[with the keyword DISTINCT] - Example
MYSQL>SELECT DISTINCT Class
FROM Student;

In the output, there would be no duplicate rows.


When ever DISTINCT is used, only one NULL value is returned in the result, no matter
how many NULL values are encountered.
Performing simple calculation in MySQL
To perform calculations, you may write the
expression with SELECT statement.
For example, to evaluate the expression 3
* 4 + 8, we write
MYSQL> SELECT 3*4+8;
SQL Operators
There are four types of SQL operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Special Operators / Clauses
Arithmetic Operators
Arithmetic Operators are used to perform
arithmetic operations like addition (+),
subtraction (-), multiplication (*),
division (/), modulus (%).
MYSQL> SELECT 52%7; 3

MYSQL> SELECT 3+NULL; NULL


MYSQL> SELECT 7*0; 0 What will be the output of
SELECT 7/0;

Any arithmetic expression containing a null always evaluates to NULL.


Relational Operators
Relational Operator is a mathematical
symbol which is used to compare two values.
The different types of comparison operators
in SQL are:
Operator Description
= Equal to
!= Not Equal to
> Greater than
>= Greater than or Equal to
< Lesser than
<= Lesser than or Equal to
Logical Operators
Logical Operators are operators used to
combine multiple conditions to filter the
data selected. These operators are also
known as Boolean operators. The 3 logical
operators used are:
Operator Symbol Order of Precedence
NOT !
AND &&
OR ||
Special Operators /
Clauses used with SELECT statement

Clauses used with Description


SELECT statement

DISTINCT Permits only unique values. Eliminates duplicate values

WHERE The WHERE clause is used to retrieve data/rows that meet some specified
conditions.
IN Checks whether an attribute value matches any value with a given list

BETWEEN Checks whether an attribute values is within a range


LIKE Checks whether an attribute matches a given string pattern

IS NULL / Checks whether an attribute value is NULL or NOT


IS NOT NULL
Selecting specific rows – WHERE clause
The WHERE clause in SELECT statement
specifies the criteria for selection of
rows to be retrieved from the database.
Syntax:
MYSQL> SELECT <columnname>, <columname>….]
FROM <tablename>
WHERE <condition>;

When WHERE clause is present, the program goes through the entire table row by
row and examines each row to determine if the given condition is true. If it is true,
the row is displayed in the output.
Selecting specific rows – WHERE clause

Example:
MYSQL> SELECT Name, DOB
Retrieves the name and date of birth of all
students from 12B
FROM student
WHERE class='12B';

MYSQL> SELECT EName, Dept Retrieves the name and department of all
employees whose salary is more than
FROM Employee 5000
WHERE Salary>5000;
Selecting specific rows – using multiple
conditions

MYSQL> SELECT Name, DOB Retrieves the name and date of birth of all
students from 12A and 12B
FROM student
WHERE class='12B' or class='12A'
MYSQL> SELECT EName, Dept
FROM Employee
WHERE Salary>5000 and Age < 40;

o rs Retrieves the name and department of all


rat ons
o pe diti employees whose salary is more than 5000
a l on
c
i ec and age is below 40
g
f lo tipl
l
s e o mu
U i th
w
Condition based on a range – BETWEEN clause
The BETWEEN operator defines a range of
values that the column value must fall into
to make the condition true. The range
includes both the lower and upper value.
Example:
MYSQL> SELECT *
FROM STUDENT
WHERE MARKS BETWEEN 60 AND 80;

The above query will retrieve all the records of those students whose marks
fall in the range 60 to 80 including 60 and 80
Condition based on a range – NOT BETWEEN clause
MYSQL> SELECT *
FROM STUDENT
WHERE MARKS NOT BETWEEN 60 AND 80;

What will happen if NOT BETWEEN operator is used?


Condition based on a list – IN operator
The IN operator selects values that match any value in a given list
of values.
Example: to display a list of employees from DELHI, MUMBAI and
CHENNAI

MYSQL> SELECT *
FROM EMPLOYEE
WHERE CITY IN ('DELHI','MUMBAI','CHENNAI');

The above query will retrieve all the records of those employees who are
from either DELHI, MUMBAI or CHENNAI
Condition based on a list – NOT IN operator
Used to retrieve rows that do not match the list
values.

MYSQL> SELECT *
FROM EMPLOYEE
WHERE CITY NOT IN ('DELHI','MUMBAI','CHENNAI');

The above query will display the details of all employees other than
from DELHI and MUMBAI
Condition based on pattern matching– LIKE clause
Many a times we come across situations
where we don’t want to query by matching
exact text or value. Rather, we are
interested to find matching of only a few
characters or values in column values. For
example, to find out names starting with
‘T’ or to find out pin codes starting with
‘60’. This is called pattern matching.
Condition based on pattern matching– LIKE clause

We cannot match such patterns using =


operator as we are not looking for exact
match. SQL provides LIKE operator that can
be used with WHERE clause to search for a
specified pattern in a column.
The LIKE operator makes use of the
following two wild card characters:
% (percent) — used to represent zero, one,
or multiple characters
_ (underscore) — used to represent a
single character
Condition based on pattern matching– LIKE clause

Example:

MYSQL>SELECT * FROM EMPLOYEE Searches for name starting with


‘K’
WHERE EName LIKE 'K%';

MYSQL>SELECT * FROM EMPLOYEE Searches for name ending with


WHERE EName LIKE '%a'; ‘a’
Condition based on pattern matching– LIKE clause
Example:

MYSQL>SELECT * FROM EMPLOYEE Searches for name having


WHERE EName LIKE '_a%'; second letter ‘a’

MYSQL>SELECT * FROM EMPLOYEE


Searches for name having 5
WHERE EName LIKE '_ _ _ _ _'; letters
Condition based on pattern matching– LIKE clause
Example:

MYSQL>SELECT * FROM EMPLOYEE Searches for name having letter


WHERE EName LIKE '%s%'; ‘s’ anywhere in the name

MYSQL>SELECT * FROM EMPLOYEE


Searches for name starting with
WHERE EName LIKE 'S_ _ _'; S and has only 4 letters.
Condition based on pattern matching– NOT LIKE clause

Example:

MYSQL>SELECT Name FROM Student


WHERE Class NOT LIKE '11%';

MYSQL>SELECT Name FROM Student


WHERE Name NOT LIKE 'A%';

What will be the output of the above queries?


When we type first letter of a contact name
in our contact list in our mobile phones
all the names containing that character are
displayed. Can you relate SQL statement
with the process?
List other real life situations where you
can visualize an SQL statement in
operation.
Handling NULL values – IS NULL / IS NOT NULL
In order to check for NULL value in a
column, we use IS NULL.
Non-NULL values in a table can be searched
for using IS NOT NULL.

Relational Operators cannot be used with NULL


Handling NULL values – IS NULL / IS NOT NULL
Example:
MYSQL>SELECT * FROM EMPLOYEE
WHERE ADDRESS IS NULL;

MYSQL>SELECT * FROM STUDENT


WHERE PHONE_NO IS NOT NULL;

Relational Operators cannot be used with NULL


Renaming of columns – Using column Aliases
In case we want to rename any column while
displaying the output, we can do so by using
alias 'AS' in the query.
Syntax:
MYSQL> SELECT <columnname> as <column alias>
FROM <tablename>;

Column aliasing is only for output purpose. Column aliasing name


having more than one word should be enclosed in quotes
Renaming of columns – Using column Aliases
Example:
MYSQL> SELECT Name as ‘Student Name’
FROM Student;
MYSQL> SELECT 22/7 AS PI;

Column aliasing is only for output purpose.


Column aliasing name having more than one word should be enclosed in quotes
Sorting Results – ORDER BY clause

ORDER BY clause is used to display data in


an ordered (arranged) form with respect to
a specified column. By default, ORDER BY
displays records in ascending order of the
specified column’s values. To display the
records in descending order, the DESC
(means descending) keyword needs to be
written with that column.
Sorting Results – ORDER BY clause
Syntax:
MYSQL> SELECT <columnname>,[<columnname…..]
FROM <tablename>
[WHERE <condition>]
[ORDER BY <columnname>]
Sorting Results – ORDER BY clause
Example: To display the student details in
the alphabetic order of names
MYSQL> SELECT *
FROM Student
ORDER BY Name;
Sorting Results – ORDER BY clause
Example: To display the names of students
in the descending order of marks
MYSQL> SELECT Name
FROM Student
ORDER BY Marks Desc;
Sorting Results – ORDER BY clause

Example: To display the names of all grade


11 students in the descending order of
marks
MYSQL> SELECT Name
FROM Student
WHERE Class LIKE '11_'
ORDER BY Marks Desc;
SQL commands are classified into:
DDL – CREATE DATABASE, CREATE TABLE
DML – INSERT INTO, SELECT
MORE DML commands
Modifying data with UPDATE command
Sometimes we may need to make changes to
some or all the value(s) in an existing
record. For example, we may require some
changes in address, phone number or
spelling of name, etc. The UPDATE statement
is used to make such modifications in the
existing data.
UPDATE Command

Syntax:
MYSQL> UPDATE <tablename>
SET <columnname>=<new value>
[WHERE <condition>];

Example:
MYSQL> UPDATE Student SET DOB='2007-04-14'
WHERE RollNo=1;

Updates the Date of Birth of the


Student whose RollNo is 1
UPDATE command
Example
MYSQL> UPDATE EMPLOYEE
SET SALARY = SALARY + 1000;

Increases the salary of all


employees by 1000
MORE DML commands

Deleting records with DELETE command


While working with tables, we may reach at a
situation where we no loner need some rows
of data. In such cases we would like to
remove them.
The DELETE command is used to delete one or
more record(s) from a table.
DELETE command
Syntax:
MYSQL> DELETE FROM <tablename>
[WHERE <condition>];

Example:
MYSQL> DELETE FROM EMPLOYEE
WHERE DEPT='SALES';

Deletes the records of all employees in the


Sales Department
DELETE command

Example:

MYSQL> DELETE FROM STUDENT


WHERE CLASS='12B';

What will happen to the following SQL command?

MYSQL> DELETE FROM STUDENT;


Commonly used DML Commands

SELECT – for retrieving records from a


table.
INSERT INTO – for adding records to a table.
DELETE – for removing records from a table.
UPDATE – for making changes to the values in
a table.
MORE DDL commands

ALTER TABLE command


After creating a table we may realize that
we need to add / remove an attribute or to
modify the datatype of an existing
attribute or to add constraint in
attribute.
In all such cases, we need to change or
alter the structure of the table by using
the ALTER command.
ALTER TABLE command
Syntax:
ALTER TABLE <tablename>
ADD/Modify/DROP attribute1, attribute2,.. ;
ALTER TABLE command
Adding an attribute to a table

Syntax:
ALTER TABLE <tablename>
ADD <columnname> <data type>;

Example:
ALTER TABLE STUDENT Adds a new column PhoneNo with
ADD PHONENO CHAR(13); datatype char(13) to the table Student
ALTER TABLE command
Modifying datatype of an attribute

Syntax:
ALTER TABLE <tablename>
MODIFY <columnname> <new data type>;

Example:
ALTER TABLE EMPLOYEE Changes the existing datatype /
MODIFY DESIGNATION VARCHAR(20); increases the width of the column
ALTER TABLE command

Removing an attribute

Syntax:
ALTER TABLE <tablename>
DROP <columnname>;

Example:
ALTER TABLE EMPLOYEE Removes the column Commission from the
DROP COMMISSION; table Employee
MORE DDL commands
DROP TABLE command / DROP DATABASE command
Sometimes a table in a database or the
database itself needs to be removed. We
can use DROP command to remove a database
or a table permanently from the system.

However, one should be very cautious while using this statement as it cannot
be undone.
DROP TABLE command
Syntax:
MYSQL> DROP TABLE <tablename>;

Example:
MYSQL> DROP TABLE EMPLOYEE;

The entire table along with its contents will be deleted.


DROP DATABASE command
Syntax:
MYSQL> DROP DATABASE <databasename>;

Example:
MYSQL> DROP DATABASE SCHOOL;

When a database is removed, all the tables within it will also


get deleted.
Database is a collection of related tables.
MySQL is a 'relational' DBMS.
A table is a collection of rows and columns,
where each row is a record and columns
describe the feature of records.
SQL is the standard language for most RDBMS.
SQL is case insensitive.
CREATE DATABASE statement is used to create
a new database.
USE statement is used for making the
specified database as active database.
• CREATE TABLE statement is used to create a
table.
• Every attribute in a CREATE TABLE statement
must have a name and a datatype.
• ALTER TABLE statement is used to make
changes in the structure of a table like
adding, removing or changing datatype of
column(s).
• The DESC statement with table name shows the
structure of the table.
• INSERT INTO statement is used to insert
record(s) in a table.
• UPDATE statement is used to modify
existing data in a table.
• DELETE statement is used to delete
records in a table.
• The SELECT statement is used to retrieve
data from one or more database tables.
• SELECT * FROM table_name displays data
from all the attributes of that table.
• The WHERE clause is used to enforce
condition(s) in a query.
• DISTINCT clause is used to eliminate
repetition and display the values only
once.
• The BETWEEN operator defines the range of
values inclusive of boundary values.
• The IN operator selects values that match
any value in the given list of values.
• NULL values can be tested using IS NULL
and IS NOT NULL.
• ORDER BY clause is used to display the
result of an SQL query in ascending or
descending order with respect to
specified attribute values. The default
is ascending order.
• LIKE clause is used for pattern matching.
% and _ are two wild card characters.
• The percent (%) symbol is used to
represent zero or more characters.
• The underscore (_) symbol is used to
represent a single character.
DDL Commands DML Commands
Data Definition Language Data Manipulation Language
Commands Commands
They are used to alter or They are used to manipulate
change the structure or the data inside a table
schema of the database /
table.
They are used to add/remove They are used to retrieve
databases, add/remove data, insert information,
tables, add/remove columns, update information or delete
change the datatype of a information from a table
column etc.
Eg: CREATE TABLE, CREATE Eg: SELECT, INSERT INTO,
DATABASE, ALTER TABLE, DROP UPDATE, DELETE etc
TABLE, DROP DATABASE etc
ALTER TABLE UPDATE
DDL Command DML Command
They are used to alter or They are used to change
change the structure of the the data inside a table.
table by add / removing
columns, changing the
datatype of a column etc
DROP TABLE DELETE
DDL Command DML Command
Used to remove the entire Used to delete one or more
table along with its records from the table.
contents.

You might also like