0% found this document useful (0 votes)
29 views60 pages

SQL New Slide

Uploaded by

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

SQL New Slide

Uploaded by

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

Structured Query

Language
Structured Query Language
• Structured Query Language (SQL) is a language
designed for managing data in relational database
management system (RDBMS). SQL provides an easy
and efficient way to interact with relational databases.
Components of SQL

SQL has three components,


-
Data Definition Language (DDL):

Data Manipulation language (DML):

Data Control Language (DCL):


DataDefinitionLangauage(DDL)
Command Description

CREATE Creates a new table, Create a view of a table.


-
-

ALTER MODIFY an existing a table.ADD a new column


- and also RENAME the tablename.

DROP Deletes an entire table, a view of a table.


- -
DataManipulationLanguage(DML)
-

Command Description
-
SELECT Retrieves certain records from one or more
tables.
-
INSERT Creates a record.

-
UPDATE Modifies records.
-
DELETE Deletes records.
Data Control Language(DCL)
-

Command Description

GRANT Gives a privilege to user.


-
- REVOKE Takes back privileges granted from user.
Data types in SQL
-

Data type defines the type of value that may be entered in the
column of a table. MySQL data types are classified into three.
They are
-• Numeric data type:
The most commonly used numeric data types in MySQL are INT
or INTEGER and DEC or DECIMAL.
-• String (text) data type:
String is a group of characters. The most commonly used string
data types in MySQL are CHARACTER or CHAR and
VARCHAR.
-
• Date and Time data type.:
MySQL has data types for storing dates and times. The data type
used to store date type value is DATE and to store time value is
TIME.
Numeric datatype
- -
-
-
O
-
-
O
- E
O 6
-
>
O
O
-

- -
-

O
O O
String Datatypes
-
-
CHAR VARCHAR
Its full name is CHARACTER Its full name is VARIABLE
-
- CHARACTER
-

The CHAR is a fixed length character VARCHAR represents variable length


-
data type. strings -

-
-
It can hold a maximum It can hold a maximum of 65,535
-
of 255 characters. characters.
- -

E
mysql>create table student(name
CHAR(20));
--
mysql>create table student1(name
VARCHAR(20));
-
-
DATE and TIME Datatype
9/10/3
DATE TIME
The DATE data type is used to store
-
The TIME data type is used to store
-
dates. time values.
-
-
-
-

MySQL represents date values in It shows values in the standard


YYYY-MM-DD format.- -
HH:MM:SS format. -

For example, '2011-01-24', '2011/01/25', For example: 22:32:45


-
'20110126' are valid date formats in -

MySQL
SQL commands
-
• Creating tables:
-

The DDL command CREATE TABLE is used to define a table by


-

specifying the name of the table and giving the column definitions
consisting of name of the column, data type and size, and constraints if
any, etc.
The syntax of CREATE TABLE command is:
CREATE TABLE <table_name>
--

(<column_name>
-
<data_type>
-
[<constarints>],
<column_name> <data_type> [<constarints>],
--

………………………………………………………………………..
-
-
-

.............................. .............................. );
-
Rules for naming tables and
columns
1. The name may contain letters (A - Z, a - z), digits (0 -
9), under score ( _ ) and dollar ($) symbol.

2. The name must contain at least one character.

3. The name must not contain white spaces, special


symbols.

4. The name must not be an SQL keyword.

5. The name should not duplicate with the names of


other tables in the same data base.
dub
gender-
adm-no nam
-
&
-
-
-

course, f-Income
• Eg: Create table:
CREATE TABLE student (adm_no INT,
-- ---

-
name VARCHAR(20),
-

gender CHAR,
-

dob DATE,
- -

course VARCHAR(15),
--

f_income INT);
--
Constraints
Constraints are the rules enforced on data that are entered into the
column of a table. Constraints could - be column level or table
-

-
level.
no
Column Constraints: wome

Column constraints are applied only to individual columns.


NOT NULL: -
-
Ensures that a column cannot have NULL value. -

AUTO_INCREMENT: - -
Allows a unique number to be generated automatically when a
new record is inserted into a table.
PRIMARY KEY:
Uniquely identified each rows/records in a database table.
-
UNIQUE:
-

Ensures that all values in a column are different.


DEFAULT: -
Provides a default value for a column when none is specified
-
O
Eg:CREATE TABLE student
-
--

