Вы находитесь на странице: 1из 30

Prabin

Babu Dhakal, CDPA, TU

SQL
Structured Query Language
Crea<ng, Querying, edi<ng RDBMS
Prabin Babu Dhakal, CDPA, TU
Prabin Babu Dhakal, CDPA, TU

Introduc)on to SQL
•  Structured Query Language(SQL) is used for storing and managing data in RDBMS.
•  First commercial language introduced for E.F Codd's Rela)onal model.
•  Today almost all RDBMS uses SQL as the standard database language.
•  SQL is used to perform all type of data opera<ons in RDBMS.
•  DDL : Data Defini)on Language
–  create: to create new table or database alter: for altera<on
–  truncate: delete data from table drop: to drop a table
–  rename: to rename a table
•  DML : Data Manipula)on Language
–  insert: to insert a new row update: to update exis<ng row
–  delete: to delete a row merge: merging two rows or two tables
•  TCL : Transac)on Control Language
–  Keep a check on other commands and their effect on the database.
–  Can annul changes made by other commands by rolling back to original state. Or make changes permanent.
–  commit: to permanently save rollback: to undo change savepoint: to save temporarily
•  DCL : Data Control Language
–  Data control language provides command to grant and take back authority.
–  grant: grant permission of right revoke: take back permission.
•  DQL : Data Query Language
–  select: retrieve records from one or more table
Prabin Babu Dhakal, CDPA, TU

DQL: Data Query Language


•  Data Query Language (DQL)
•  Data Query Language is used to extract data from
the database. It doesn't modify any data in the
database. It describes only one query
•  Select query is used to retrieve data from tables.
–  The most used SQL query.
–  Can retrieve data from rela<on (table) in different ways
•  Can select complete table
•  Can select subset of aBributes (columns)
•  Can select subset of tuples (rows)
Prabin Babu Dhakal, CDPA, TU

SELECT statement
•  Syntax of select statement
•  SELECT <fieldlist>
FROM <tablename>
WHERE <condition>
–  <tablename>: States which rela<on (table) to select
data from
–  <fieldlist>: States which aSributes (columns) in table
to extract
–  <Condi<on>: States the condi<on for selec<ng tuple
(row) based on its values
–  Example:
SELECT col-name1, col-name4, col-name5
FROM table-name
WHERE condition;
Prabin Babu Dhakal, CDPA, TU

SELECT: Example table to be used


•  Consider the following Student table,
id name age address income
101 Ram 25 Ayodhya 10000
102 Sita 28 Janakpur 15000
103 Krish 27 Dwarika 13000
104 Buddha 22 Lumbini 16000
105 Radha 26 Gokul 18000

•  Now we want to select (retrieve) the data
according to our requirements
Prabin Babu Dhakal, CDPA, TU

SELECT: All records in a table


•  A special character asterisk * is used to address
all the data(belonging to all columns) in a query.
•  SELECT * FROM Student;
•  The above query will show all the records in
every column of the Student table.
id name age address income
101 Ram 25 Ayodhya 10000
102 Sita 28 Janakpur 15000
103 Krish 27 Dwarika 13000
104 Buddha 22 Lumbini 16000
105 Radha 26 Gokul 18000
Prabin Babu Dhakal, CDPA, TU

SELECT: Column wise


•  If we want only the id, name and age of all the
students, we can write following
•  SELECT id, name, age FROM Student;
–  The above query will fetch informa<on of id,
name and age column from Student table
id name age
101 Ram 25
102 Sita 28
103 Krish 27
104 Buddha 22
105 Radha 26
Prabin Babu Dhakal, CDPA, TU

SELECT: Perform simple calcula)on


SELECT id, name, income+3000 FROM Student;
•  Performs simple addi<on in output data
•  The above command will display a new column in the
result, showing 3000 added into exis<ng income of the
Students.
•  This command does not change the original table
•  Output:
id name income+3000
101 Ram 13000
102 Sita 18000
103 Krish 16000
104 Buddha 19000
105 Radha 21000

Prabin Babu Dhakal, CDPA, TU

