SQL
Structured Query Language
By
Dr.Shrija Madhu
Head L&D
GIET(A),Rajahmundry 1
SQL Introduction
2
Standard language for querying and manipulating data
Type of SQL statements are divided into five different
categories:
• Data definition language (DDL),
• Data manipulation language (DML),
• Data Control Language (DCL),
• Transaction Control Statement (TCS),
• Session Control Statements (SCS).
Data Definition Language (DDL)
Data definition statement are use to define the database structure
or table.
Statement Description
CREATE Create new database/table.
ALTER Modifies the structure of database/table.
DROP Deletes a database/table.
TRUNCATE Remove all table records including allocated table spaces.
RENAME Rename the database/table.
Data Manipulation Language (DML)
Data manipulation statement are used for managing data
within table object.
Statement Description
SELECT Retrieve data from the table.
INSERT Insert data into a table.
UPDATE Updates existing data with new data within a table.
DELETE Deletes the records rows from the table.
MERGE MERGE (also called UPSERT) statements to INSERT new records or UPDATE existing records depending on
condition matches or not.
LOCK TABLE LOCK TABLE statement to lock one or more tables in a specified mode. Table access denied to a other users for the
duration of your table operation.
CALL
EXPLAIN PLAN
Statements are supported in PL/SQL only for executed dynamically. CALL a PL/SQL program or EXPLAIN PATH
access the data path.
Data Control Language (DCL)
Data control statement are use to give privileges to access
limited data.
Statement Description
GRANT Gives privileges to user for accessing database data.
REVOKE Take back for given privileges.
ANALYZE ANALYZE statement to collect statistics information about index, cluster, table.
AUDIT To track the occurrence of a specific SQL statement or all SQL statements
during the user sessions.
COMMENT Write comment to the data table.
Transaction Control Language (TCL)
Transaction control statements are used to store the
changes permanently into database.
Statement Description
COMMIT Permanent work save into database.
ROLLBACK Restore database to original form since the last COMMIT.
SAVEPOINT Create SAVEPOINT for later use ROLLBACK the new changes.
SET
TRANSACTION
SET TRANSACTION command set the transaction properties
such as read-write/read only access.
Session Control Language (SCL)
Session control statements manage properties dynamically
of a user session.
Statement Description
ALTER SESSION ALTER SESSION statement to modify conditions or parameters
that are affect to your database connection.
SET ROLE SET ROLE statement to enable or disable the roles that are
currently enabled for the session.
Data Types in SQL
8
DDL COMMANDS
DDL Commands-Create Table
–Used for creating a table
Syntax:
CREATE TABLE table_name(
column_name1 datatype(size),
column_name2 datatype(size) ... );
Example:
SQL> CREATE TABLE users_info( no NUMBER(3,0), name VARCHAR(30), address
VARCHAR(70), contact_no VARCHAR(12) );
Table created.
DDL Commands-Drop Table
-Used for deleting or removing a table
Syntax
DROP TABLE table_name;
Example
SQL> DROP TABLE users_info;
Table dropped.
DDL Commands-Alter Table
-Used to add, manage or update table structure
ALTER TABLE Statement can do the following:
• TABLE RENAME
• ADD NEW COLUMN IN TABLE
• MODIFY EXISTING COLUMN IN TABLE
• RENAME COLUMN IN TABLE
• DROP THE EXISTING COLUMN IN TABLE
.
DDL Commands-Alter Table Contd.
.
SQL TABLE RENAME
You can rename the SQL table using this syntax,
Syntax
ALTER TABLE table_name RENAME TO new_table_name;
Example
SQL> ALTER TABLE userinfo RENAME TO user_info;
Table altered.
DDL Commands-Alter Table Contd.
.
SQL ADD NEW COLUMN IN TABLE
You can add new column in table using this syntax,
Syntax
ALTER TABLE table_name ADD column_name datatype[(size)];
Example
SQL> ALTER TABLE user_info ADD state VARCHAR2(12);
Table altered.
DDL Commands-Alter Table Contd.
.
SQL ADD MULTIPLE COLUMN IN TABLE
You can add multiple column in table at a time using this syntax,
Syntax
ALTER TABLE table_name ADD ( column_name1 datatype[(size)],
column_name2 datatype[(size)], ... );
Example
SQL> ALTER TABLE user_info ADD (city VARCHAR2(30), country
VARCHAR2(30) );
Table altered.
DDL Commands-Alter Table Contd.
.
SQL MODIFY EXISTING COLUMN IN TABLE
You can modify the existing column datatype, size, NOT NULL or CONSTRAINTS in table
using this syntax,
Syntax
ALTER TABLE table_name MODIFY column_name column_datatype[(size)];
Example
SQL> ALTER TABLE user_info MODIFY state VARCHAR2(10);
Table altered.
DDL Commands-Alter Table Contd.
.
SQL RENAME COLUMN IN TABLE
You can rename the existing column in table using this syntax,
Syntax
ALTER TABLE table_name RENAME COLUMN old_column_name TO
new_column_name;
Example
SQL> ALTER TABLE user_info RENAME COLUMN no TO sno;
Table altered.
DDL Commands-Alter Table Contd.
.
SQL DROP THE COLUMN IN TABLE
You can drop existing column in table using this syntax,
Syntax
ALTER TABLE table_name DROP COLUMN column_name;
Example
SQL> ALTER TABLE user_info DROP COLUMN country;
Table altered.
DML COMMANDS
DML Commands-Insert
.
INSERT INTO statement
Using INSERT INTO statement to insert record into database.
When inserting data into table no need to specify the column names if values is table structure wise (column wise).
Syntax
INSERT INTO table_name VALUES (value1, value2, value3, ...);
Example
SQL> INSERT INTO users_info VALUES (1, 'Opal Kole', '63 street Ct.', '000-444-7847');
1 row created.
When you inserting data into table and you haven't know table structure you must specify the column name.
Syntax
INSERT INTO table_name [ (column_name1, column_name2, ...) ] VALUES (value1, value2, ...);
Example
SQL> INSERT INTO users_info (name, address, no, contact_no) VALUES ('Beccaa Moss', '2500 green
city.', 3, '000-444-7142');
1 row created.
DML Commands-Insert Contd.
.
INSERT ALL statement
Using INSERT ALL statement to insert more then one records into table.We can insert more then one record in single
SQL INSERT statement.
Syntax
INSERT ALL INTO table_name [ (column_name1, column_name2, ...) ] VALUES (record1_value1,
record1_value2, ...) INTO table_name [ (column_name1, column_name2, ...) ] VALUES
(record2_value1, record2_value2, ...) INTO table_name [ (column_name1, column_name2, ...) ]
VALUES (record3_value1, record3_value2, ...) .... SELECT * FROM dual;
Example
SQL> INSERT ALL INTO users_info (no, name, address, contact_no) VALUES (4, 'Paul Singh', '1343
Prospect St', '000-444-7141') INTO users_info (no, name, address, contact_no) VALUES (5, 'Ken
Myer', '137 Clay Road', '000-444-7084') INTO users_info (no, name, address, contact_no) VALUES
(6, 'Jack Evans', '1365 Grove Way', '000-444-7957') INTO users_info (no, name, address,
contact_no) VALUES (7, 'Reed Koch', '1274 West Street', '000-444-4784') SELECT * FROM dual; 4
rows created.
DML Commands-Insert Contd.
.
SQL Multiple Row Insert into Table
You can insert multiple record by this way first you execute INSERT INTO statement with & sign with column name. If you
want to add another record you just execute forward slash (/) to again execute last statement automatically and you can
insert new data again.
SQL> INSERT INTO users_info VALUES (&no, &name, &address, &contact_no);
Enter value for no: 8
Enter value for name: 'Gabe Hee'
Enter value for address: '1220 Dallas Drive'
Enter value for contact_no: '000-444-4584'
old 1: INSERT INTO users_info VALUES (&no, &name, &address, &contact_no)
new 1: INSERT INTO users_info VALUES (8, 'Gabe Hee', '1220 Dallas Drive', '000-444-4584')
1 row created.
SQL> /
Enter value for no: 9
Enter value for name: 'Ben Mares'
Enter value for address: '101 Candy Road'
Enter value for contact_no: '000-444-5484'
old 1: INSERT INTO users_info VALUES (&no, &name, &address, &contact_no)
new 1: INSERT INTO users_info VALUES (9, 'Ben Mares', '101 Candy Road', '000-444-5484')
1 row created.
DML Commands-Insert Contd.
.
SQL Insert Data only in specified COLUMNS
You can insert data in specific columns. When you write INSERT statement you have
to specify column name for inserting only that column data into table.
Syntax
INSERT INTO Table_Name (specific_column_name1, ...) VALUES
(value1,...);
Example
SQL> INSERT INTO users_info(no, name) VALUES (10, 'Sariya Vargas');
1 row created.
DML Commands-Insert Contd.
.
INSERT INTO SELECT Statement
INSERT INTO SELECT Statement is used to insert data into a table from another
table.
Syntax
INSERT INTO new_table_name [(column_name1,column_name2,...)] SELECT
column_name1, column_name1 ... FROM another_table_name [WHERE
condition];
Example
SQL> CREATE TABLE demo_tbl( no NUMBER(3), name VARCHAR2(50) ); Table
created. SQL> INSERT INTO demo_tbl (no, name) SELECT no, name FROM
users_info; 10 rows created.
DML Commands-Update Command
SQL UPDATE statement to update table records with in database. You can update all table row or
update data only matching condition using WHERE clause.
.
SQL UPDATE All Rows
Syntax
UPDATE table_name SET column_name1 = value1, column_name2 = value2, ...;
Example Statement
SQL> UPDATE demo1 SET contact_no = 444;
10 rows updated.
.
DML Commands-Update Command
SQL UPDATE statement to update table records with in database. You can update all table row or
update data only matching condition using WHERE clause.
.
SQL UPDATE All Rows
Syntax
UPDATE table_name SET column_name1 = value1, column_name2 = value2, ...;
Example Statement
SQL> UPDATE demo1 SET contact_no = 444;
10 rows updated.
.
DML Commands-Delete Command
SQL DELETE Statement is used to delete one or more then one row removed from table.
SQL DELETE Query use following two way,
•Remove all TABLE rows
•Remove only specific TABLE row/rows
Remove only specific TABLE row
Syntax
DELETE FROM table_name [ WHERE condition ] [ LIMIT number ];
Example
SQL> DELETE FROM demo1 WHERE NO = 10;
1 row deleted.
Remove all TABLE rows
Syntax
DELETE FROM table_name;
Example
SQL> DELETE FROM demo1;
9 rows deleted.
Tables in SQL
28
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Attribute names
Table name
Tuples or rows
Tables Explained
• The schema of a table is the table name and its attributes:
Product(PName, Price, Category, Manfacturer)
• A key is an attribute whose values are unique;
we underline a key
Product(PName, Price, Category, Manfacturer)
29
SQL Select Query
30
Basic form: (plus many many more bells and whistles)
SELECT attributes
FROM relations (possibly multiple)
WHERE conditions (selections)
Simple SQL Query
31
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT *
FROM Product
WHERE category=‘Gadgets’
Product
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks“selection”
Simple SQL Query
32
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
Product
PName Price Manufacturer
SingleTouch $149.99 Canon
MultiTouch $203.99 Hitachi
“selection” and
“projection”
A Notation for SQL Queries
33
SELECT PName, Price, Manufacturer
FROM Product
WHERE Price > 100
Product(PName, Price, Category, Manfacturer)
Answer(PName, Price, Manfacturer)
Input Schema
Output Schema
Selections
What goes in the WHERE clause:
• x = y, x < y, x <= y, etc
• For number, they have the usual meanings
• For CHAR and VARCHAR: lexicographic ordering
• Expected conversion between CHAR and VARCHAR
• For dates and times, what you expect...
• Pattern matching on strings...
34
The LIKE operator
• s LIKE p: pattern matching on strings
• p may contain two special symbols:
• % = any sequence of characters
• _ = any single character
Product(PName, Price, Category, Manufacturer)
Find all products whose name mentions ‘gizmo’:
35
SELECT *
FROM Products
WHERE PName LIKE ‘%gizmo%’
Eliminating Duplicates
36
SELECT DISTINCT category
FROM Product
Compare to:
SELECT category
FROM Product
Category
Gadgets
Gadgets
Photography
Household
Category
Gadgets
Photography
Household
Ordering the Results
37
SELECT pname, price, manufacturer
FROM Product
WHERE category=‘gizmo’ AND price > 50
ORDER BY price, pname
Ordering is ascending, unless you specify the DESC keyword.
Ties are broken by the second attribute on the ORDER BY list, etc.
Ordering the Results
38
SELECT category
FROM Product
ORDER BY pname
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
?
Ordering the Results
39
SELECT DISTINCT category
FROM Product
ORDER BY category
Compare to:
Category
Gadgets
Household
Photography
SELECT category
FROM Product
ORDER BY pname ?
Joins in SQL
• Connect two or more tables:
40
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
What is
the connection
between
them ?
Exercises
41
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Company (cname, stock price, country)
Person(per-name, phone number, city)
Ex #1: Find people who bought telephony products.
Ex #2: Find names of people who bought American products
Ex #3: Find names of people who bought American products and they
live in Seattle.
Ex #4: Find people who have both bought and sold something.
Ex #5: Find people who bought stuff from Joe or bought products
from a company whose stock prices is more than $50.
Joins
42
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all products under $200 manufactured in Japan;
return their names and prices.
SELECT pname, price
FROM Product, Company
WHERE manufacturer=cname AND country=‘Japan’
AND price <= 200
Join
between Product
and Company
Joins in SQL
43
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
PName Price
SingleTouch $149.99
SELECT pname, price
FROM Product, Company
WHERE manufacturer=cname AND country=‘Japan’
AND price <= 200
Joins
44
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
Find all countries that manufacture some product in the ‘Gadgets’ category.
SELECT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’
Joins in SQL
45
Name Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Product
Company
Cname StockPrice Country
GizmoWorks 25 USA
Canon 65 Japan
Hitachi 15 Japan
SELECT country
FROM Product, Company
WHERE manufacturer=cname AND category=‘Gadgets’
Country
??
??
What is
the problem ?
What’s the
solution ?
Joins
46
Product (pname, price, category, manufacturer)
Purchase (buyer, seller, store, product)
Person(persname, phoneNumber, city)
Find names of people living in Seattle that bought some product in the
‘Gadgets’ category, and the names of the stores they bought such product
from
SELECT DISTINCT persname, store
FROM Person, Purchase, Product
WHERE persname=buyer AND product = pname AND
city=‘Seattle’ AND category=‘Gadgets’
Disambiguating Attributes
• Sometimes two relations have the same attr:
Person(pname, address, worksfor)
Company(cname, address)
47
SELECT DISTINCT pname, address
FROM Person, Company
WHERE worksfor = cname
SELECT DISTINCT Person.pname, Company.address
FROM Person, Company
WHERE Person.worksfor = Company.cname
Which
address ?
Aggregate functions
• AVG – calculates the average of a set of values.
• COUNT – counts rows in a specified table or view.
• MIN – gets the minimum value in a set of values.
• MAX – gets the maximum value in a set of values.
• SUM – calculates the sum of values.
Aggregate functions
• AVG – calculates the average of a set of values.
ex. Select avg(salary) from Employee
• COUNT – counts rows in a specified table or view.
ex. Select count(salary) from Employee where salary>10000;
• MIN – gets the minimum value in a set of values.
ex. Select min(salary) from Employee
• MAX – gets the maximum value in a set of values.
ex. Select max(salary) from Employee
• SUM – calculates the sum of values.
ex. Select sum(salary) from Employee
References
• http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
• https://www.way2tutorial.com/sql/type-of-sql-statements.php
• https://www.journaldev.com/16774/sql-data-types

SQL - DML and DDL Commands

  • 1.
    SQL Structured Query Language By Dr.ShrijaMadhu Head L&D GIET(A),Rajahmundry 1
  • 2.
    SQL Introduction 2 Standard languagefor querying and manipulating data Type of SQL statements are divided into five different categories: • Data definition language (DDL), • Data manipulation language (DML), • Data Control Language (DCL), • Transaction Control Statement (TCS), • Session Control Statements (SCS).
  • 3.
    Data Definition Language(DDL) Data definition statement are use to define the database structure or table. Statement Description CREATE Create new database/table. ALTER Modifies the structure of database/table. DROP Deletes a database/table. TRUNCATE Remove all table records including allocated table spaces. RENAME Rename the database/table.
  • 4.
    Data Manipulation Language(DML) Data manipulation statement are used for managing data within table object. Statement Description SELECT Retrieve data from the table. INSERT Insert data into a table. UPDATE Updates existing data with new data within a table. DELETE Deletes the records rows from the table. MERGE MERGE (also called UPSERT) statements to INSERT new records or UPDATE existing records depending on condition matches or not. LOCK TABLE LOCK TABLE statement to lock one or more tables in a specified mode. Table access denied to a other users for the duration of your table operation. CALL EXPLAIN PLAN Statements are supported in PL/SQL only for executed dynamically. CALL a PL/SQL program or EXPLAIN PATH access the data path.
  • 5.
    Data Control Language(DCL) Data control statement are use to give privileges to access limited data. Statement Description GRANT Gives privileges to user for accessing database data. REVOKE Take back for given privileges. ANALYZE ANALYZE statement to collect statistics information about index, cluster, table. AUDIT To track the occurrence of a specific SQL statement or all SQL statements during the user sessions. COMMENT Write comment to the data table.
  • 6.
    Transaction Control Language(TCL) Transaction control statements are used to store the changes permanently into database. Statement Description COMMIT Permanent work save into database. ROLLBACK Restore database to original form since the last COMMIT. SAVEPOINT Create SAVEPOINT for later use ROLLBACK the new changes. SET TRANSACTION SET TRANSACTION command set the transaction properties such as read-write/read only access.
  • 7.
    Session Control Language(SCL) Session control statements manage properties dynamically of a user session. Statement Description ALTER SESSION ALTER SESSION statement to modify conditions or parameters that are affect to your database connection. SET ROLE SET ROLE statement to enable or disable the roles that are currently enabled for the session.
  • 8.
  • 9.
  • 10.
    DDL Commands-Create Table –Usedfor creating a table Syntax: CREATE TABLE table_name( column_name1 datatype(size), column_name2 datatype(size) ... ); Example: SQL> CREATE TABLE users_info( no NUMBER(3,0), name VARCHAR(30), address VARCHAR(70), contact_no VARCHAR(12) ); Table created.
  • 11.
    DDL Commands-Drop Table -Usedfor deleting or removing a table Syntax DROP TABLE table_name; Example SQL> DROP TABLE users_info; Table dropped.
  • 12.
    DDL Commands-Alter Table -Usedto add, manage or update table structure ALTER TABLE Statement can do the following: • TABLE RENAME • ADD NEW COLUMN IN TABLE • MODIFY EXISTING COLUMN IN TABLE • RENAME COLUMN IN TABLE • DROP THE EXISTING COLUMN IN TABLE .
  • 13.
    DDL Commands-Alter TableContd. . SQL TABLE RENAME You can rename the SQL table using this syntax, Syntax ALTER TABLE table_name RENAME TO new_table_name; Example SQL> ALTER TABLE userinfo RENAME TO user_info; Table altered.
  • 14.
    DDL Commands-Alter TableContd. . SQL ADD NEW COLUMN IN TABLE You can add new column in table using this syntax, Syntax ALTER TABLE table_name ADD column_name datatype[(size)]; Example SQL> ALTER TABLE user_info ADD state VARCHAR2(12); Table altered.
  • 15.
    DDL Commands-Alter TableContd. . SQL ADD MULTIPLE COLUMN IN TABLE You can add multiple column in table at a time using this syntax, Syntax ALTER TABLE table_name ADD ( column_name1 datatype[(size)], column_name2 datatype[(size)], ... ); Example SQL> ALTER TABLE user_info ADD (city VARCHAR2(30), country VARCHAR2(30) ); Table altered.
  • 16.
    DDL Commands-Alter TableContd. . SQL MODIFY EXISTING COLUMN IN TABLE You can modify the existing column datatype, size, NOT NULL or CONSTRAINTS in table using this syntax, Syntax ALTER TABLE table_name MODIFY column_name column_datatype[(size)]; Example SQL> ALTER TABLE user_info MODIFY state VARCHAR2(10); Table altered.
  • 17.
    DDL Commands-Alter TableContd. . SQL RENAME COLUMN IN TABLE You can rename the existing column in table using this syntax, Syntax ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Example SQL> ALTER TABLE user_info RENAME COLUMN no TO sno; Table altered.
  • 18.
    DDL Commands-Alter TableContd. . SQL DROP THE COLUMN IN TABLE You can drop existing column in table using this syntax, Syntax ALTER TABLE table_name DROP COLUMN column_name; Example SQL> ALTER TABLE user_info DROP COLUMN country; Table altered.
  • 19.
  • 20.
    DML Commands-Insert . INSERT INTOstatement Using INSERT INTO statement to insert record into database. When inserting data into table no need to specify the column names if values is table structure wise (column wise). Syntax INSERT INTO table_name VALUES (value1, value2, value3, ...); Example SQL> INSERT INTO users_info VALUES (1, 'Opal Kole', '63 street Ct.', '000-444-7847'); 1 row created. When you inserting data into table and you haven't know table structure you must specify the column name. Syntax INSERT INTO table_name [ (column_name1, column_name2, ...) ] VALUES (value1, value2, ...); Example SQL> INSERT INTO users_info (name, address, no, contact_no) VALUES ('Beccaa Moss', '2500 green city.', 3, '000-444-7142'); 1 row created.
  • 21.
    DML Commands-Insert Contd. . INSERTALL statement Using INSERT ALL statement to insert more then one records into table.We can insert more then one record in single SQL INSERT statement. Syntax INSERT ALL INTO table_name [ (column_name1, column_name2, ...) ] VALUES (record1_value1, record1_value2, ...) INTO table_name [ (column_name1, column_name2, ...) ] VALUES (record2_value1, record2_value2, ...) INTO table_name [ (column_name1, column_name2, ...) ] VALUES (record3_value1, record3_value2, ...) .... SELECT * FROM dual; Example SQL> INSERT ALL INTO users_info (no, name, address, contact_no) VALUES (4, 'Paul Singh', '1343 Prospect St', '000-444-7141') INTO users_info (no, name, address, contact_no) VALUES (5, 'Ken Myer', '137 Clay Road', '000-444-7084') INTO users_info (no, name, address, contact_no) VALUES (6, 'Jack Evans', '1365 Grove Way', '000-444-7957') INTO users_info (no, name, address, contact_no) VALUES (7, 'Reed Koch', '1274 West Street', '000-444-4784') SELECT * FROM dual; 4 rows created.
  • 22.
    DML Commands-Insert Contd. . SQLMultiple Row Insert into Table You can insert multiple record by this way first you execute INSERT INTO statement with & sign with column name. If you want to add another record you just execute forward slash (/) to again execute last statement automatically and you can insert new data again. SQL> INSERT INTO users_info VALUES (&no, &name, &address, &contact_no); Enter value for no: 8 Enter value for name: 'Gabe Hee' Enter value for address: '1220 Dallas Drive' Enter value for contact_no: '000-444-4584' old 1: INSERT INTO users_info VALUES (&no, &name, &address, &contact_no) new 1: INSERT INTO users_info VALUES (8, 'Gabe Hee', '1220 Dallas Drive', '000-444-4584') 1 row created. SQL> / Enter value for no: 9 Enter value for name: 'Ben Mares' Enter value for address: '101 Candy Road' Enter value for contact_no: '000-444-5484' old 1: INSERT INTO users_info VALUES (&no, &name, &address, &contact_no) new 1: INSERT INTO users_info VALUES (9, 'Ben Mares', '101 Candy Road', '000-444-5484') 1 row created.
  • 23.
    DML Commands-Insert Contd. . SQLInsert Data only in specified COLUMNS You can insert data in specific columns. When you write INSERT statement you have to specify column name for inserting only that column data into table. Syntax INSERT INTO Table_Name (specific_column_name1, ...) VALUES (value1,...); Example SQL> INSERT INTO users_info(no, name) VALUES (10, 'Sariya Vargas'); 1 row created.
  • 24.
    DML Commands-Insert Contd. . INSERTINTO SELECT Statement INSERT INTO SELECT Statement is used to insert data into a table from another table. Syntax INSERT INTO new_table_name [(column_name1,column_name2,...)] SELECT column_name1, column_name1 ... FROM another_table_name [WHERE condition]; Example SQL> CREATE TABLE demo_tbl( no NUMBER(3), name VARCHAR2(50) ); Table created. SQL> INSERT INTO demo_tbl (no, name) SELECT no, name FROM users_info; 10 rows created.
  • 25.
    DML Commands-Update Command SQLUPDATE statement to update table records with in database. You can update all table row or update data only matching condition using WHERE clause. . SQL UPDATE All Rows Syntax UPDATE table_name SET column_name1 = value1, column_name2 = value2, ...; Example Statement SQL> UPDATE demo1 SET contact_no = 444; 10 rows updated. .
  • 26.
    DML Commands-Update Command SQLUPDATE statement to update table records with in database. You can update all table row or update data only matching condition using WHERE clause. . SQL UPDATE All Rows Syntax UPDATE table_name SET column_name1 = value1, column_name2 = value2, ...; Example Statement SQL> UPDATE demo1 SET contact_no = 444; 10 rows updated. .
  • 27.
    DML Commands-Delete Command SQLDELETE Statement is used to delete one or more then one row removed from table. SQL DELETE Query use following two way, •Remove all TABLE rows •Remove only specific TABLE row/rows Remove only specific TABLE row Syntax DELETE FROM table_name [ WHERE condition ] [ LIMIT number ]; Example SQL> DELETE FROM demo1 WHERE NO = 10; 1 row deleted. Remove all TABLE rows Syntax DELETE FROM table_name; Example SQL> DELETE FROM demo1; 9 rows deleted.
  • 28.
    Tables in SQL 28 PNamePrice Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Attribute names Table name Tuples or rows
  • 29.
    Tables Explained • Theschema of a table is the table name and its attributes: Product(PName, Price, Category, Manfacturer) • A key is an attribute whose values are unique; we underline a key Product(PName, Price, Category, Manfacturer) 29
  • 30.
    SQL Select Query 30 Basicform: (plus many many more bells and whistles) SELECT attributes FROM relations (possibly multiple) WHERE conditions (selections)
  • 31.
    Simple SQL Query 31 PNamePrice Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT * FROM Product WHERE category=‘Gadgets’ Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks“selection”
  • 32.
    Simple SQL Query 32 PNamePrice Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 Product PName Price Manufacturer SingleTouch $149.99 Canon MultiTouch $203.99 Hitachi “selection” and “projection”
  • 33.
    A Notation forSQL Queries 33 SELECT PName, Price, Manufacturer FROM Product WHERE Price > 100 Product(PName, Price, Category, Manfacturer) Answer(PName, Price, Manfacturer) Input Schema Output Schema
  • 34.
    Selections What goes inthe WHERE clause: • x = y, x < y, x <= y, etc • For number, they have the usual meanings • For CHAR and VARCHAR: lexicographic ordering • Expected conversion between CHAR and VARCHAR • For dates and times, what you expect... • Pattern matching on strings... 34
  • 35.
    The LIKE operator •s LIKE p: pattern matching on strings • p may contain two special symbols: • % = any sequence of characters • _ = any single character Product(PName, Price, Category, Manufacturer) Find all products whose name mentions ‘gizmo’: 35 SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’
  • 36.
    Eliminating Duplicates 36 SELECT DISTINCTcategory FROM Product Compare to: SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 37.
    Ordering the Results 37 SELECTpname, price, manufacturer FROM Product WHERE category=‘gizmo’ AND price > 50 ORDER BY price, pname Ordering is ascending, unless you specify the DESC keyword. Ties are broken by the second attribute on the ORDER BY list, etc.
  • 38.
    Ordering the Results 38 SELECTcategory FROM Product ORDER BY pname PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi ?
  • 39.
    Ordering the Results 39 SELECTDISTINCT category FROM Product ORDER BY category Compare to: Category Gadgets Household Photography SELECT category FROM Product ORDER BY pname ?
  • 40.
    Joins in SQL •Connect two or more tables: 40 PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan What is the connection between them ?
  • 41.
    Exercises 41 Product (pname, price,category, manufacturer) Purchase (buyer, seller, store, product) Company (cname, stock price, country) Person(per-name, phone number, city) Ex #1: Find people who bought telephony products. Ex #2: Find names of people who bought American products Ex #3: Find names of people who bought American products and they live in Seattle. Ex #4: Find people who have both bought and sold something. Ex #5: Find people who bought stuff from Joe or bought products from a company whose stock prices is more than $50.
  • 42.
    Joins 42 Product (pname, price,category, manufacturer) Company (cname, stockPrice, country) Find all products under $200 manufactured in Japan; return their names and prices. SELECT pname, price FROM Product, Company WHERE manufacturer=cname AND country=‘Japan’ AND price <= 200 Join between Product and Company
  • 43.
    Joins in SQL 43 PNamePrice Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan PName Price SingleTouch $149.99 SELECT pname, price FROM Product, Company WHERE manufacturer=cname AND country=‘Japan’ AND price <= 200
  • 44.
    Joins 44 Product (pname, price,category, manufacturer) Company (cname, stockPrice, country) Find all countries that manufacture some product in the ‘Gadgets’ category. SELECT country FROM Product, Company WHERE manufacturer=cname AND category=‘Gadgets’
  • 45.
    Joins in SQL 45 NamePrice Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Gadgets GizmoWorks SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 Japan SELECT country FROM Product, Company WHERE manufacturer=cname AND category=‘Gadgets’ Country ?? ?? What is the problem ? What’s the solution ?
  • 46.
    Joins 46 Product (pname, price,category, manufacturer) Purchase (buyer, seller, store, product) Person(persname, phoneNumber, city) Find names of people living in Seattle that bought some product in the ‘Gadgets’ category, and the names of the stores they bought such product from SELECT DISTINCT persname, store FROM Person, Purchase, Product WHERE persname=buyer AND product = pname AND city=‘Seattle’ AND category=‘Gadgets’
  • 47.
    Disambiguating Attributes • Sometimestwo relations have the same attr: Person(pname, address, worksfor) Company(cname, address) 47 SELECT DISTINCT pname, address FROM Person, Company WHERE worksfor = cname SELECT DISTINCT Person.pname, Company.address FROM Person, Company WHERE Person.worksfor = Company.cname Which address ?
  • 48.
    Aggregate functions • AVG– calculates the average of a set of values. • COUNT – counts rows in a specified table or view. • MIN – gets the minimum value in a set of values. • MAX – gets the maximum value in a set of values. • SUM – calculates the sum of values.
  • 49.
    Aggregate functions • AVG– calculates the average of a set of values. ex. Select avg(salary) from Employee • COUNT – counts rows in a specified table or view. ex. Select count(salary) from Employee where salary>10000; • MIN – gets the minimum value in a set of values. ex. Select min(salary) from Employee • MAX – gets the maximum value in a set of values. ex. Select max(salary) from Employee • SUM – calculates the sum of values. ex. Select sum(salary) from Employee
  • 50.

Editor's Notes

  • #9 Diagram Reference:https://www.journaldev.com/16774/sql-data-types
  • #29 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #31 http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #32 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #33 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #34 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #37 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #38 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #39 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #40 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #41 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #43 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #44 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #45 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #46 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  • #47 Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt