Sei sulla pagina 1di 59

Advanced

SQL

Constraints, Joins, Views, Sub


queries, Set Opera;on,
Administra;on
Advanced SQL
•  Alias
•  Constrain
•  Join
•  Set
•  View
•  Func;ons
•  Sequence
•  Sub-query
SQL Alias
•  Alias is used to give an alias •  Example: Consider the following two tables,
name to a table or a column. –  The class table,
This is quite useful in case of •  ID Name
large or complex queries. Alias is •  1 Bishnu
mainly used for giving a short •  2 Pragya
alias name for a column or a •  3 Puja
•  4 Shyam
table with complex names.
•  5 Raisa
•  Syntax of Alias for table names, –  The class_info table,
SELECT column-name as •  ID Address
colum_alias from table-name •  1 Gorkha
as table_alias •  2 Sunsari
•  Following is an Example using •  3 Ilam
Alias, •  7 Kathmandu
SELECT * from •  8 Janakpur
Employee_detail as ed; •  Query to fetch data from both the tables using
•  Alias syntax for columns will be SQL Alias,
like, –  SELECT C.id, C.Name, Ci.Address from
SELECT column-name as alias- Class as C, Class_info as Ci where
name from table-name C.id=Ci.id;
•  ID Name Address
•  Example using alias for columns, •  1 Bishnu Gorkha
SELECT customer_id as cid •  2 Pragya Sunsari
from Emp; •  3 Puja Ilam
SQL Constraints
•  SQl Constraints are rules used to limit the type of data that can go
into a table, to maintain the accuracy and integrity of the data
inside table.
•  Constraints can be divided into following two types,
–  Column level constraints : limits only column data
–  Table level constraints : limits whole table data
–  Column wide constraint can only be defined inline (same line) others
can be defined inline or out of line
•  Constraints are used to make sure that the integrity of data is
maintained in the database. Following are the most used
constraints that can be applied to a table.
–  NOT NULL
–  UNIQUE
–  PRIMARY KEY
–  FOREIGN KEY
–  CHECK
–  DEFAULT
NOT NULL Constraints
•  NOT NULL Constraint
–  NOT NULL constraint restricts a column from having a
NULL value. Once NOT NULL constraint is applied to a
column, you cannot pass a null value to that column.
It enforces a column to contain a proper value. One
important point to note about NOT NULL constraint is
that it cannot be defined at table level.
•  Example using NOT NULL constraint
CREATE table Student(
id int NOT NULL,
Name varchar(60),
Age int);
–  The above query will declare that the id field of
Student table will not take NULL value.
UNIQUE Constraint
•  UNIQUE Constraint
–  UNIQUE constraint ensures that a field or column will only have
unique values. A UNIQUE constraint field will not have duplicate data.
UNIQUE constraint can be applied at column level or table level.
•  Example using UNIQUE constraint when creaDng a Table (Table
Level)
–  CREATE table Student(
•  id int NOT NULL UNIQUE,
•  Name varchar(60),
•  Age int);
–  The above query will declare that the id field of Student table will only
have unique values and wont take NULL value.
•  Example using UNIQUE constraint aGer Table is created (Column
Level)
–  ALTER table Student add UNIQUE(id);
–  The above query specifies that id field of Student table will only have
unique value.
PRIMARY KEY Constraint
•  Primary Key Constraint
–  Primary key constraint uniquely iden;fies each record in a database. A
Primary Key must contain unique value and it must not contain null
value. Usually Primary Key is used to index the data inside the table.
•  Example using PRIMARY KEY constraint at Table Level
–  CREATE table Student (
•  s_id int PRIMARY KEY,
•  name varchar(60) NOT NULL,
•  age int);
–  The above command will creates a PRIMARY KEY on the s_id.
•  Example using PRIMARY KEY constraint at Column Level
–  ALTER table Student add PRIMARY KEY (s_id);
–  The above command will create a PRIMARY KEY on the s_id.
–  create table student(
•  s_id int,
•  name varchar(50),
•  age int,
•  constraint st_pk primary key (s_id) )
FOREIGN KEY Constraints
•  Foreign Key Constraint
–  Used to relate two tables
–  Also used to restrict ac;ons that would destroy links between tables.
•  Example using FOREIGN KEY constraint at Table Level
CREATE table Order_Detail(
order_id int PRIMARY KEY,
order_name varchar(60) NOT NULL,
c_id int FOREIGN KEY REFERENCES Customer_Detail(c_id));
•  Example using FOREIGN KEY constraint at Column Level
ALTER table Order_Detail add FOREIGN KEY (c_id)
REFERENCES Customer_Detail (c_id);
create table student(
id int primary key,
name varchar (50),
course int,
constraint st_fk foreign key() references course(id)
);
Foreign Key example
•  Customer_Detail Table
–  c_id c_Name address
–  101 Ram Ayodhya
–  102 Om Himalaya
–  103 Rawan Lanka
•  Order_Detail Table
–  o_id o_name c_id
–  10 teapot11 101
–  11 biscuit12 101
–  12 biscuit13 103
•  In Customer_Detail table, c_id is the primary key which is set as
foreign key in Order_Detail table.
•  The value that is entered in c_id which is set as foreign key in
Order_Detail table must be present in Customer_Detail table where it
is set as primary key.
•  This prevents invalid data to be inserted into c_id column of
Order_Detail table.
FOREIGN KEY examples
•  Example using FOREIGN KEY –  Customer_Detail Table
•  c_id c_Name address
CREATE table Order_Detail( •  101 Ram Ayodhya
order_id int PRIMARY KEY, •  102 Om Himalaya
order_name varchar(60) NOT NULL, •  103 Rawan Lanka
c_id int , –  Order_Detail Table
CONSTRAINT fk_detail •  o_id o_name c_id
FOREIGN KEY (department_id) •  10 teapot11 101
REFERENCES customer_detail (c_id) •  11 biscuit12 101
•  12 biscuit13 103
);
–  In Customer_Detail table, c_id is the
primary key which is set as foreign
CREATE table Order_Detail( key in Order_Detail table.
order_id int PRIMARY KEY, –  The value that is entered in c_id
which is set as foreign key in
order_name varchar(60) NOT NULL, Order_Detail table must be present
c_id int , in Customer_Detail table where it is
CONSTRAINT fk_detail set as primary key.
REFERENCES customer_detail (c_id) –  This prevents invalid data to be
); inserted into c_id column of
Order_Detail table.
Foreign Key Behavior on delete
•  Behavior of Foreign Key Column on Delete
–  There are two ways to maintain the integrity of data in Child table,
when a par;cular record is deleted in main table.
–  When two tables are connected with Foreign key, and certain data in
the main table is deleted, for which record exit in child table too, then
we must have some mechanism to save the integrity of data in child
table.
•  On Delete Cascade
–  This will remove the record from child table, if that value of foreign
key is deleted from the main table.
•  On Delete Null
–  This will set all the values in that record of child table as NULL, for
which the value of foreign key is deleted from the main table.
•  If we don't use any of the above, then we cannot delete data from
the main table for which data in child table exists. We will get an
error if we try to do so.
–  ERROR : Record in child table exist
CHECK Constraint
•  CHECK Constraint
–  CHECK constraint is used to restrict the value of a column
between a range. It performs check on the values, before
storing them into the database. Its like condi;on checking
before saving data into a column.
•  Example using CHECK constraint at Table Level
–  CREATE TABLE student(
s_id int CHECK (s_id > 0),
name varchar(60) NOT NULL,
age int);
–  The above query will restrict the s_id value to be greater
than zero.
•  Example using CHECK constraint at Column Level
–  ALTER table Student add CHECK (s_id > 0);
Check constraint example
•  CREATE TABLE divisions (
div_no INT CONSTRAINT check_divno CHECK (div_no BETWEEN
10 AND 99),
div_name VARCHAR(9) CONSTRAINT check_divname CHECK
(div_name = UPPER(div_name)) DISABLE,
office VARCHAR(10) CONSTRAINT check_office CHECK (office
IN ('DALLAS','BOSTON', 'PARIS','TOKYO')) DISABLE
);
•  check_divno ensures that no division numbers are less than 10 or
greater than 99.
•  check_divname ensures that all division names are in uppercase.
•  check_office restricts office loca;ons to Dallas, Boston, Paris, or
Tokyo.
•  In column that contains the DISABLE clause, it only defines the
constraints and does not enable them.
Sub-query
•  In SQL, one query can be given as input to
another query known as sub-query
–  The sub-query must be enclosed in brackets.
–  The sub-query can be given alias for ease of reference
•  Syntax
–  SELECT fieldlist from (SELECT fieldlist from table1)
•  Example
–  SELECT avg(income)
FROM
(SELECT * from salary where gender = 'F')
EXISTS
•  The EXISTS operator is used to test for the existence of any
record in a subquery.
•  The EXISTS operator returns true if the subquery returns
one or more records.
•  E.g. SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE
condition);
•  We can replace EXISTS with NOT EXISTS to supply nega;ve
condi;on
•  As soon as one one match is found, statement is true and it
can stop, so it will be much faster than IN if subquery
returns very large result set, but slower if it returns smaller
set
IN operator
•  The IN operator allows us to specify mul;ple values in a
WHERE clause.
•  The IN operator is a shorthand for mul;ple OR condi;ons
•  E.g. SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
•  SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
•  E.g. Select name FROM employees WHERE category
IN ('Manager', 'Supervisor');
•  We can also include NOT in front of IN to supply nega;ve list
•  In is used to compare one value to several other values
BETWEEN
•  The BETWEEN operator selects values within a
given range. The values can be numbers, text, or
dates. It is inclusive: begin and end values are
included.
•  SELECT column(s) FROM table_name
WHERE column BETWEEN value1 AND
value2;
•  e.g. Select name FROM employee WHERE
salary BETWEEN 10000 AND 20000;
SQL JOIN
•  SQL Join is used to fetch data from two or more tables,
which is joined to appear as single set of data.
•  SQL Join is used for combining column from two or
more tables by using values common to both tables.
•  Join Keyword is used in SQL queries for joining two or
more tables.
•  Minimum required condi;on for joining table, is (n-1)
where n, is number of tables.
•  A table can also join to itself known as, Self Join.
•  Types of Join
–  Inner
–  Outer
–  Cross
–  Self, theta, natural, equi
Joins in Rela;onal Algebra