(adm_no INT PRIMARY KEY AUTO_INCREMENT,


-- -

name VARCHAR(20) NOT NULL,


-
-

gender CHAR DEFAULT 'M',


=

dob DATE,
-

course VARCHAR(15),
-
-

f_income INT);
-
Table Constraints:
Table constraints are similar to column constraints. But
table constraints are used not only on individual columns,
but also on a group of columns.
CREATE TABLE stock
(icode CHAR(2) PRIMARY KEY AUTO_INCREMENT,
iname VARCHAR(30) NOT NULL,
dt_purchase DATE,
rate DECIMAL(10,2),
qty INT,
UNIQUE (icode, iname));
S
Viewing the structure of a table
-

The DESCRIBE command is used to display the structure


definitions of a table.
The syntax is: DESCRIBE <table_name>; OR
--

DESC <table_name> ;
- -

Eg:DESC student;
-

- -----

--
- - -
-
-
Inserting data into tables
1) The DML command INSERT INTO is used to insert tuples into tables.

INSERT INTO <table_name> [<column1>,<column2>,<column3>,…… <column n>]


-
-

VALUES(<value1>,<value2>,<value3>,………<value n>);
-
- -

For example, let us insert a new record into the table student with data 1001, 'Alok',
'M', 1998/10/2, 'Science', 24000 into the columns adm_no, name, gender, dob,
course and f_income, respectively.
Fe
----

E
INSERT INTO student(adm_no,name,gender,dob,course,f_income) VALUES
--------

---(1001,'Alok','M','1998/10/2', 'Science', 24000);

The response of the system will be:

Query OK, 1 row affected (0.05 sec).


'AloK; im
;
insert into student (100, ,
↑ 990/10/2" 'scins" , 2000d
,
,

cont…
2) MySQL allows inserting several rows into a table with a
single INSERT command by specifying multiple value lists.

INSERT INTO <table_name> VALUES(...), (...), ...


…………………………………………..;
-

INSERT INTO student


VALUES('Bharath','1999/01/01','Commerce',45000),
('Virat','1998/12/05','Science',22000);

The response of the system will be: Query OK, 2 rows


affected (0.02 sec)

Records: 2 Duplicates: 0 Warnings: 0


Retrieving information from
tables
The SELECT command has several forms of its own. The simplest form of
-

SELECT command is:

SELECT <column_name> [,<column_name>,<column_name>,…..] from


-- -
-
<table_name>;
-
-

Eg:SELECT name, course FROM student; Select


many
O E course from
-

studenty
-

-
z
-
-
-

2
2
-

- cont...
• SELECT * FROM student;
-
-

&
Eliminating duplicate values in columns using DISTINCT.

SELECT DISTINCT course FROM student;


-
- -

O
-

-
-

If we give the keyword ALL in the place of DISTINCT, then the


result will contain all the duplicate values in the column.
• Selecting specific rows using WHERE clause
-

– Selection is based on some conditions use WHERE clause.


-

– The syntax of SELECT command with WHERE clause is:


SELECT <column_name>,<column_name>,<column_name>,…..]
-- -

FROM <table_name>
--

WHERE <condition>;
-

The conditions are expressed with the help of relational


operators and logical operators.
-


=
SELECT * FROM student WHERE gender='F';


-

A
SELECT name, course, f_income FROM student WHERE course='Science' AND
f_income<25000; -

-
-
-
-

- -

cont..
Special operators for setting conditions.
-
⚫ BETWEEN...AND – Condition based on Range of
-
-

Values
-
-

-
IN – Condition based on List of Values
-

-
⚫ LIKE – Condition based on Pattern Matching
- -

⚫ IS – Condition based on Null Value Search


-
-
BETWEEN...AND
A range of values can be given as condition.
SELECT name, f_income FROM student WHERE
-

f_income BETWEEN 25000 AND 45000;


-

=
-
>

OUTPUT
Select * from student where
IN course = "Command
&
AND course : "Humanities
-
-
, -

A list of values can be provided as Condition


SELECT * FROM student WHERE
- -

course IN('Commerce', 'Humanities');


-
-
---
I
-

or

SELECT * FROM student WHERE


course NOT IN('Science'); L

E
-
- -

OUTPUT
LIKE
Condition based on Pattern Matching
-

⚫ String data having some similarities in characters is the condition for


accessing records

⚫ Two wild card characters are used %(percentage) and _(underscore)


- -
-

⚫ % denotes substring and _ denores single character


&
-
⚫ "Ab%" matches any string beginning with "Ab".
=> -

⚫ "%cat%" matches any string containing "cat" as substring. For


-- -

example,"education", "indication", "catering" etc.

⚫ "_ _ _ _" matches any string of exactly four characters without


any space in between them.

⚫ "_ _ _ %" matches any string of at least 3 characters.


Example for LIKE

SELECT name FROM student WHERE name LIKE '%ar';


