321DBMS Unit 2 PPT (SQL)
321DBMS Unit 2 PPT (SQL)
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
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
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
6
TCL: Transaction Control Language
7
DCL: Data Control Language
8
SQL Data Types
Datatype Use
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).
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
DECIMAL(P,S) Exact numerical, 'P' is precision value and 'S' is scale value.
10
Data type Description
BIT VARYING(N) 'N' is the number of bits to store (length can vary up to N)
TIMESTAMP stores year, month, day, hour, minute and second values
TIME WITH exactly same as time but also store an offset from UTC
TIMESTAMP WITH same as timestamp but also stores an offset from UTC of
11
SQL Command Description
SQL Command
CREATE DATABASE Creates a new database
Create Database:
Example:
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,
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 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;
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.
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.
< Less than. You typically use it with numeric and date/time data types.
28
In this syntax:
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.
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
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
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
39
HAVING clause