SQL - DML and DDL Commands

S
Shrija MadhuPROFESSOR um GIET
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
1 von 50

Recomendados

Sql commandsSql commands
Sql commandsPooja Dixit
597 views18 Folien
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)Sharad Dubey
16.2K views20 Folien
MysqlMysql
MysqlTSUBHASHRI
1.9K views27 Folien
SQL Commands SQL Commands
SQL Commands Sachidananda M H
2K views73 Folien
SQL OverviewSQL Overview
SQL OverviewStewart Rogers
6K views37 Folien

Más contenido relacionado

Was ist angesagt?(20)

Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde3.5K views
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
Dhananjay Goel6.9K views
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
Knowledge Center Computer 668 views
Introduction to sqlIntroduction to sql
Introduction to sql
VARSHAKUMARI49382 views
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies31.6K views
SQL BasicsSQL Basics
SQL Basics
Hammad Rasheed40.4K views
Joins in SQLJoins in SQL
Joins in SQL
Vigneshwaran Sankaran2.7K views
Sql commandsSql commands
Sql commands
Prof. Dr. K. Adisesha6.6K views
SQL commandsSQL commands
SQL commands
GirdharRatne8.8K views
TriggersTriggers
Triggers
Pooja Dixit658 views
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
bixxman10.7K views
Basic sql CommandsBasic sql Commands
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL603 views
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
Ankit Rai2.5K views
Sql tutorialSql tutorial
Sql tutorial
Rumman Ansari1.9K views
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers10K views
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
Mohan Kumar.R1.8K views
SQLSQL
SQL
Vineeta Garg1.8K views
Sql queries presentationSql queries presentation
Sql queries presentation
NITISH KUMAR8.4K views
SQL - RDBMS ConceptsSQL - RDBMS Concepts
SQL - RDBMS Concepts
WebStackAcademy6K views

Similar a SQL - DML and DDL Commands

Oracle sql materialOracle sql material
Oracle sql materialprathap kumar
1.1K views23 Folien
SqlbysandeepSqlbysandeep
Sqlbysandeepsandeepkhandare1183
517 views15 Folien
COMPUTERS SQL COMPUTERS SQL
COMPUTERS SQL Rc Os
50 views6 Folien
SQL QuerySQL Query
SQL QueryImam340267
21 views29 Folien
SQLSQL
SQLShyam Khant
268 views94 Folien

Similar a SQL - DML and DDL Commands(20)

Oracle sql materialOracle sql material
Oracle sql material
prathap kumar1.1K views
SqlbysandeepSqlbysandeep
Sqlbysandeep
sandeepkhandare1183517 views
COMPUTERS SQL COMPUTERS SQL
COMPUTERS SQL
Rc Os50 views
SQL QuerySQL Query
SQL Query
Imam34026721 views
SQLSQL
SQL
Shyam Khant268 views
Introduction to sql newIntroduction to sql new
Introduction to sql new
SANTOSH RATH424 views
Sql basics and DDL statementsSql basics and DDL statements
Sql basics and DDL statements
Mohd Tousif438 views
LabLab
Lab
neelam_rawat1.1K views
SQL.pptSQL.ppt
SQL.ppt
Ranjit27351526 views
SqlSql
Sql
Karunakaran Mallikeswaran1.5K views
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
paddu123589 views
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
paddu123594 views
SQL-SHORT-NOTES.pptxSQL-SHORT-NOTES.pptx
SQL-SHORT-NOTES.pptx
PratheeshKumarN2 views
Assignment#02Assignment#02
Assignment#02
Sunita Milind Dol1.4K views
MySQL Essential TrainingMySQL Essential Training
MySQL Essential Training
HudaRaghibKadhim88 views
Sql tutorialSql tutorial
Sql tutorial
amitabros47 views
Basic sql(oracle) queriesBasic sql(oracle) queries
Basic sql(oracle) queries
Harish Gyanani966 views
SQLSQL
SQL
Rajesh-QA48 views
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
NETsolutions Asia: NSA – Thailand, Sripatum University: SPU1.4K views
Sql Commands_Dr.R.Shalini.pptSql Commands_Dr.R.Shalini.ppt
Sql Commands_Dr.R.Shalini.ppt
DrRShaliniVISTAS90 views

