BPA DBMS Chapter4 - Simple SQL
BPA DBMS Chapter4 - Simple SQL
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
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
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
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
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
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;