WERE clause
•  Where clause is used to specify condi<on while
retrieving data from table.
•  Used mostly with Select, Update and Delete query.
•  If the condi<on specified by where clause is true for
the row, then only that result is returned.
•  Syntax for WHERE clause
–  SELECT field1, field2, field3, FieldN FROM table-name
WHERE [condi<on];
•  Example using WHERE clause
–  If we want to select rows based on their id. We want only
the record for a student whose id is exactly equal to 101
SELECT id, name, age, FROM Student WHERE id=101;
id name age
101 Ram 25
Prabin Babu Dhakal, CDPA, TU

SELECT: Based on Condi)on


•  Suppose we want to select only the student whose name is Krish
SELECT * FROM Student WHERE name='Krish';
id name age address income
103 Krish 17 Dwarika 13000
•  Suppose we want to select only the student whose income is
greater than 14000
SELECT * FROM Student WHERE income>14000;
id name age address income
102 Sita 28 Janakpur 15000
104 Buddha 22 Lumbini 16000
105 Radha 26 Gokul 18000
•  Suppose we want to select only the student who are young (being
young defined as having age less or equal to 25)
SELECT * FROM Student WHERE age<=25;
id name age address income
101 Ram 25 Ayodhya 10000
104 Buddha 22 Lumbini 16000

Prabin Babu Dhakal, CDPA, TU

AND & OR operator


•  AND and OR operators are used with WHERE clause to make more precise
condi<ons for fetching data from database by combining more than one
condi<on together.
•  AND operator
–  Final condi<on will be true if all condi<ons joined by AND operator is true
•  Retrieve records where salary is less than 10000 and age greater than 25.
–  SELECT * FROM Student WHERE salary < 10000 AND age > 25
•  OR operator
–  OR operator is also used to combine mul<ple condi<ons with Where clause.
The only difference between AND and OR is their behavior. When we use AND
to combine two or more than two condi<ons, records sa<sfying all the
condi<on will be in the result. But in case of OR, at least one condi<on from
the condi<ons specified must be sa<sfied by any record to be in the result.
•  Example of OR
–  Consider the following Emp table
–  SELECT * FROM Emp WHERE salary > 10000 OR age > 25
–  The above query will return records where either salary is greater than 10000
or age greater than 25.
Prabin Babu Dhakal, CDPA, TU

LIMIT, OFFSET
•  It controls the maximum number of records to retrieve. At most,
the number of records specified by number_rows will be returned
in the result set. The first row returned by LIMIT will be determined
by offset_value.
•  Syntax
–  SELECT * FROM table_name
LIMIT number_rows
OFFSET offset_value;
•  Example from the Sales table
•  oid order_name previous_balance customer
•  11 ord1 2000 Shyam
•  12 ord2 1000 Ram
•  13 ord3 2000 Ram
•  14 ord4 1000 Radha
•  15 ord5 2000 Shyam
–  SELECT * FROM Sales LIMIT 2 OFFSET 1
•  oid order_name previous_balance customer
•  12 ord2 1000 Ram
•  13 ord3 2000 Ram
Prabin Babu Dhakal, CDPA, TU

LIKE clause
•  Like clause is used as condi<on in SQL query.
–  Like clause compares data with an expression using wildcard operators.
–  It is used to find similar data from the table.
•  Wildcard operators: There are two wildcard operators that are used in like clause.
–  Percent sign % : represents zero, one or more than one character.
–  Underscore sign _ : represents only one character.
•  Examples
–  Suppose We want to list all records where name starts with character 'R'.
–  SELECT * FROM Student WHERE name like 'R%';
id name age address income
101 Ram 25 Ayodhya 10000
105  Radha 26 Gokul 18000
–  We want to retrieve all records from Student table where name contains 'd' as third character.
–  SELECT * FROM Student WHERE name like '_ _d%';
id name age address income
104 Buddha 22 Lumbini 16000
105  Radha 26 Gokul 18000
–  We want to select all records from Student table where address contains 'i' character.
–  SELECT * FROM Student WHERE address like '%i%';
id name age address income
103 Krish 27 Dwarika 13000
104 Buddha 22 Lumbini 16000
Prabin Babu Dhakal, CDPA, TU

ORDER BY Clause
•  ORDER BY clause is used with Select
statement for arranging retrieved data in
sorted order.
–  By default sorts data in ascending order or use
ASC keyword.
–  To sort data in descending order DESC keyword is
used
•  Syntax of Order By
–  SELECT column-list
FROM table-name
ORDER BY asc|desc;
Prabin Babu Dhakal, CDPA, TU

ORDER BY example
•  Suppose we want result in ascending order of the salary.
SELECT * FROM Student ORDER BY salary;
id name age address income
101 Ram 25 Ayodhya 10000
103 Krish 27 Dwarika 13000
102 Sita 28 Janakpur 15000
104 Buddha 22 Lumbini 16000
105 Radha 26 Gokul 18000
•  Return result in descending order of the salary.
SELECT * FROM Student ORDER BY name DESC;
id name age address income
102 Sita 28 Janakpur 15000
101 Ram 25 Ayodhya 10000
105 Radha 26 Gokul 18000
103 Krish 27 Dwarika 13000
104 Buddha 22 Lumbini 16000
Prabin Babu Dhakal, CDPA, TU

GROUP BY Clause
•  GROUP BY clause is used to group the results of a SELECT query based on one or more columns. It
is also used with SQL func<ons to group the result from one or more tables.
•  Syntax for using Group by in a statement.
–  SELECT column_name, func<on(column_name)
FROM table_name
WHERE condi<on
GROUP BY column_name
•  Example of Group by in a Statement: Consider the following employee table.
•  eid name age salary
•  401 Anu 22 9000
•  402 Shan< 29 8000
•  403 Rohan 34 6000
•  404 ScoS 44 9000
•  405 Tiger 35 8000
–  Here we want to find name and age of employees grouped by their salaries
–  SELECT name, age FROM Employee GROUP BY salary
–  Result will be,
•  name age
•  Rohan 34
•  shan< 29
•  anu 22
•  Example of Group by in a Statement with WHERE clause
–  select name, salary from Emp where age > 25 group by salary Result will be.
•  name salary
•  Rohan 6000
•  Shan< 8000
•  ScoS 9000
•  Group By clause will always come at the end, just like the Order by clause.
Prabin Babu Dhakal, CDPA, TU

HAVING Clause
• 
HAVING clause is used with SQL Queries to give more precise condi<on for a
statement. It is used to men<on condi<on in Group based SQL func<ons, just like
WHERE clause. We can put condi<ons having func<ons in having clause
•  Syntax for having will be,
–  SELECT column_name, func<on(column_name)
FROM table_name
WHERE condi<on
GROUP BY column_name
HAVING func<on(column_name) condi<on
•  Example of HAVING Statement: Consider the following Sales table.
•  oid order_name previous_balance customer
•  11 ord1 2000 Shyam
•  12 ord2 1000 Ram
•  13 ord3 2000 Ram
•  14 ord4 1000 Radha
•  15 ord5 2000 Shyam
•  Suppose we want to find the customer whose previous_balance sum is more than
3000.
•  We will use the below SQL query,
•  SELECT * FROM Sales GROUP BY customer HAVING sum(previous_balance) > 3000
Result will be,
•  oid order_name previous_balance customer
•  11 ord1 2000 Shyam
Prabin Babu Dhakal, CDPA, TU

DML
•  Data Manipula<on Language (DML)
statements are used for managing data in
database. DML commands are not auto-
commiSed. It means changes made by DML
command are not permanent to database, it
can be rolled back.
•  Insert
•  Update
•  Delete
Prabin Babu Dhakal, CDPA, TU

INSERT INTO
•  Insert command is used to insert data into a table. Following is its general syntax,
–  INSERT INTO table-name (column1, column2,…)
VALUES (data1,data2,..)
•  The list of column is op<onal unless you want to insert subset of fields
•  Consider a table Student with following fields.
•  S_id S_Name age
–  INSERT into Student values(101,'Ram',15);
•  S_id S_Name age
•  101 Ram 15
•  Insert NULL value to a column: Both the statements below will insert NULL value
into age column of the Student table.
–  INSERT INTO Student (id, name) VALUES (102,'Hari');
–  INSERT INTO Student VALUES (102,'Hari',null);
•  S_id S_Name age
•  101 Ram 15
•  102 Hari
•  Insert Default value to a column: Both will insert default value into the age column. If the age column
has default value of 14, it will insert 14; otherwise it will insert NULL
–  INSERT INTO Student VALUES (103,'Sita',default);
–  INSERT INTO Student VALUES (103,'Sita');
•  S_id S_Name age
•  101 Ram 15
•  102 Hari
•  103 Sita 14
Prabin Babu Dhakal, CDPA, TU