•  ⋈
Natural Join: R1 R2
•  Theta Join: R1 R2
•  Equi Join: When the theta condi;on is equal (=)
•  Lek Outer Join: R L
•  Right outer Join: R L
•  Full Outer Join: R L
•  Cross Join: R1 x R2
•  Semi Join: R1 R2
•  Self Join: R1 R1
Different types of Joins
•  INNER JOIN
•  OUTER JOIN
–  LEFT OUTER JOIN or LEFT JOIN
–  RIGHT OUTER JOIN or RIGHT JOIN
–  FULL OUTER JOIN or FULL JOIN
•  NATURAL JOIN
•  CROSS JOIN
•  SELF JOIN
SQL Joins
Cross JOIN or Cartesian Product
•  This type of JOIN returns the –  The class_info table,
cartesian product of rows from •  ID Address
the tables in Join. It will return a •  1 Morang
•  2 Gorkha
table which consists of records •  3 Ilam
which combines each row from
the first table with each row of •  Cross JOIN query will be,
the second table. –  SELECT * from class,
CROSS JOIN class_info;
•  Cross JOIN Syntax is,
•  SELECT column-name-list –  SELECT * from class ,
from table-name1 CROSS class_info;
JOIN table-name2; •  The result table will look like,
•  ID NAME ID Address
•  The tables can be •  1 Bisnu 1 Morang
separated by comma also. •  2 Raisa 1 Morang
•  Example of Cross JOIN •  4 Puja 1 Morang
–  The class table, •  1 Bisnu 2 Gorkha
•  ID NAME •  2 Raisa 2 Gorkha
•  4 Puja 2 Gorkha
•  1 Bisnu
•  2 Raisa •  1 Bisnu 3 Ilam
•  4 Puja •  2 Raisa 3 Ilam
•  4 Puja 3 Ilam
INNER Join – THETA/EQUI Join
•  This is a simple JOIN in which the –  The class_info table,
result is based on matched data •  ID Address
as per the equality condi;on •  1 Gorkha
•  2 Morang
specified in the query. •  3 Nuwakot
•  Inner Join Syntax is, •  Inner JOIN query will be,
SELECT column-name-list from –  SELECT * from class INNER JOIN
table-name1 class_info ON class.id =
INNER JOIN table-name2 class_info.id;
ON table-name1.column-name =
table-name2.column-name; –  SELECT * from class, class_info
where class.id = class_info.id;
•  Example of Inner JOIN
–  The class table,
•  The result table will look like,
•  ID NAME ID Address
•  ID NAME
•  1 Bisnu 1 Gorkha
•  1 Bisnu •  2 Raisa 2 Morang
•  2 Raisa •  3 Janu 3 Nuwakot
•  3 Janu
•  4 Puja •  If the condi;on is supplied in inner join
it is called theta join. If condi;on
contains equal sign (=), it is called equi
join
Natural JOIN
•  Natural Join is a type of Inner join •  Example of Natural JOIN
which is based on column having –  The class table,
same name and same datatype •  ID NAME
present in both the tables to be •  1 Bisnu
joined. •  2 Raisa
•  3 Janu
•  We don't need to provide join •  4 Mina
condi;on. It joins two tables –  The class_info table,
automa;cally •  ID Address
•  Natural Join Syntax is, •  1 Gorkha
•  2 Morang
–  SELECT * from table-name1
•  3 Nuwakot
NATURAL JOIN table-name2;
•  In the given example, •  Natural join query will be,
–  both the tables being joined have –  SELECT * from class
ID column(same name and same NATURAL JOIN class_info;
datatype), •  The result table will look like,
–  hence the records for which value •  ID NAME Address
of ID matches in both the tables •  1 Bisnu Gorkha
will be the result of Natural Join •  2 Raisa Morang
•  3 Janu Nuwakot
Outer JOIN
•  Outer Join is based on both matched and
unmatched data. Outer Joins subdivide
further into,
–  Lek Outer Join
–  Right Outer Join
–  Full Outer Join
LeG Outer Join
•  The lek outer join returns a result –  The class_info table,
table with the matched data of two •  ID Address
tables then remaining rows of the leG •  1 Gorkha
•  2 Morang
table and null for the right table's
•  3 Nuwakot
column. •  7 Sunsari
•  Lek Outer Join syntax is, •  8 Ilam
SELECT column-name-list •  LeG Outer Join query will be,
from table-name1 –  SELECT * FROM class
LEFT OUTER JOIN table-name2 LEFT OUTER JOIN class_info
ON table-name1.column-name = ON class.id=class_info.id;
table-name2.column-name;
•  Lek outer Join Syntax for Oracle is, •  The result table will look like,
•  ID NAME ID Address
select column-name-list •  1 Bisnu 1 Gorkha
from table-name1, table-name2
on table-name1.column-name = •  2 Raisa 2 Morang
table-name2.column-name(+); •  3 Janu 3 Nuwakot
•  4 Mina null null
•  Example of Lek Outer Join with the •  5 Puja null null
class table,
•  ID NAME
•  1 Bisnu
•  2 Raisa
•  3 Janu
•  4 Mina
•  5 Puja
Right Outer Join
•  The right outer join returns a result –  The class_info table,
table with the matched data of two •  ID Address
tables then remaining rows of the •  1 Gorkha
•  2 Morang
right table and null for the leG table's
•  3 Nuwakot
columns. •  7 Sunsari
•  Right Outer Join Syntax is, •  8 Ilam
–  select column-name-list from table- •  Right Outer Join query will be,
name1 –  SELECT * FROM class
RIGHT OUTER JOIN table-name2 RIGHT OUTER JOIN class_info
ON table-name1.column-name = table- ON (class.id=class_info.id);
name2.column-name;
–  Right outer Join Syntax for Oracle is, •  The result table will look like,
–  select column-name-list from table- •  ID NAME ID Address
name1, table-name2 •  1 Bisnu 1 Gorkha
on table-name1.column-name(+) = •  2 Raisa 2 Morang
table-name2.column-name; •  3 Janu 3 Nuwakot
•  null null 7 Sunsari
•  Example of Lek Outer Join with the •  null null 8 Ilam
class table,
•  ID NAME
•  1 Bisnu
•  2 Raisa
•  3 Janu
•  4 Mina
•  5 Puja
Full Outer Join
•  The full outer join returns a result –  The class_info table,
table with the matched data of •  ID Address
two table then remaining rows of •  1 Gorkha
•  2 Morang
both leG table and then the right •  3 Nuwakot
table. •  7 Sunsari
•  Full Outer Join Syntax is, •  8 Ilam
–  select column-name-list from •  Full Outer Join query will be like,
table-name1 –  SELECT * FROM class
FULL OUTER JOIN table-name2 FULL OUTER JOIN class_info
ON table-name1.column-name = ON (class.id=class_info.id);
table-name2.column-name;
•  The result table will look like,
•  Example of Lek Outer Join with •  ID NAME ID Address
the class table, •  1 Bisnu 1 Gorkha
•  ID NAME •  2 Raisa 2 Morang
•  1 Bisnu •  3 Janu 3 Nuwakot
•  2 Raisa •  4 Mina null null
•  3 Janu •  5 Puja null null
•  4 Mina •  null null 7 Sunsari
•  5 Puja •  null null 8 Ilam
Self Join
•  Self join is regular join in •  E.g.: table client
which a table is joined –  id name phone zone
(compared) to itself. –  1 Pragya 9853 Koshi
•  One prac;cal use for self- –  2 Mina 9833 Bagma;
joins: obtaining running –  3 Januka 9754 Bagma;
counts and running totals –  4 Raisa 9841 Koshi
in an SQL query. –  5 Bishnu 9767 Gandaki
•  To write the query, •  Match client names from same
–  select from same table zone
twice with different SELECT A.name AS n1, B.name
aliases, AS n2
–  set up the comparison, and FROM client AS A, client AS B
–  eliminate cases where a WHERE a.id <> b.id
par;cular value would be AND A.zone = b.zone
equal to itself. ORDER BY A.zone
Semi Join/an; join
•  A join where the result only contains the columns from one
of the joined tables
–  Used for reducing communica;on cost in distributed database
–  Semi-joins are wripen using EXISTS or IN.
•  An INNER JOIN returns the columns from both tables. A
LEFT SEMI JOIN only returns the records from the lek-hand
table.
•  It has following form:
–  SELECT ... FROM outer_tables WHERE expr IN/
EXISTS (SELECT ... FROM inner_tables ...)
–  E.g. SELECT name FROM table_1 as a
WHERE EXISTS( SELECT * FROM table_2 as b WHERE
(a.name=b.name))
•  If we replace EXISTS with NOT EXISTS, or IN with NOT IN,
then it is called an; join
Semi Join Example
•  SELECT * FROM Country
WHERE Continent='Europe'
AND Country.Code IN (SELECT
City.country FROM City WHERE
City.Population>1000000);
Semi join example
•  Give list of departments with at least one employee
•  Tradi;onal join:
–  SELECT d.deptno, d.dname from dept as d,
emp as e where e.deptno=d.deptno;
•  With semi join
–  SELECT d.deptno, d.dname FROM dept D where
EXISTS (SELECT 1 from Emp E WHERE
e.deptno=d.deptno);
•  If we use semi join, no department appear more than
once and once DBMS finds one department, it stops
processing other department so it might be slightly
faster. if we use tradi;onal join, we have to use dis;nct
SET opera;ons
•  SQL supports few Set opera;ons to be
performed on table data. These are used to
get meaningful results from data, under
different special condi;ons.
–  Union
–  Union All
–  Intersect
–  Minus
UNION
•  UNION is used to combine the results of
two or more Select statements. However it
will eliminate duplicate rows from its result
set. In case of union, number of columns
and datatype must be same in both the
tables.
•  Example of UNION
Om •  The First table,
Sita •  ID Name
Ram Om •  1 Ram
•  2 Om
–  The Second table,
•  ID Name
•  2 Om
•  3 Sita
•  Union SQL query will be,
–  select * from First
UNION
select * from second
•  The result table will look like,
–  ID NAME
–  1 Ram
–  2 Om
–  3 Sita
UNION ALL
•  This opera;on is similar to Union.
But it also shows the duplicate
rows.
•  Example of Union All
–  The First table,
•  ID NAME
•  1 Ram
Om Sita •  2 Om
Ram Om –  The Second table,
•  ID NAME
•  2 Om
•  3 Sita
•  Union All query will be like,
–  select * from First
UNION ALL
select * from second
•  The result table will look like,
•  ID NAME
•  1 Ram
•  2 Om
•  2 Om
•  3 Sita
INTERSECT
•  Intersect opera;on is used to combine
two SELECT statements, but it only
retuns the records which are common
from both SELECT statements. In case of
Intersect the number of columns and
datatype must be same. MySQL does not
support INTERSECT operator.
•  Example of Intersect
Om –  The First table,
Sita •  ID Name
Ram Om •  1 Ram
•  2 Om
–  The Second table,
•  ID Name
•  2 Om
•  3 Sita
•  SELECT query
–  select * from First
INTERSECT
select * from second
•  The result table will look like
•  ID NAME
•  2 Om
MINUS
•  Minus opera;on combines result of
two Select statements and return
only those result which belongs to
first set of result. MySQL does not
support INTERSECT operator. Some
implementa;on use EXCEPT
•  Example of Minus
Om –  The First table,
Sita •  ID Name
Ram Om •  1 Ram
•  2 Om
–  The Second table,
•  ID Name
•  2 Om
•  3 Sita
•  Minus query will be,
–  select * from First
MINUS /EXCEPT
select * from second
•  The result table will look like,
•  ID NAME
•  1 Ram
SQL VIEW
•  A view in SQL is a logical subset of data from
one or more tables. View is also used to
restrict data access.
•  Syntax for crea;ng a View,
–  CREATE or REPLACE
view view_name AS
SELECT column_name(s)
FROM table_name
WHERE condi3on
Example of CreaDng a View
•  Consider following Sale table,
•  oid order_name previous_balance customer address
•  11 ord1 2000 Bishnu Gorkha
•  12 ord2 1000 Raisa Morang
•  13 ord3 2000 Janu Nuwakot
•  14 ord4 1000 Puja Gorkha
•  15 ord5 2000 Subarna Gorkha
•  SQL Query to Create View
–  CREATE VIEW sale_view as
select * from Sale
where address= 'Gorkha';
•  The data fetched from select statement will be stored in another object
called sale_view. We can use create separately and replace too but using
both together works beper.
•  Displaying a View: Syntax of displaying a view is similar to fetching data from
table using Select statement.
–  SELECT * from sale_view
•  The right of viewing this view can be given to area sales manager of Gorkha.
Thus protec;ng data from other area
Force View CreaDon
•  FORCE keyword is used while crea;ng a view.
–  This keyword force to create View even if the
table does not exist.
–  Aker crea;ng a force View if we create the base
table and enter values in it, the view will be
automa;cally updated.
•  Syntax for forced View is,
–  CREATE / REPLACE force
view view_name AS
SELECT column_name(s)
FROM table_name
WHERE condi3on
Update a View
•  Update command for view is same as for
tables.
•  Syntax to Update a View is,
–  UPDATE view-name
SET field-name = value
WHERE condi;on;
•  If we update a view it also updates base table
data automa;cally.
Read-Only View
•  We can create a view with read-only op;on to restrict
access to the view.
•  Syntax to create a view with Read-Only Access
–  CREATE / REPLACE force
VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condi3on
WITH read-only
•  The above syntax will create view for read-only
purpose, we cannot Update or Insert data into read-
only view. It will throw an error.
Types of View
•  There are two types of view,
–  Simple View
•  Created from one table
•  Does not contain func;ons
•  Does not contain groups of data
–  Complex View
•  Created from one or more table
•  Contain func;ons
•  Contains groups of data
SQL FuncDons
•  SQL provides many built-in func;ons to perform
opera;ons on data. These func;ons are useful while
performing mathema;cal calcula;ons, string
concatena;ons, sub-strings etc. SQL func;ons are
divided into two categories,
•  Aggregate FuncDons: These func;ons return a single
value aker calcula;ng from a group of values. Some
frequently used Aggregate func;ons.
–  AVG(), COUNT(), SUM(), FIRST(), LAST(), MAX(), MIN()
•  Scalar FuncDons: Scalar func;ons return a single value
from an input value. Some frequently used Scalar
Func;ons.
–  UCASE(), LCASE(), MID(), ROUND()
Aggregate FuncDons
•  These func;ons return a single value aker calcula;ng from a group
of values. Following are some frequently used Aggregate func;ons.
•  AVG(): Average returns average value aker calcula;ng from values in
a numeric column.
•  COUNT(): Count returns the number of rows present in the table
either based on some condi;on or without condi;on.
•  FIRST(): First func;on returns first value of a selected column
•  LAST(): LAST return the return last value from selected column
•  MAX(): MAX func;on returns maximum value from selected column
of the table.
•  MIN(): MIN func;on returns minimum value from a selected column
of the table.
•  SUM(): SUM func;on returns total sum of a selected columns
numeric values.
COUNT()
•  Count returns the number of rows present in the table either based on
some condi;on or without condi;on.
•  Its general Syntax is,
–  SELECT COUNT(column_name) from table-name
•  Example: Consider following Emp table
•  eid name age salary
•  401 Bishnu 22 9000
•  402 Pragya 29 8000
•  403 Puja 34 6000
•  404 Saroj 44 10000
•  405 Shyam 35 8000
•  SQL query to count employees, sa;sfying specified condi;on is,
–  SELECT COUNT(name) from Emp where salary > 8000;
•  count(name)
•  2
•  Example of COUNT(disDnct)
–  SELECT COUNT(disDnct salary) from emp;
•  count(dis;nct salary)
•  4
AVG()
•  AVG: (Average) returns average value aker calcula;ng from
values in a numeric column.
•  Its general Syntax is,
–  SELECT AVG(column_name) from table_name
•  Example: Consider following Emp table
•  eid name age salary
•  401 Bishnu 22 9000
•  402 Pragya 29 8000
•  403 Puja 34 6000
•  404 Saroj 44 10000
•  405 Shyam 35 8000
•  SQL query to find average of salary will be,
–  SELECT avg(salary) from Emp;
•  Result of the above query will be,
•  avg(salary)
•  8200
SUM()
•  SUM func;on returns total sum of a selected columns numeric
values.
•  Syntax for SUM is,
–  SELECT SUM(column_name) from table-name
•  Example of SUM()
•  Consider following Emp table
•  eid name age salary
•  401 Bishnu 22 9000
•  402 Pragya 29 8000
•  403 Puja 34 6000
•  404 Saroj 44 10000
•  405 Shyam 35 8000
•  SQL query to find sum of salaries will be,
–  SELECT SUM(salary) from emp;
•  Result of above query is,
•  SUM(salary)
•  41000
FIRST(), LAST()
•  First func;on returns first value of a selected column and Last func;on
returns the last value
•  Syntax for FIRST func;on is,
–  SELECT FIRST(column_name) from table-name
–  SELECT LAST(column_name) from table-name
•  Example: Consider following Emp table
•  eid name age salary
•  401 Bishnu 22 9000
•  402 Pragya 29 8000
•  403 Puja 34 6000
•  404 Saroj 44 10000
•  405 Shyam 35 8000
•  SQL query and result
–  SELECT FIRST(salary) from Emp;
•  first(salary)
•  9000
–  SELECT LAST(salary) from EMP;
•  last(salary)
•  8000
MAX(), MIN()
•  MAX func;on returns maximum and MIN func;on returns minimum value
from selected column of the table.
•  Syntax
–  SELECT MAX(column_name) from table-name
–  SELECT MIN(column_name) from table-name
•  Example: Consider following Emp table
•  eid name age salary
•  401 Bishnu 22 9000
•  402 Pragya 29 8000
•  403 Puja 34 6000
•  404 Saroj 44 10000
•  405 Shyam 35 8000
•  SQL query to find Maximum and Minimum salary is,
–  SELECT MAX(salary) from emp;
•  MAX(salary)
•  10000
–  SELECT MAX(salary) from emp;
•  MIN(salary)
•  6000
Scalar FuncDons
•  Scalar func;ons return a single value from an
input value. Following are some frequently used
Scalar Func;ons.
–  UCASE(): UCASE func;on is used to convert value of
string column to Uppercase character.
–  LCASE(): LCASE func;on is used to convert value of
string column to Lowercase character.
–  MID(): MID func;on is used to extract substrings from
column values of string type in a table.
–  ROUND(): ROUND func;on is used to round a numeric
field to number of nearest integer. It is used on
Decimal point values.
UCASE(), LCASE()
•  UCASE func;on is used to •  SQL query
convert value of string column –  SELECT UCASE(name) from emp;
to Uppercase character. •  UCASE(name)
•  BISHNU
•  Syntax
•  PRAGYA
–  SELECT UCASE(column_name) •  PUJA
from table-name •  SAROJ
–  SELECT LCASE(column_name) •  SHYAM
from table-name –  SELECT LCASE(name) from emp;
•  Example: Consider following •  LCASE(name)
Emp table •  bishnu
•  eid name age salary •  pragya
•  401 Bishnu 22 9000 •  puja
•  402 Pragya 29 8000 •  saroj
•  403 Puja 34 6000 •  shyam
•  404 Saroj 44 10000
•  405 Shyam 35 8000
MID()
•  MID func;on is used to •  SQL query will be,
extract substrings from –  select MID(name,2,2) from emp;
column values of string type •  MID(name,2,2)
in a table. •  is
•  ra
•  Syntax for MID func;on is, •  uj
–  SELECT MID(column_name, •  ar
start, length) from table-name •  hy
•  Example: Consider following
Emp table
•  eid name age salary
•  401 Bishnu 22 9000
•  402 Pragya 29 8000
•  403 Puja 34 6000
•  404 Saroj 44 10000
•  405 Shyam 35 8000
ROUND()
•  ROUND func;on is used to round a numeric field to number of nearest
integer. It is used on Decimal point values. Syntax of Round func;on is,
–  SELECT ROUND(column_name, decimals) from table-name
•  Example of ROUND(): Consider following Emp table
•  eid name age salary
•  401 anu 22 9000.67
•  402 shane 29 8000.98
•  403 rohan 34 6000.45
•  404 scop 44 10000
•  405 Tiger 35 8000.01
•  SQL query is,
–  SELECT ROUND(salary) from emp;
•  ROUND(salary)
•  9001
•  8001
•  6000
•  10000
•  8000
SQL Sequence
•  Sequence is a feature supported by some •  Example to create Sequence
database systems to produce unique •  The sequence query is following
values on demand. Some DBMS like –  CREATE Sequence seq_1
MySQL supports AUTO_INCREMENT in start with 1
place of Sequence. AUTO_INCREMENT is increment by 1
applied on columns, it automa;cally maxvalue 999
increments the column value by 1 each cycle ;
;me a new record is entered into the •  Example to use Sequence
table. Sequence is also some what similar –  The class table,
to AUTO_INCREMENT but its has some •  ID NAME
extra features. •  1 abhi
•  2 adam
•  CreaDng Sequence •  4 alex
–  CREATE Sequence sequence-name
start with ini3al-value •  The sql query will be,
increment by increment-value –  INSERT into class
maxvalue maximum-value value(seq_1.nextval,'anu');
cycle|nocycle •  ID NAME
–  Start, increment, maxvalue carry similar •  1 abhi
meaning •  2 adam
–  Cycle specifies that if the maximum value •  4 alex
exceeds, sequence will restart its cycle from •  1 anu
the begining. •  Once you use nextval the sequence will
–  No cycle specifies that if sequence exceeds increment even if you don't Insert any
maxvalue an error will be thrown. record into the table.
Sequence and auto increment
•  Auto increment is used to increment some fields
automa;cally on every insert opera;on. If
nothing is supplied for that column, the dbms
automa;cally inserts next value in that field.
•  Mysql: CREATE TABLE person(id int
AUTO_INCREMENT PRIMARY KEY, name
varchar(200))
•  SQL Server: CREATE TABLE person( id int
IDENTITY(1,1) PRIMARY KEY, name varchar(200))
Crea;ng user
•  The user must be created at first to login into database and execute
queries. CREATE USER command is used for that
•  Syntax for oracle, mysql: CREATE USER <username> IDENTIFIED BY
<password>
•  Syntax for postgresql: CREATE USER <username> WITH SYSID uid |
CREATEDB | NOCREATEDB | CREATEUSER | NOCREATEUSER | IN
GROUP groupname [, ...] | [ ENCRYPTED |
UNENCRYPTED ]PASSWORD 'password' | VALID UNTIL ';me'
•  SQL Server: CREATE USER username WITH SYSID uid | CREATEDB |
NOCREATEDB | CREATEUSER | NOCREATEUSER | IN GROUP
groupname [, ...] | [ ENCRYPTED | UNENCRYPTED ]PASSWORD
'password' | VALID UNTIL ';me'
•  Example: CREATE USER prabin IDENTIFIED BY abc=123
Changing password
•  If you want to change the password, you can do it
with following commands on specific
implementa;on of DBMS
•  oracle: ALTER USER <username> IDENTIFIED BY
<password>
•  Mysql: SET PASSWORD FOR <username> =
PASSWORD('password')
•  PostgreSQL: ALTER USER <username> WITH
PASSWORD <password>
•  SQL Server: ALTER LOGIN <loginName> WITH
PASSWORD = password
INDEX
•  Indexes are used to retrieve data from the database very
fast. The users cannot see the indexes, they are just used to
speed up searches/queries.
•  Syntax: CREATE INDEX <index_name> ON table_name
(column1, column2,…)
•  E.g. CREATE INDEX idx_firstname ON person(firstname)
•  Syntax: DROP INDEX <index_name>
•  e.g. Oracle: DROP INDEX idx_firstname
•  e.g. Mysql: ALTER TABLE person DROP INDEX idx_firstname
•  e.g. SQL Server: DROP INDEX table_name.index_name
•  e.g. Access: DROP INDEX index_name ON table_name

Potrebbero piacerti anche