Último(20)

231112 (WR) v1  ChatGPT OEB 2023.pdf231112 (WR) v1  ChatGPT OEB 2023.pdf
231112 (WR) v1 ChatGPT OEB 2023.pdf
WilfredRubens.com118 views
Lecture: Open InnovationLecture: Open Innovation
Lecture: Open Innovation
Michal Hron94 views
Plastic waste.pdfPlastic waste.pdf
Plastic waste.pdf
alqaseedae94 views
Structure and Functions of Cell.pdfStructure and Functions of Cell.pdf
Structure and Functions of Cell.pdf
Nithya Murugan256 views
STYP infopack.pdfSTYP infopack.pdf
STYP infopack.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego159 views
STERILITY TEST.pptxSTERILITY TEST.pptx
STERILITY TEST.pptx
Anupkumar Sharma107 views
Narration  ppt.pptxNarration  ppt.pptx
Narration ppt.pptx
TARIQ KHAN76 views
Psychology KS5Psychology KS5
Psychology KS5
WestHatch56 views
Azure DevOps Pipeline setup for Mule APIs #36Azure DevOps Pipeline setup for Mule APIs #36
Azure DevOps Pipeline setup for Mule APIs #36
MysoreMuleSoftMeetup84 views
Psychology KS4Psychology KS4
Psychology KS4
WestHatch54 views
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov74 views
Scope of Biochemistry.pptxScope of Biochemistry.pptx
Scope of Biochemistry.pptx
shoba shoba119 views
Streaming Quiz 2023.pdfStreaming Quiz 2023.pdf
Streaming Quiz 2023.pdf
Quiz Club NITW97 views
Gopal Chakraborty Memorial Quiz 2.0 Prelims.pptxGopal Chakraborty Memorial Quiz 2.0 Prelims.pptx
Gopal Chakraborty Memorial Quiz 2.0 Prelims.pptx
Debapriya Chakraborty479 views
discussion post.pdfdiscussion post.pdf
discussion post.pdf
jessemercerail85 views
BYSC infopack.pdfBYSC infopack.pdf
BYSC infopack.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego160 views

SQL - DML and DDL Commands

  • 1. SQL Structured Query Language By Dr.Shrija Madhu Head L&D GIET(A),Rajahmundry 1
  • 2. 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).
  • 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.
  • 10. 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.
  • 11. DDL Commands-Drop Table -Used for deleting or removing a table Syntax DROP TABLE table_name; Example SQL> DROP TABLE users_info; Table dropped.
  • 12. 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 .
  • 13. 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.
  • 14. 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.
  • 15. 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.
  • 16. 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.
  • 17. 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.
  • 18. 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.
  • 20. 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.
  • 21. 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.
  • 22. 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.
  • 23. 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.
  • 24. 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.
  • 25. 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. .
  • 26. 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. .
  • 27. 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.
  • 28. 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
  • 29. 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
  • 30. SQL Select Query 30 Basic form: (plus many many more bells and whistles) SELECT attributes FROM relations (possibly multiple) WHERE conditions (selections)
  • 31. 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”
  • 32. 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”
  • 33. 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
  • 34. 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
  • 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 DISTINCT category FROM Product Compare to: SELECT category FROM Product Category Gadgets Gadgets Photography Household Category Gadgets Photography Household
  • 37. 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.
  • 38. 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 ?
  • 39. 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 ?
  • 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 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
  • 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 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 ?
  • 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 • 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 ?
  • 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

Hinweis der Redaktion

  1. Diagram Reference:https://www.journaldev.com/16774/sql-data-types
  2. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  3. http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  4. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  5. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  6. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  7. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  8. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  9. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  10. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  11. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  12. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  13. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  14. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  15. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt
  16. Slides Reference: http://courses.cs.tau.ac.il/databases/databases2009/slides/sql-basic.ppt