-
--
-
- --

OUTPUT

SELECT name FROM student WHERE name LIKE 'Div_ _ ar';


-

-
-
- -
- =>
-

2
IS
-

Condition based on Null Value Search


-
SELECT name, course FROM student WHERE
-

f_income IS NULL;
-

OUTPUT

E -

-
-
-
ORDER BY clause -

⚫ Used for sorting Resuts in Alphabetic order


⚫ ASC keyword is used for Ascending order sorting
⚫ DESC keyword is used for descending order sorting
-

-
SELECT * FROM student ORDER BY name;
-

-
-
-

-
Descending order Sorting
-

O
SELECT * FROM student ORDER BY name DESC;
-
-
Aggregate Functions

-
-

-
- -

-
- -

--

SELECT MAX(f_income), MIN(f_income), AVG(f_income)


-
FROM student;
-
-

O 0
-F
SELECT COUNT(*), COUNT (f_income) FROM student
WHERE course='Science';

O

GROUP BY clause

⚫ Used for Grouping of records


⚫ rows of a table can be grouped together based on a
common value
⚫ Tuples with the same attribute value are placed together
in one group.
⚫ this process can be considered as categorisation of
records.
-

SELECT course, COUNT(*),AVG(f_income)FROM


-
student
GROUP BY course;
- - -

- - -
O
HAVING clause

⚫ Used for Applying conditions to form groups


⚫ Used along with GROUP BY clause

SELECT course, COUNT(*) FROM student


- -

GROUP BY course
-

HAVING COUNT(*) > 3;


--
UPDATE Command
⚫ Used for modifying table data

⚫ It is a DML Command

⚫ Values in one or more columns of specified rows can


be changed.

⚫ Changes may be affected in all or in selected rows of


the table.

⚫ The new data is given using SET keyword


(essential clause of UPDATE)
⚫ The new data can be a constant, an expression or
data from other tables.
The syntax of UPDATE command:
-

UPDATE <table_name>
-

SET <column_name> = <value> [,<column_name>


-
-

= <value>,...]
[WHERE <condition>];
-

Example

UPDATE student SET f_income=27000


-

WHERE name='Kaushi';
-

-
SELECT * FROM student WHERE name='Kaushi';
ALTER TABLE Command
-

⚫ Used to modify the structure of table


-
⚫ It is a DDL Command

⚫ The Modification can be :

1)Adding or dropping column(s)


-

2)Changing the data type and size of


existing column(s)
3)Renaming a table, etc.
Adding new column(s)
-

⚫ One or more columns can be added at any position in an


existing table.
⚫ ADD clause is used along with ALTER TABLE Command
-
-

⚫ Syntax:
ALTER TABLE <table_name>
-

ADD- -
<column_name> <data_type> [<size>] [<constraint>]

I
- -

[FIRST | AFTER <column_name>]; --


-

Example:
ALTER TABLE student
- - -

ADD gr_mks INTEGER AFTER dob,


&
-
-

ADD C reg_no INTEGER; -


- -

- -

(two new columns, gr_mks and reg_no is added)


-
Removing Column from a table
-

⚫ DROP clause is used in ALTER TABLE


-
Command

Syntax
⚫ ALTER TABLE <table_name> DROP
-

<column_name>;
-
-

Example
⚫ ALTER TABLE student DROP gr_mks;
-
(the column “gr_mks” will be removed)
-
Changing the definition of a column
MODIFY clause is used with ALTER TABLE command.
- -

Syntax:
ALTER TABLE <table_name>
-

MODIFY <column_name> <data_type>[<size>] [<constraint>];


-
- -
-

Example:
ALTER TABLE student
&
- - -

MODIFY reg_no INTEGER UNIQUE;


-
-
-
-
-
-
Renaming a table

⚫ RENAME TO clause is used with ALTER TABLE


-

command.
⚫ We can rename a table even though it contains tuples.
Syntax:
ALTER TABLE <table_name>
-

RENAME TO <new_table_name>;
-

Example a
ALTER TABLE student RENAME TO student2015;
---
-
DELETE FROM Command

⚫ Used for deleting rows from a table


⚫ It is a DML Command
⚫ WHERE Clause is used for deleting selected rows
⚫ If WHERE Clause is not used all rows will be deleted

Syntax
⚫ DELETE FROM <table_name> [WHERE <condition>];
-
-
Example
⚫ DELETE FROM student2015 WHERE adm_no=1027;
- -

⚫ (The record of Sreekumar with admission number 1027


-
will be deleted)
-
DROP TABLE Command
-
⚫ Used to remove Table from
Database
⚫ Its a DDL Command

