0% found this document useful (0 votes)
27 views

321DBMS Unit 2 PPT (SQL)

The document provides information on SQL (Structured Query Language) including: - SQL is used to manage data in relational database management systems and was developed by IBM. - SQL commands include DDL, DML, DCL, DQL, and TCL which are used for creating, modifying, querying, and controlling databases and data. - The document describes several SQL data types and common SQL commands like CREATE, ALTER, SELECT, INSERT, UPDATE, DELETE and provides examples of using CREATE DATABASE and CREATE TABLE commands.

Uploaded by

Sanya Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

321DBMS Unit 2 PPT (SQL)

The document provides information on SQL (Structured Query Language) including: - SQL is used to manage data in relational database management systems and was developed by IBM. - SQL commands include DDL, DML, DCL, DQL, and TCL which are used for creating, modifying, querying, and controlling databases and data. - The document describes several SQL data types and common SQL commands like CREATE, ALTER, SELECT, INSERT, UPDATE, DELETE and provides examples of using CREATE DATABASE and CREATE TABLE commands.

Uploaded by

Sanya Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Database Management Systems

Unit-2

Dr. Vrinda
Sachdeva
Introduction to SQL

Structure Query Language(SQL) is a database query language used for storing and
managing data in Relational DBMS. SQL was the first commercial language
introduced for E.F Codd's Relational model of database.

Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) use SQL as
the standard database query language. SQL is used to perform all types of data
operations in RDBMS.

2
Introduction to SQL

SQL (Structured Query Language) is a computer-based structured, formatted


database language designed for managing data in relational database
management systems (RDBMS). SQL is a standardized computer language which
was initially developed by IBM for querying, altering and defining relational
databases, using declarative statements.
● SQL is Structured Query Language, which was initially developed by IBM.
● SQL is pronounced as "sequel".
● SQL is a computer language for storing, manipulating, and retrieving data in a
relational database.
● SQL is the standard language for Relational Database System.

3
SQL Can Do….

● SQL can CREATE new databases and its objects like (table, index, views, store
procedure, functions, and triggers).
● SQL can ALTER the structure of the existing databases.
● SQL can DROP(delete) objects from the database.
● SQL can TRUNCATE(remove) all records from the tables.
● SQL can COMMENT to the data dictionary.
● SQL can RENAME an object.
● SQL can SELECT(retrieve) data from the database.
● SQL can INSERT data into a table.
● SQL can UPDATE existing data within a table.
● SQL can DELETE records from a database table.
● SQL can set GRANT and REVOKE privileges of users in a database.

4
SQL Command
Command Description

DDL: Data Definition Language


create to create new table
or database
This includes changes to the structure
of the table like creation of table,
alter for alteration
altering table, deleting a table etc.

All DDL commands are auto-committed. truncate delete data from table
That means it saves all the changes
drop to drop a table
permanently in the database.
rename to rename a table

5
DML: Data Manipulation Language

DML commands are used for Command Description


manipulating the data stored in insert to insert a new row
the table and not the table itself.
update to update existing row
DML commands not
delete to delete a row
are auto-committed. It
changes are not permanent means merge merging two rows or
two tables
to database, they can be rolled
back.

6
TCL: Transaction Control Language

These commands are to keep a Command Description


check on other commands and
their effect on the database. These commit to permanently save
commands can annul changes
made by other commands by rollback to undo change
rolling the data back to its original
savepoint to save temporarily
state. It can also make any
temporary change permanent.

7
DCL: Data Control Language

Data control language are the commands to Command Description


grant and take back authority from any grant grant permission of right
database user.
revoke take back permission.

DQL: Data Query Language


Command Description Data query language is used to
fetch data from tables based on
select retrieve records from one or more table
conditions that we can easily apply.

8
SQL Data Types
Datatype Use

INT used for columns which will store integer values.

FLOAT used for columns which will store float values.

DOUBLE used for columns which will store float values.

VARCHAR used for columns which will be used to store characters and integers, basically a string.

CHAR used for columns which will store char values(single character).

DATE used for columns which will store date values.

TEXT used for columns which will store text which is generally long in length. For example, if
you create a table for storing profile information of a social networking website, then for
about me section you can have a column of type TEXT.

9
Data type Description

SMALLINT Integer numerical (no decimal). Precision 5

INTEGER(P) or INT(P) Integer numerical (no decimal). Precision P

INTEGER Integer numerical (no decimal). Precision 10

NUMERIC(P,S) Exact numerical (Same as DECIMAL) Precision P and scale value S.

REAL approximate numerical, mantissa precision 7

