CH 14 SQL
CH 14 SQL
CH 14 SQL
SQL Commands
Def -
SQL is a structured query language for storing, manipulating and retrieving data in relational
databases.
SQL is the standard language for Relational Database systems like Oracle, Sybase, MySQL, etc.
History –
1970 – Dr E.F.Codd of IBM known as father of relational database described a relational model for
databases.
1974 – Structured Query Language appeared.
1978 – IBM released a product named system/R
1986 – IBM developed first prototype of relational database, and was released by Relational
software it later became Oracle.
Two standard Organization ANSI (American National Standards Institute) and the ISO (International
standards Organization) currently promote SQL.
Characteristics of SQL-
1. It is very easy to learn and use.
2. Large volumes of data can be handled easily.
3. It is a non procedural language.
4. SQL can be linked to other high level languages.
5. SQL can change system security settings.
6. All user permissions on databases or tables.
Functions of SQL -
1. Allows users to describe the data.
2. Allows users to create and drop databases and tables.
3. Allows users to access data in RDBMS.
4. Allows users to define the data in database and manipulate the data.
5. Allows users to create views, stored procedures, etc.
6. Allows embedding within other languages using SQL modules.
7. Allows users to set permissions on tables, procedures and views.
SQL Commands –
Commands are instructions used to communicate with the database to perform specific task such
as creating table, add data to table, modify, delete, etc. The commands used are CREATE,
SELECT, DELETE, DROP, etc.
Functions of DDL
1. DDL define the physical characteristics of each record.
2. DDL describes the schema and subschema.
3. DDL indicates the keys of the records.
4. DDL provides data security measures.
5. DDL provides means for associating related records or fields.
6. DDL provides for Logical and Physical data Independence.
Commands of DDL
CREATE – command creates a new table, a view of a table, etc.
ALTER – command modifies an existing database object such as a table.
DROP – command deletes an entire table.
Functions –
1. DML provides data manipulation techniques like selection, insertion, deletion, update,
replacement, retrieval, sorting and display of data or records.
2. DML facilitates use of relationship between the records.
3. DML enables the user and application program to be independent of physical data structure.
4. DML provides for independence of Programming languages.
Commands of DML
INSERT – Command to Add new records (rows) of data in a table.
UPDATE - Command to Modify the existing records (rows) in a table.
DELETE - Command to Delete the existing records (rows) in a table.
Data Types supported by SQL – SQL Server offers different categories of data types
1. Exact numeric data types – Int, numeric
2. Floating Point numeric data types – Float, Real
3. Date and Time Data types – datetime, date, time
4. Character, strings data types – char(fixed length), varchar(Variable length)
Comparison Operators
= equal to != or <> not equal to
> < >= <=
!< not less than !> not greater than
Comparison Operators example:
Assume variable a = 10 and variable b = 20, then:
Logical Operators –
ALL Used to compare a value to all values in
another value set.
AND to combine multiple conditions
ANY Used to compare a value to any applicable
value
BETWEEN used to search values within a range
EXISTS used to search for the presence of a row in
a table
IN Used to compare a value to a list of values
that have been specified
LIKE Used to compare a value to similar values
NOT Reverses the meaning of logical operator
eg. NOT BETWEEN
OR Is used to combine multiple conditions
IS NULL Is used to compare a value with a NULL
value
UNIQUE Check for uniqueness (no duplicates)
SQL Expressions –
SQL Expressions are like formulas and written in query language.
TYPES –
1. SQL – Boolean Expression – fetches the data on the basis of matching single
value.
Syntax : SELECT col1, col2 from tablename where single value matches expr;
Eg : SELECT * from Employees where age>=35;
SQL Constraints –
Constraints are the rules enforced on data columns of table. They ensure the accuracy and
reliability of data in the database.
Constraints can be Column Level or Table Level – commonly used constraints are primary key,
foreign key, Not NULL, unique constraint, etc.
DROP TABLE command – used to remove an existing table from the database.
Syntax – DROP TABLE table_name;
Eg : DROP TABLE employees;
DML commands –
INSERT command- used to add new rows of data in the table.
Syntax – INSERT INTO tablename [(col1, col2,… colN)] VALUES ( value1, value2,……..
valueN);
Here col1, col2 are the names of the columns in the table into which data is to be inserted (to
add data to all the columns in the table it is not necessary to mention the column names)
The [ ] bracket indicates that the items inside the bracket are optional.
INSERT INTO command performs
1. Creates a new row in the table.
2. Loads the values passed into the column specified
SELECT command – Statement is used to fetch the data from database table.
Query – is a request for some information from the database.
SQL uses SELECT command for data retrieval. This command can perform selection as well
as projection operations of Relational Algebra.
Examples.
Selecting all columns and all rows in a table. Command is SELECT * FROM student;
Selecting a set of columns from a table. Command is SELECT regno, name FROM student;
Removing duplicate data (DISTINCT) SELECT DISTINCT city FROM student;
Logical operators –
AND operator –allows to combine multiple conditions in a SQL statement where clause
SELECT col1,col2,…,coln FROM tablename where [condition 1] AND [condition 2];
Eg. SELECT id,name FROM employees where (salary>30000) AND (salary < 40000);
UPDATE command – used to change data or modify the existing data in a table.
Syntax – UPDATE tablename SET colname = value [WHERE condition]
Eg.
i. To change fees of all students to 30000 UPDATE student SET fees = 30000;
ii. To reduce the fees of students by 500 UPDATE student SET fees = fees - 500;
DELETE command –
used to remove row or rows from a table, where condition can be used.
Syntax –DELETE FROM tablename [where condition]
Eg. DELETE FROM student where fees >=40000;
ORDER BY –
It is used to sort the data in ascending or descending order based on one or more columns.
Syntax – SELECT columnlist FROM tablename [WHERE CONDITION(S)] [ORDERBY
colname(s)] [ASC|DESC]
Eg: SELECT * FROM student ORDER BY rno;
Eg. SELECT regno, name, marks, combi FROM student order by name;
GROUP BY –
It is used with the select statement to arrange identical data into groups.
GROUP BY clause follows the where clause in SELECT statement and precedes the ORDER
BY clause.
Syntax – SELECT columnlist FROM tablename [WHERE CONDITION(S)]
[GROUP BY colname(s)] [ORDER BY colname(s)] [ASC|DESC]
SELECT regno,name,marks,combi FROM student groupby combi orderby name
GROUP Functions –
are built in SQL functions that operate on group of rows and return a single value for the entire
group.
Functions are –
Count( ) - returns the number of rows in the table that satisfies the condition.
Eg. SELECT count(*) from employees;
Max() - returns maximum value from a column.
Eg. SELECT max(salary) from employees;
Min() - returns minimum value from a column.
Eg. SELECT min(salary) from employees;
Avg() – returns average value from a numeric column.
Eg. SELECT avg(salary) from employees;
Sum() – returns sum of a numeric column.
Eg. SELECT sum(salary) from employees;
DISTINCT – is used with SELECT to eliminate all the duplicate records and fetch only
unique records.
Syntax : SELECT Distinct colname from tablename;
Eg: SELECT Distinct name from employees;
JOINS – are used to fetch data from two or more tables based on a join condition which is
specified in the WHERE clause.
Types of JOINS
1. INNER JOIN –
Returns rows when there is a match in both tables also called EQUI JOIN.
Syntax – SELECT table1.colname, table2.colname…. FROM table1 INNER JOIN table2 ON
table1.commonfield = table2.commonfield
Eg. SELECT id, name, amount FROM customers INNER JOIN orders ON customers.id =
orders.cid
OR
SELECT id, name, amount FROM customers, orders WHERE customers.id = orders.cid
2. LEFT JOIN –
Returns all rows from the left table even if there are no matches in the right table.
3. RIGHT JOIN –
Returns all rows from the right table even if there are no matches in the left table.
4. FULL JOIN –
Returns rows when there is a match in one of the tables.
5. SELF JOIN –
It is used to join a table to itself as if the table were two tables, temporarily renaming at least
one table in the SQL statement.
6. CARTESIAN JOIN –
Returns the Cartesian product of the sets of rows from the two or more joined tables.
Syntax – SELECT table1.col1, table2.col2 …. FROM table1, table2….;
Eg. SELECT * FROM customers, orders;
In above query there are two tables customer and orders. There are 5 records in customers
and 4 records in orders. In Cartesian product each row of customers is concatenated with each
row of orders. The total number of records after Cartesian product is 20(5 X 4).
Creating views –
Views can be created from a single table, multiple table or another view.
CREATE VIEW viewname AS SELECT name,age from employees;
COMMIT command –
It is used to save changes invoked by a transaction to the database.
Syntax : COMMIT;
DCL commands –
Are used to enforce database security in a multiple user database environment.
GRANT –
This command is used to provide access or privilege on the database object to the user.
Syntax: GRANT privilege_name on object_name to User_name
Privilege_name is the access right granted to the user, it can be All, Execute, Select, etc.
Object_name can be table, view, etc.
User_name is to whom access is being granted.
Eg. Grant Select on employee to user1;
Revoke –
This Command removes user access rights or privileges to the database objects.
Syntax: REVOKE privilege_name on object_name from User_name
Eg. Revoke Select on employee from user1;
DUAL table in Oracle –
DUAL is a single row and single column dummy table provided by Oracle. This is used to
perform mathematical calculations without using a table.
Eg. SELECT 3*2 from dual;
Output – 3*2
6
Privileges and Roles
Priveleges
It defines the access rights provided to a user on a database object.
There are 2 types of Privileges
1. System Privileges –
This allows the user to create, alter or drop database objects.
2. Object Privileges –
This allows the user to execute select, insert, update, or delete data from database objects to
which the privileges apply.
Roles –
These are set of privileges grouped together. Eg. System role.
Connect – Privileges granted to this role are create table, create view, etc.
Resource – Create procedures, create trigger, etc.
DBA – All system privileges.
Date functions –
Take values that are date type as input and return values of date type, except for the
Months_between function.
Conversion Functions :
These functions help to convert a value in one form to another form. i.e a value from one
datatype to another datatype.