UPDATE
•  Update command is used to update a row of a table. Following is its
general syntax,
–  UPDATE table-name SET column-name = value WHERE condiBon;
•  Lets see an example,
–  update Student set age=18 where s_id=102;
•  S_id S_Name age
•  101 Ram 15
•  102 Hari 18
•  103 Sita 14
•  Example to Update mul)ple columns
–  UPDATE Student SET s_name='Radha', age=16 WHERE s_id=103;
–  The above command will update two columns of a record.
•  S_id S_Name age
•  101 Ram 15
•  102 Hari 18
•  103 Radha 16
Prabin Babu Dhakal, CDPA, TU

DELETE
•  Delete command is used to delete data from a table. Delete
command can also be used with condi<on to delete a par<cular
row. Following is its general syntax,
–  DELETE FROM table-name WHERE condiBon;
•  Example to Delete all Records from a Table
–  DELETE from Student;
–  The above command will delete all the records from Student table.
•  Example to Delete a par)cular Record from a Table
–  Consider the following Student table
•  S_id S_Name age
•  101 Ram 15
•  102 Hari 18
•  103 Radha 16
–  DELETE FROM Student WHERE s_id=102;
•  S_id S_Name age
•  101 Ram 15
•  103 Radha 16
•  WARNING: Always use WHERE clause with DELETE
Prabin Babu Dhakal, CDPA, TU

CRUD opera<on
•  You oqen hear about CRUD opera<on while
working with database and soqware
•  C: Create (Not to be confused with create table)
–  INSERT INTO … VALUES … used for Create opera<on
•  R: Read
–  SELECT… FROM … used for read opera<on
•  U: Update
–  UPDATE … SET … used for upda<ng database
•  D: Delete
–  DELETE FROM … used for dele<ng rows from db
Prabin Babu Dhakal, CDPA, TU

DDL
•  Data Defini<on Language
–  Create
–  Alter
–  Truncate
–  Drop
–  Rename
Prabin Babu Dhakal, CDPA, TU

CREATE
•  Create is a DDL command used to create a table or a database.
•  Crea<ng a Database
–  CREATE DATABASE database-name;
•  Example
–  CREATE DATABASE school;
•  Crea<ng a Table
–  CREATE command is also used to create a table. We can specify names and datat-ypes of various
columns along. Following is the Syntax,
–  CREATE TABLE table-name {
column-name1 datatype1,
column-name2 datatype2,
column-name3 datatype3,
column-name4 datatype4 };
–  CREATE TABLE command will tell the database system to create a new table with given table name and
column informa<on.
•  Example
–  CREATE TABLE Student(
id int,
name varchar,
age int );
–  The above command will create a new table Student in database system with 3 columns, namely id,
name and age.
Prabin Babu Dhakal, CDPA, TU

ALTER
•  ALTER command is used for changing table structures. There are various uses of alter
command, such as,
–  to add/rename/remove a column in exis<ng table
–  to change datatype of any column or to modify its size.
–  alter is also used to drop a column.
–  You can also add/modify column with constraints.
•  Add Column to exis)ng Table
–  alter table table-name add(column-name datatype);
–  e.g. alter table Student add(address char);
•  Add Mul)ple Column to exis)ng Table
–  alter table table-name add(column-name1 datatype1, column-name2 datatype2, …);
–  e.g. alter table Student add(father-name varchar(60), mother-name varchar(60), dob date);
•  Add column with Default Value
–  alter table table-name add(column-name1 datatype1 default data);
–  e.g. alter table Student add(dob date default '1-Jan-99');
•  Modify an exis)ng Column
–  alter table table-name modify(column-name datatype);
–  e.g. alter table Student modify(address varchar(30));
•  Drop a Column
–  alter table table-name drop(column-name);
–  e.g. alter table Student drop(address);
Prabin Babu Dhakal, CDPA, TU

Truncate, Drop or Rename a Table