DECIMAL(P,S) Exact numerical, 'P' is precision value and 'S' is scale value.

DOUBLE PRECISION double precision floating-point number

FLOAT(N) Approximate numerical, floating-point with at least N digits

CHAR(N) or CHARACTER(N) character string. fixed-length N

VARCHAR(N) character string. Variable length. Maximum length N

10
Data type Description

BIT(N) 'N' is the number of bits to store

BIT VARYING(N) 'N' is the number of bits to store (length can vary up to N)

DATE stores year, month, and day values

TIME stores hour, minute and second values

TIMESTAMP stores year, month, day, hour, minute and second values

TIME WITH exactly same as time but also store an offset from UTC

TIME ZONE of the time specified

TIMESTAMP WITH same as timestamp but also stores an offset from UTC of

TIME ZONE the time specified.

11
SQL Command Description

SQL Command
CREATE DATABASE Creates a new database

CREATE TABLE Creates a new table

ALTER DATABASE Modifies a database

ALTER TABLE Modifies a table

DROP TABLE Deletes a table

CREATE INDEX Creates an index

DROP INDEX Deletes an index

SELECT Fetch data from database tables

UPDATE Modify data in a database table

DELETE Deletes data from a database table 12

INSERT INTO Inserts new data into a database table


SQL CREATE Commands

Create Database:

The SQL CREATE DATABASE Statement is used to create a new database.

Syntax: CREATE DATABASE database_name;

Example:

The following SQL statement creates a new database named as "my_database":

CREATE DATABASE my_database;

13
SQL CREATE Command
Create Table: Example
The SQL CREATE TABLE Statement is used to
The following SQL statement creates a
create a new table in a database.
Syntax: new table in the database named as
CREATE TABLE table_name "tbl_employee":
( CREATE TABLE tbl_employee
column_name1 datatype(size) [ NULL | NOT
NULL ], (
column_name2 datatype(size) [ NULL | NOT employee_id INT NOT NULL,
NULL ], last_name VARCHAR(100) NOT NULL,
column_name3 datatype(size) [ NULL | NOT
first_name VARCHAR(100) NOT NULL,
NULL ],
.... address VARCHAR(255) NULL
); );

14
SQL: ALTER command

alter command is used for altering the table structure, such as,
● to add a column to existing table
● to rename any existing column
● to change datatype of any column or to modify its size.
● to drop a column from the table.
Using ALTER command we can add a column to any existing table. Following is
the
Syntax: Example:
ALTER TABLE table_name ADD ALTER TABLE student ADD
( (
column_name datatype address VARCHAR(200)
); );
15
ALTER Command: Modify an existing Column

ALTER command can also be used to modify data type of any existing column.
Following is the syntax,

ALTER TABLE table_name modify(


column_name datatype
);

Example:
ALTER TABLE student MODIFY(
address varchar(300));

16
ALTER Command: Rename a Column /Table

Using ALTER command you can rename The syntax to rename a table in
an existing column. Following is the syntax, MySQL is:
ALTER TABLE table_name
CHANGE COLUMN old_name new_name ALTER TABLE table_name
column_definition RENAME TO new_table_name;
[ FIRST | AFTER column_name ]

Example
Example:
ALTER TABLE contacts
ALTER TABLE contacts RENAME TO people;
CHANGE COLUMN contact_type ctype
varchar(20) NOT NULL;

17
Syntax

Select Command SELECT select_list


FROM
table_name;
The SELECT statement allows you to select data SELECT employeeNumber,
from one or more tables. lastName,
firstName,
MySQL SELECT statement examples extension,
email,
SELECT officeCode,
lastName reportsTo,
FROM jobTitle
emplo FROM
yees; employees;

SELECT SELECT *
FROM
lastNa employees;
me,
firstName, Use the SELECT
jobTitle statement to
FROM select data
employ from a table.
ees; 18
Use the SELECT * to select data from all columns of a
Select Command