⚫ Syntax
DROP TABLE <table_name>;
-

⚫ Example
DROP TABLE student2015; -

(The table student2015 will be deleted from the database )


-
Nested Query

&
⚫ One query inside another Query
⚫ Inner query is known as Sub query

⚫ The Query that contains the Sub Query is known as

⚫ Outer Query

⚫ SQL first evaluates the inner query(sub query) within the WHERE
⚫ clause and the result of inner query is then substituted in the

⚫ condition of the outer query.

⚫ Example

SELECT name, course FROM student2015


WHERE f_income=(SELECT MAX(f_income) FROM student2015);
-

(Name and course of with highest f_income will be retrived)


G
VIEW

⚫ A view is a virtual table that does not really exist in the database
⚫ It is derived from one or more tables.
-
⚫ The table(s) from which the tuples are collected to create a view is
called base table(s).
⚫ Tuples are not physically stored anywhere.
⚫ The definition of the view is stored in the database.
⚫ We can view the desired information that is stored in a base table.
⚫ The contents of a view are taken from other tables using a query
Condition.
⚫ View is created using the DDL command CREATE VIEW .
⚫ Views Can perform all DML commands similar to a table.
⚫ We can use the same table as different table(virtual)without using
extra space.
⚫ Views can be Securely shared.
⚫ Reduces the complexity of conditions with WHERE clause while
accessing records.
Creating VIEW

Syntax:
CREATE VIEW <view_name>
-

AS SELECT <column_name1> [,<column_name2],...]


-

FROM <table_name> [WHERE <condition>];


-

--
-

Example ---
CREATE VIEW student1998 AS SELECT * FROM student2015
- -
WHERE dob < '1999-1-1';
-

Deleting VIEW

Syntax
DROP VIEW <view_name>;

Example:
DROP VIEW student1998;
-
10What is meant by column constraints? Write any
4 column constraints in SQL.
Constraints are the rules enforced on data that
are entered into the column of a table.
The column constraints are

1. NOT NULL 2
2. AUTO_INCREMENT L
3. UNIQUE -
4. PRIMARY_KEY -

5. DEFAULT -
Null values in in tables are specified as “null”.
State whether true or false.

E
false. “null” is a string
What is the use of SELECT command in SQL? Write
down its syntax of usage.

SELECT is used to retrieve information from specified


columns
-- in a table.

Syntax –
SELECT -

<column_name>[,<column_name>,<column_name>,
--
…] FROM <table_name>;
-

Example – SELECT name FROM student;


Briefly describe three optional clauses used with
-

SELECT command in SQL.


-

-
a. WHERE - used to select specific rows.
- -

b. ORDER BY – used to sort the result of a query.


- -
c. FROM – It is an essential clause with SELECT
command. Used to specify the table name.
-
-
Write the differences between WHERE and HAVING clauses in
SQL. -

WHERE clause is used along with SELECT to select specific


rows. -

Eg. SELECT Rollno, Batch FROM student


WHERE Name=”Pranoy”;
-
HAVING is used along with GROUP BY clause. The condition in
HAVING clause is applied to form groups of
records.
Eg. SELECT course, COUNT(*) FROM student
GROUP BY course
HAVING COUNT(*) > 3;
Define VIEW in SQL. How it is created? 2

A view is a virtual table that does not really exist in


the database, but is derived from one or more
tables.
Eg. CREATE VIEW newschool
AS SELECT Rollno, Name, Batch FROM student;
Differentiate DELETE and DROP in SQL. Write the syntax of
DELETE and DROP.

DELETE used to remove individual or a set of rows from a table. It


is a DML command.
-

Syntax
DELETE FROM <table_name> [WHERE <condition>];
Eg - -

DELETE FROM student WHERE RollNo=1027;


DROP used to remove a table from the database permanently. It
-
is a DDL command. -

Syntax
DROP TABLE <table_name>;
-

Eg
-
DROP TABLE student;
Write SQL queries based on the table STUDENT given below.
-

-
z
(a) Add a new, field percentage
-
to the table.
(b) Update percentage of all students. (percentage: Total/3)
Commen
(c) Find the average of column total from student in cornmerce -
-

batch. -

(d) Delete all students in Humanities batch.-


-
(e) Find the number of students whose percentage is greater than
-
90. -

TABLE Student
a) ALTER
Percentage DE (3, 4)
;
ADD
Student
b) UPDATE
Total/s
set percentage =
;
2) select aus(total) from student
'Commenc
where batch :
;
Student
d) Delete
&
From
;
where batch : "Humantics

count() from Student


ef Select
where percentage > alo

You might also like