•  truncate command
–  truncate command removes all records from a table. But this command will not destroy the table's
structure. When we apply truncate command on a table its Primary key is ini<alized.
–  truncate table table-name;
–  truncate table Student; The above query will delete all the records of Student table.
–  truncate command is different from delete command. delete command will delete all the rows from a
table whereas truncate command re-ini<alizes a table(like a newly created table).
–  For eg. If you have a table with 10 rows and an auto_increment primary key, if you use delete
command to delete all the rows, it will delete all the rows, but will not ini<alize the primary key, hence
if you will insert any row aqer using delete command, the auto_increment primary key will start from
11. But in case of truncate command, primary key is re-ini<alized.
•  drop command
–  drop query completely removes a table from database. This command will also destroy the table
structure. Following is its Syntax,
–  drop table table-name
–  e.g. drop table Student; The above query will delete the Student table completely. It can also be used
on Databases. For Example, to drop a database,
–  drop database Test; The above query will drop a database named Test from the system.
•  rename query
–  rename command is used to rename a table. Following is its Syntax,
–  rename table old-table-name to new-table-name.
–  rename table Student to Student-record; The above query will rename Student table to Student-record
Prabin Babu Dhakal, CDPA, TU

TCL Commands
•  Transac<on Control Language(TCL) commands
are used to manage transac<ons in database.
These are used to manage the changes made
by DML statements. It also allows statements
to be grouped together into logical
transac<ons.
•  Commit command
•  Rollback command
•  Savepoint command
Prabin Babu Dhakal, CDPA, TU

Commit, Rollback and Savepoint


•  Commit command
–  Commit command is used to permanently save any transac<on into
database.
–  Following is Commit command's syntax,
–  commit;
•  Rollback command
–  This command restores the database to last commiSed state. It is also
use with savepoint command to jump to a savepoint in a transac<on.
–  Following is Rollback command's syntax,
–  rollback to savepoint-name;
•  Savepoint command
–  savepoint command is used to temporarily save a transac<on so that
you can rollback to that point whenever necessary.
–  Following is savepoint command's syntax,
–  savepoint savepoint-name;
Prabin Babu Dhakal, CDPA, TU

Example of Savepoint and Rollback


•  Following is the class table, •  Now rollback to savepoint B
•  ID NAME –  rollback to B;
•  1 Ram –  SELECT * from class;
•  2 Narayan
–  The resultant table will look like
•  4 Gita
•  ID NAME
•  Lets use some SQL queries on the above table •  1 Ram
and see the results. •  2 Narayan
–  INSERT into class values(5, 'Rahul'); •  4 Gita
–  commit; •  5 Sita
•  6 Radha
–  UPDATE class set name='Sita' where id='5';
–  savepoint A; •  Now rollback to savepoint A
–  INSERT into class values(6,'Radha'); –  rollback to A;
–  savepoint B; –  SELECT * from class;
–  INSERT into class values(7,'Bhairav'); –  The result table will look like
–  savepoint C; •  ID NAME
•  1 Ram
–  SELECT * from class; •  2 Narayan
•  The resultant table will look like, •  4 Gita
•  ID NAME •  5 Sita
•  1 Ram
•  2 Narayan
•  4 Gita
•  5 Sita
•  6 Radha
•  7 Bhairav
Prabin Babu Dhakal, CDPA, TU

DCL Commands
•  Data Control Language(DCL) is used to control privilege in Database. To perform
any opera<on in the database, such as for crea<ng tables, sequences or views we
need privileges.
•  Privileges are of two types,
–  System : crea<ng session, table etc are all types of system privilege.
–  Object : any command or query to work on tables comes under object privilege.
•  DCL defines two commands,
–  Grant : Gives user access privileges to database.
–  Revoke : Take back permissions from user.
•  Examples
–  Allow a User to create Session: GRANT create session TO username;
–  Allow a User to create Table: GRANT create table TO username;
–  Provide User with some Space on Tablespace to store Table: ALTER user username
quota unlimited ON system;
–  Grant all privilege to a User: GRANT sysdba TO username;
–  Grant permission to Create any Table: GRANT create any table TO username;
–  Grant permission to Drop any Table: GRANT drop any table TO username;
–  take back Permissions: REVOKE create table FROM username;

Вам также может понравиться