SELECT 1 + 1;
SELECT NOW();
SELECT
CONCAT('John','
','Doe');
SELECT select_list FROM dual;
SELECT expression AS column_alias;
SELECT CONCAT('John',' ','Doe') AS
name;

MySQL SELECT statement doesn’t


require the FROM clause

Use the dual table if you want to use the FROM clause but don’t want to reference a table.
19
Assign an alias to a column to make it more readable.
Order By Clause
SELECT ORDER BY in ascending order: Use the ORDER BY clause to sort
select_list the result set by one or more
ORDER BY column1 ASC; columns.
FROM
table_name Use the ASC option to sort the
ORDER BY in descending order: result set in ascending order and
ORDER BY
the DESC option to sort the result
column1 [ASC| ORDER BY column1 DESC; set in descending order.
DESC], column2
[ASC|DESC], If you want to sort the result set by The ORDER BY clause is evaluated
multiple columns, after the FROM and SELECT
...; clauses.
ORDER BY In MySQL, NULL is lower than
column1, non-NULL values

column2;
20
WHERE Clause
SELECT
The WHERE clause allows you to specify a search SELECT lastname,
condition for the rows returned by a query. The lastname, firstname,
following shows the syntax of the WHERE clause: jobtitle,
firstname,
SELECT officeCode
jobtitle
select_list FROM FROM
FROM employees employees
table_name WHERE WHERE
WHERE jobtitle = 'Sales jobtitle = 'Sales Rep'
Search_c Rep';
ondition; AND
The search_condition is a combination of one or officeCode = 1;
more expressions using the logical operator AND,
OR and NOT.

21
+-----------+-----------+--------------------+------------+
| lastName | firstName | j o b T i t l e | officeCode |
WHERE Clause +-----------+-----------+--------------------+------------+
| Murphy | Diane | President | 1 |
| Bow | Anthony | Sales Manager (NA) | 1 |
SELECT | Jennings | L e s l i e | Sales Rep | 1 |
| Thompson | L e s l i e | Sales Rep | 1 |
lastname, | F i r r e l l i | Jeff | VP Marketing | 1 |
firstname, | Patterson | Mary | VP Sales | 1 |
| F i r r e l l i | Julie | Sales Rep | 2 |
jobtitle, | Patterson | Steve | Sales Rep | 2 |
officeCode | Tseng | Foon Yue | Sales Rep | 3 |
| Vanauf | George | Sales Rep | 3 |
FROM | Bondur | Loui | Sales Rep | 4 |
| Hernandez | Gerard | Sales Rep | 4 |
employees | C a s t i l l o | Pamela | Sales Rep | 4 |
WHERE | Gerard | Martin | Sales Rep | 4 |
| Nish i | Mami | Sales Rep | 5 |
jobtitle = 'Sales Rep' | Kato | Yoshimi | Sales Rep | 5 |
AND officeCode = 1; | Fixter | Andy | Sales Rep | 6 |
| Marsh | Peter | Sales Rep | 6 |
| King | Tom | Sales Rep | 6 |
| Bo t t | Larry | Sales Rep | 7 |
| Jones | Barry | Sales Rep | 7 |
+-----------+-----------+--------------------+------------+
21 rows i n se t (0.00 sec)
22
BETWEEN Operator
+-----------+-----------+------------+
The BETWEEN operator returns TRUE if a | firstName | lastName | officeCode |
value is in a range of values: +-----------+-----------+------------+
| Diane | Murphy | 1 |
| Mary | Patterson | 1 |
SELECT | Jeff | Firrelli | 1 |
firstName, | Anthony | Bow | 1 |
| Leslie | Jennings | 1 |
lastName, | Leslie | Thompson | 1 |
officeCode | Julie | Firrelli | 2 |
| Steve | Patterson | 2 |
FROM | Foon Yue | Tseng | 3 |
employees | George | Vanauf | 3 |
WHERE +-----------+-----------+------------+
10 rows i n s et (0.00 sec)
officeCode BETWEEN 1 AND 3
ORDER BY
officeCode;

23
LIKE Operator
The LIKE operator evaluates to TRUE if a SELECT
firstName, +-----------+-----------+
value matches a specified pattern. | firstName | lastName |
lastName +-----------+-----------+
FROM | Leslie | Thompson |
To form a pattern, you use the % and _ employees | Mary | Patterson |
wildcards. WHERE | Steve | Patterson |
| William | Patterson |
lastName LIKE '%son' +-----------+-----------+
The % wildcard matches any string of ORDER BY 4 rows i n se t (0.00 sec)
zero or more characters while the _ firstName;
wildcard matches any single character.

The following query finds the employees


whose last names end with the string
'son':

24
IN Operator
The IN operator returns TRUE if a value +-----------+-----------+------------+
| firstName | lastName | officeCode |
matches any value in a list. +-----------+-----------+------------+
| Diane | Murphy | 1 |
| Mary | Patterson | 1 |
SELECT | Jeff | Firrelli | 1 |
| Anthony | Bow | 1 |
firstName, | Leslie | Jennings | 1 |
lastName, | Leslie | Thompson | 1 |
officeCode | Julie | Firrelli | 2 |
| Steve | Patterson | 2 |
FROM | Foon Yue | Tseng | 3 |
employees | George | Vanauf | 3 |
WHERE +-----------+-----------+------------+
10 rows i n set (0.00 sec)
officeCode IN (1 , 2, 3)
ORDER BY
officeCode;

25
IS NULL Operator
To check if a value is NULL or not, you use the IS +----------+-----------+-----------+
NULL operator, not the equal operator (=). | lastName | firstName | reportsTo |
+----------+-----------+-----------+
| Murphy | Diane | NULL |
The IS NULL operator returns TRUE if a value is +----------+-----------+-----------+
NULL. 1 row i n set (0.01 sec)

SELECT
lastName,

firstName,
reportsTo
FROM
employees
WHERE
reportsT
o IS NULL;
26
WHERE clause with comparison operators
Operator Description

= Equal to. You can use it with almost any data type.

<> or != Not equal to

< Less than. You typically use it with numeric and date/time data types.

> Greater than.

<= Less than or equal to

>= Greater than or equal to

● Use the WHERE clause to filter rows by a condition.


● MySQL evaluates the WHERE clause after the FROM clause and before the ORDER BY
clauses.
27
DISTINCT Clause
To remove these duplicate rows, you use the SELECT DISTINCT
DISTINCT clause in the SELECT statement. state, city
FROM
SELECT DISTINCT custo
select_list +---------------+----------------+
mers
WHERE
FROM | state
| city |
table_name state IS NOT NULL +---------------+----------------+
WHERE
ORDER BY | BC | Tsawassen |
search_condition state, | BC | Vancouver |
ORDER BY city; | CA | Brisbane |
| CA | Burbank |
sort_expressio
| CA | Burlingame |
n;
| CA | Glendale |
| CA | Los Angeles |
Use the MySQL DISTINCT clause to remove | CA | Pasadena |
duplicate rows from the result set returned by | CA | San Diego |
the SELECT clause. ...

28
In this syntax:

LIMIT Clause ● The offset specifies the offset of the first


row to return. The offset of the first row is
0, not 1.
The LIMIT clause is used in the SELECT
● The row_count specifies the maximum
statement to constrain the number of rows to
return. The LIMIT clause accepts one or two number of rows to return.
arguments. The values of both arguments must
be zero or positive integers. The following picture illustrates the LIMIT
clause:
The following illustrates the LIMIT clause
syntax with two arguments:
SELECT
select_list
FROM
table_n
ame
LIMIT
[offset,]
row_count; 29
SELECT
customerNumber
LIMIT Clause , customerName
FROM
customers
SELECT ORDER BY customerName
customerNumber, LIMIT 10, 10;
customerName,
creditLimit
FROM
customers
ORDER BY creditLimit DESC
LIMIT 5;

30
Join clauses
A join is a method of linking data between one (self-join) or more tables based on
values of the common column between the tables.

MySQL supports the following types of joins:


1. Inner join
2. Left join
3. Right join
4. Cross join

To join tables, you use the cross join, inner join, left join, or right join clause. The
join clause is used in the SELECT statement appeared after the FROM clause.
Note that MySQL hasn’t supported the FULL OUTER JOIN yet.

31
Join clauses
CREATE TABLE members INSERT INTO members(name) VALUES('John'),
( member_id INT ('Jane'),('Mary'),('David'),('Amelia');
AUTO_INCREMENT, name
VARCHAR(100), INSERT INTO committees(name)
VALUES('John'),('Mary'),('Amelia'),('Joe');
PRIMARY KEY (member_id)
); SELECT * FROM members;
SELECT * FROM committees;
CREATE TABLE committees
( committee_id INT +-----------+--------+ +--------------+--------+
| member_id | name | | committee_id | name |
AUTO_INCREMENT, name +-----------+--------+ +--------------+--------+
VARCHAR(100), | 1 | John | 1 | John |
| | | 2 | Mary |
PRIMARY KEY (committee_id) | 2 | Jane | 3 | Amelia |
); | | | 4 | Joe |
| 3 || Amelia
5 Mary | +--------------+--------+
+ - - - - - - - - - - - + - -| - - - - - - + 4 rows i n se t (0.00 sec)
5 rows i n set 4 | (0.00 David sec) 32
|
SELECT column_list
FROM table_1
INNER JOIN clause INNER JOIN
table_2 USING
(column_name);
SELECT
The following shows the basic syntax of the m.member_id,
inner join clause that joins two tables table_1 m.name AS member,
and table_2: c.committee_id,
c.name AS
SELECT column_list committee
FROM table_1 FROM
INNER JOIN table_2 members m
ON join_condition; INNER JOIN
committees
SELECT c ON
The inner join clause joins two tables based on c.name = m.name;
m.member_id,
a condition which is known as a join predicate. m.name AS member,
c.committee_id,
If the join condition uses the equality operator
c.name AS
(=) and the column names in both tables used committee
for matching are the same, and you can use the FROM
USING clause instead: members m
INNER JOIN 33
committees c
LEFT JOIN clause SELECT
m.member_id,
m.name AS member,
c.committee_id,
The left join selects data starting from the left table. c.name AS
For each row in the left table, the left join compares committee
with every row in the right table. FROM
members m
SELECT column_list
LEFT JOIN committees
FROM table_1
LEFT JOIN table_2 c USING(name);
ON join_condition; +-----------+--------+--------------+-----------+
The left join also supports the USING clause if the | member_id | member | committee_id | committee |
column used for matching in both tables are the +-----------+--------+--------------+-----------+
| 1 | John 1| John |
same: | | NULL | NULL |
| 2 | Jane 2 | Mary |
SELECT column_list | 4 | David
| | NULL | NULL |
FROM table_1 | 35 | Amelia
Mary | 3 | Amelia |
LEFT JOIN table_2 USING (column_name); + - - - - - - - - - - - + - |- - - - - - - + - - - - - - - - - - - - - - + - - - - - - - - - - - +
5 rows i n s et (0.00 sec)

34
RIGHT JOIN clause SELECT
m.member_id,
m.name AS member,
The right join clause selects all rows from the c.committee_id,
right table and matches rows in the left table. If a c.name AS
row from the right table does not have matching committee
rows from the left table, the column of the left FROM
table will have NULL in the final result set. members m
RIGHT JOIN
SELECT column_list committees c on
FROM table_1 c.name = m.name;
RIGHT JOIN table_2 +-----------+--------+--------------+-----------+
ON join_condition; | member_id | member | committee_id | committee |
+-----------+--------+--------------+-----------+
Similar to the left join clause, the right clause | 1 | John | 1 | John |
also supports the USING syntax: | 3 | Mary | 2 | Mary |
| 5 | Amelia | 3 | Amelia |
| NULL | NULL | 4 | Joe |
SELECT column_list +-----------+--------+--------------+-----------+
FROM table_1 4 rows i n s et (0.00 sec)
RIGHT JOIN table_2
USING 35
(column_name);
Inner Join Examples

Find The productCode and productName


from the products table.
And The textDescription of product lines
from the productlines table.

SELECT
productCode,
productName,
textDescription SELECT
productCode,
FROM
productName,
products t1 textDescription
INNER JOIN productlines t2 FROM
ON t1.productline = t2.productline; products
INNER JOIN
productlines 36
USING
Inner Join Examples

Find order order status, and


number,
total sales from the orders and
SELECT
orderdetails
orderNumber,
SELECT status,
t1.orderNumber, SUM(quantityOrdered * priceEach) total
t1.status, FROM
SUM(quantityOrdered * priceEach) total orders
FROM INNER JOIN orderdetails USING
orders t1 (orderNumber) GROUP BY orderNumber;
INNER JOIN orderdetails t2
ON t1.orderNumber = t2.orderNumber
GROUP BY orderNumber;

37
GROUP BY clause
The GROUP BY clause groups a set of rows into a set of summary rows by values of columns or
expressions. The GROUP BY clause returns one row for each group. In other words, it reduces the number
of rows in the result set.
The GROUP BY clause is an optional clause of the SELECT statement.

GROUP BY clause with often use with aggregate functions such as SUM, AVG, MAX, MIN, and COUNT. The
aggregate function that appears in the SELECT clause provides the information of each group.
SELECT
c1, c2,..., cn, aggregate_function(ci)
FROM
table

WHERE
where_conditions
GROUP BY c1 , c2,...,cn;

38
GROUP BY clause

Get the total amount of all orders by


status,

We join the orders table with the SELECT


status,
orderdetails table and use the SUM SUM(quantityOrdered * priceEach) AS amount
function to calculate the total amount. FROM
orders
INNER JOIN orderdetails
USING
(orderNumber)
GROUP BY
status;

39
HAVING clause

To filter the groups returned by GROUP SELECT


YEAR(orderDate) AS year,
BY clause, you use a HAVING clause. SUM(quantityOrdered * priceEach) AS total
FROM
Select the total sales of the years after orders
2003. INNER JOIN orderdetails
USING
(orderNumber)
WHERE
status = 'Shipped'
GROUP BY
year
HAVIN
G
ye 40
ar >

You might also like