Académique Documents
Professionnel Documents
Culture Documents
Overview
UNIT 1 Introduction to DBMS
What is a database Characteristics of a database Relational DBMS
Basic SQL
Overview
UNIT 4 Select Statements
Select statement Where clause Like, Logical operators, In and between predicates Null, Not null, Aggregate functions Order by
UNIT 6 - Exercises
Basic SQL
UNIT 1
Introduction to Database
Basic SQL
Introduction to Database
A database is a shared collection of logically related data, designed to meet the information needs of multiple users A database stores electronic data in an organized and acceptable manner For Example A telephone book
Name Krishna Kumar S Raghuram N Priya K Phone No +919886709024 +918026654321 +919886012234 Home Office Type Mobile
Basic SQL
Basic SQL
Characteristics of DBMS
Control data redundancy Sharing of data Maintenance of integrity Support for transaction control and recovery Data independence Availability of productivity tools SQL Control over security Hardware independence
Basic SQL
Relational DBMS
RDBMS is a model in which all data is logically structured with relations Data is stored in tables It is a two dimensional table with special properties
Users Table UserId 1001 1002 Countries Table CountryId 1 2 CountryName India England Name Krishna S Michael Yardy DateOfBirth 17-DEC-1990 21-APR-1954 CountryId 1 2
Basic SQL
Relational DBMS
Rows Tuples [collection of records] Each record contains same fields Columns Attributes Domain specific Different types of data exist mainly - Character, Numeric, Date
Users Table UserId 1001 1002 Name Krishna S Michael Yardy DateOfBirth 17-DEC-1990 21-APR-1954 CountryId 1 2
Basic SQL
Basic SQL
Basic SQL
Application Programs/Queries
Stored Database
Basic SQL
End Users
Interact with the system from workstations or terminals. A given end user can access the database via one of the applications
Administrators
One who manages the database centrally Decides on the type of internal structures and relationships Ensures security of the database Controls access to data through codes and passwords Can restrict views or operations users can perform on database
Basic SQL
Primary Key
Uniquely identify a particular record
Foreign Key
Primary key in one table will be referenced in another table CountryId is the foreign key here Users and Countries table mentioned below
UserId 1001 1002 1 2
Copyright 2010 Pratian Technologies www.pratian.com
CountryId 1 2
Summary
Understand database concepts Know characteristics of a DBMS Understand Relational DBMS concepts
Basic SQL
UNIT 2
Introduction to SQL
Basic SQL
What is SQL?
SQL stands for Structured Query Language Simple, powerful and standard data access language for relational database management systems It is a specialized language for updating, deleting and requesting information from databases
Basic SQL
DQL DML
SELECT INSERT UPDATE DELETE CREATE ALTER DROP TRUNCATE GRANT REVOKE
DATA QUERY LANGUAGE Used to get data from database DATA MANIPULATION LANGUAGE Used to add or change database data DATA DEFINITION LANGUAGE Used to manipulate database structures and definitions Used to grant and revoke access rights to database objects
DDL
RIGHTS
Basic SQL
Basic SQL
DOUBLE(M,D)
DATE
DATETIME
Basic SQL
Basic SQL
Syntax
CREATE TABLE table_name ( {col_name col_datatype [[CONSTRAINT const_name][col_constraint]]} [table_constraint], ) [AS query]
Basic SQL
Basic SQL
Basic SQL
Basic SQL
Basic SQL
Basic SQL
Basic SQL
DEFAULT CLAUSE
To specify a default value for an attribute if no value is given Example:
CREATE TABLE Users ( UserId int, Name varchar(100) NOT NULL, DateOfBirth datetime NOT NULL, City varchar(100) DEFAULT BANGALORE );
Basic SQL
UNIQUE CONSTRAINT
The keyword UNIQUE specifies that no two records can have the same attribute value for a column Example:
CREATE TABLE Countries ( CountryId int, CountryName varchar(50) UNIQUE );
Basic SQL
Basic SQL
CHECK CONSTRAINT
Check constraint allows users to restrict possible attribute values for a column to admissible ones Example:
CREATE TABLE Users ( UserId int, Name varchar(100), DateOfBirth datetime CHECK (DateOfBirth <=01/23/2011) );
Basic SQL
Basic SQL
MODIFYING A TABLE
The ALTER command is used to modify and existing table Syntax:
ALTER TABLE table_name [ADD (col_name col_datatype col_constraint,..)] | [MODIFY existing_col_name new_col_datatype new_constraint] | [ADD (table_constraint)] | [DROP CONSTRAINT constraint_name] | [DROP COLUMN existing_col_name];
Basic SQL
MODIFYING A TABLE
ADD clause
The ADD clause is used to add a column or a constraint to an existing table
MODIFY clause
The MODIFY clause is used to modify existing columns of a table
DROP clause
DROP clause is used to remove columns or constraints from a table
Basic SQL
MODIFYING A TABLE
Example:
ALTER TABLE Users ADD (Location varchar2(100) DEFAULT BANGALORE) ALTER TABLE Countries MODIFY (CountryName varchar2(100), UNIQUE); ALTER TABLE Users DROP CONSTRAINT check_dateofbirth;
Basic SQL
DROP A TABLE
To remove the definition of a table from the database DROP TABLE command is used Example:
DROP TABLE Countries
Basic SQL
Summary
Understand SQL as the standard language for interacting with relational database Know the type of SQL statements Understand DDL statements to create relational tables
Basic SQL
UNIT 3
Data Manipulation
Basic SQL
DATA MANIPULATION
DML Data Manipulation Statements are used to make changes to the data stored in a table The manipulations that can be performed on a table are Add Data is inserted into table using INSERT statement Update Any modifications to table data are made using UPDATE statement Delete Table data is deleted using DELETE statement
Basic SQL
INSERT STATEMENT
INSERT statement is used to add new data into the table Syntax:
INSERT INTO table_name [(col_name1, col_name2,)] {VALUES (value1, value2, ) | query };
Example:
INSERT INTO Countries VALUES (1, America); INSERT INTO Countries (CountryId, CountryName) VALUES (2, America);
Basic SQL
INSERT STATEMENT
Insert using parameter substitution
Example: INSERT INTO Countries (CountryId, CountryName) VALUES (&CountryId, &CountryName);
Basic SQL
Basic SQL
UPDATE STATEMENT
Update statement is used when we need to modify data in a table Syntax:
UPDATE {table_name | alias} SET col_name = value | col_name = (SELECT Statement) [WHERE Condition];
Basic SQL
UPDATE STATEMENT
Update all rows
UPDATE Users SET DateOfBirth = 17-MAY-1990;
[Date format according to DBMS. Will be 05/17/1990 for SQL Server]
Basic SQL
DELETE STATEMENT
DELETE statement is used to delete rows from a table Syntax:
DELETE [FROM] {table_name | alias } [WHERE Condition];
Basic SQL
WHAT IS A TRANSACTION?
A transaction is a unit of work that may contain of one or more SQL statements A transaction is called atomic as the database modifications brought about by the SQL statements that constitute a transaction can be
Either made permanent to the database Or, undone from the database
The changes made to a table using INSERT, UPDATE or DELETE statements are not permanent till a transaction is not marked complete
Basic SQL
TRANSACTION CONTROL
During a session, a transaction begins when the first SQL command (DDL or DML) is encountered and ends when one of the following occurs
A DDL is encountered COMMIT/ROLLBACK statement is encountered Logging off from the session System failure
Basic SQL
COMMIT TRANSACTION
Committing a transaction makes permanent the changes resulting from all successful SQL statements in a transaction Syntax: COMMIT; AUTOCOMMIT option is available to execute COMMIT automatically whenever an INSERT, UPDATE or DELETE statement is executed Syntax: SET AUTOCOMMIT ON;
Basic SQL
ROLLBACK TRANSACTION
Changes made to the database without COMMIT may be abandoned using the ROLLBACK statement When a transaction is rolled back, it is as if the transaction never occurred Syntax: ROLLBACK;
Basic SQL
Summary
We know how to manipulate data in a table using DML commands Know how to save or undo changes made to table data
Basic SQL
UNIT 4
SELECT STATEMENT
Basic SQL
SELECT STATEMENT
We will be looking at the following SELECT STATEMENT
How to retrieve data from tables Column aliases Where clause Pattern matching LIKE
Basic SQL
Basic SQL
SELECT STATEMENT
Syntax:
SELECT [ALL | DISTINCT ] { * | col_name,..} FROM table_name alias [WHERE expr1] [CONNECT BY expr2 [START WITH expr3]] [GROUP BY expr4] [HAVING expr5] [UNION | INTERSECT] [ORDER BY expr | ASC | DESC];
Basic SQL
Basic SQL
WHERE CLAUSE
WHERE Clause
Where clause is used to do selective retrieval of rows Rows which meet search condition are returned WHERE <search condition>
List of Operators
= <> < > <= >= Equal to Not equal to Less than Greater than Less than equal to Greater than equal to
Basic SQL
WHERE CLAUSE
To get all rows where order date is equal to a date
SELECT * FROM OrderReg WHERE OrderDate = 20-JAN-2009;
To get all rows where order date is greater than or equal to a date
SELECT * FROM OrderReg WHERE OrderDate >= 20-JAN-2010;
Basic SQL
LIKE PREDICATE
The pattern contains a search string along with other special characters % and _ An underscore(_) in the pattern matches exactly one character A percent sign (%) in the pattern can match zero or more characters
It cannot match a NULL
Basic SQL
LIKE PREDICATE
To list all customers whose name begins with K
SELECT ShortName FROM CustomerMaster WHERE ShortName LIKE K%;
To list all customers whose name begins with K and third letter I
SELECT ShortName FROM CustomerMaster WHERE ShortName LIKE K_I%;
Basic SQL
LOGICAL OPERATOR
A logical operator combines the results of two component conditions to produce a single result based on them or invert the result of a single condition NOT Returns true if condition is false, returns false if condition is true AND Returns true if both component conditions are true, returns false if both component conditions are false OR Returns true if either component condition is true, returns false if both component conditions are false
Basic SQL
LOGICAL OPERATOR
NOT
SELECT * FROM OrderReg WHERE NOT OrderNo = 87654321;
AND
SELECT * FROM OrderReg WHERE OrderNo > 87654321 AND OrderDate >= 18-JAN-2009;
OR
SELECT * FROM OrderReg WHERE OrderType = STANDARDS OR OrderType = JOBSTANDARDS
Basic SQL
IN PREDICATE
To select rows from defined set of values
SELECT * FROM OrderReg WHERE UnqId IN (879, 2343);
Basic SQL
BETWEEN PREDICATE
To retrieve rows which meets the range of values given
SELECT * FROM OrderReg WHERE OrderDate BETWEEN 18-MAY-2007 AND 25-MAY-2007;
Basic SQL
NULL PREDICATE
NULL predicate is used to check if an attribute or a column is null. Col_name = NULL cannot be done IS NULL
SELECT * FROM OrderReg WHERE OrderDate IS NULL
IS NOT NULL
SELECT * FROM OrderReg WHERE OrderDate IS NOT NULL
Basic SQL
AGGREGATE FUNCTIONS
Produces a single value for an entire group Functions are
COUNT Produces the number of rows query has selected AVG Produces the average of all selected values of a given column MAX Produces the largest of all selected values of a given column MIN Produces the smallest of all selected values of a given column SUM Produces the arithmetic sum of all selected values of a given column
Basic SQL
GROUP BY
The GROUP BY clause is used to group selected rows and return a single row of summary information Each group of rows are based on the values of the expression(s) specified in the GROUP BY clause Grouping can be done on multiple columns
Basic SQL
GROUP BY
Example:
SELECT ItemNo, sum(Total) FROM OrderItems GROUP BY ItemNo SELECT ItemNo, sum(Total) FROM OrderItems GROUP BY ItemNo HAVING Qty > 0
Basic SQL
ORDER BY
ORDER BY clause is used to sort records The sort is done on the column in either ascending or descending order. [ASC default] Example:
SELECT * FROM CustomerMaster ORDER BY ShortName
Basic SQL
Summary
Know how to use the SELECT statement to retrieve data from a table Know the options to be used with SELECT statement for conditional data retrieval Know how to group data based on a value Know how to sort data
Basic SQL
UNIT 5
JOINS AND SUBQUERIES
Basic SQL
Basic SQL
JOINS
JOIN is a query that combines data from more than one table by means of a single statement Joining is done in SQL by specifying the tables to be joined in the FROM clause Most join queries contain WHERE conditions that compare two columns, each from a different table. Such a condition is called join condition
Basic SQL
EQUIJOIN
An equijoin is a join with a join condition containing an equality operator Is also called inner join or simple join In the equi-join the comparison we are making between two columns is that they match the same value. We can use this method to select certain fields from both tables and only the correct rows will be joined together Example To select orders with its customer information
SELECT c.ShortName, c.RegionCode, o.OrderNo, o.OrderDate, o.OrderType FROM OrderReg o, CustomerMaster c WHERE o.UnqId = c.UnqId
Basic SQL
SELF JOIN
A self join is a join of a table to itself The table appears twice in the FROM clause and is followed by table aliases, that qualify table names in the join condition The table rows are combined and the rows which satisfy the condition are returned Example would be employee manager information
SELECT e.Name as EmployeeName, m.Name as ManagerName FROM Employees e, Employees m WHERE e.EmployeeId = m.ManagerId
Basic SQL
SELF JOIN
Employees table
EmployeeId 1001 1002 Name Krishna S Raghav V Age 18 19 Gender Male Male ManagerId NULL 1001
Basic SQL
Basic SQL
Basic SQL
Basic SQL
OUTER JOIN
Note: For oracle based SQL, syntax of the outer joins would vary a bit. LEFT or RIGHT OUTER JOIN is indicated by a + symbol For Example - We need customers with or without orders. Left outer join SELECT c,ShortName, o.OrderNo FROM CustomerMaster c, OrderReg o WHERE c.UnqId (+) = o.UnqId
Basic SQL
UNIONS
UNION is used to combine the result from multiple SELECT statements into a single result set There are few conditions to be kept in mind, when we use UNION
The number of columns in each SELECT statement has to be the same The data type of the columns in the column list of the SELECT statement must be the same or at least convertible.
Syntax:
SELECT statement UNION [DISTINCT | ALL] SELECT statement UNION [DISTINCT | ALL ]
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
UNIONS
By default the UNION removes all duplicated rows from the result set If you use UNION ALL explicitly, the duplicated rows will remain in the result set For Ex:
SELECT InvoiceNo, InvoiceDate FROM Invoice WHERE InvoiceDate BETWEEN 18-MAY-2007 AND 25-MAY-2007 UNION SELECT InvoiceNo, InvoiceDate FROM Invoice WHERE InvoiceDate BETWEEN 18-JUN-2007 AND 25-JUN-2007;
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
LOWER(string)
Converts all characters of a given string to lower case SELECT LOWER(ShortName) FROM CustomerMaster
Basic SQL
LPAD(string1, n, string2)
Adds string2 before string1 as many time as required to make the string 1 length equal to n chars To right align the names of customers SELECT LPAD(ShortName, 8, ) FROM CustomerMaster
Basic SQL
RPAD(string)
Similar to LPAD. Adds to the right end of string
Basic SQL
MONTHS_BETWEEN
Returns number of months between two dates SELECT OrderNo, OrderDate, MONTHS_BETWEEN(SYSDATE, OrderDate) FROM OrderReg
ADD_MONTHS
Returns a DATE, int1 times added. Int1 can also be a negative integer SELECT OrderNo, OrderDate, ADD_MONTHS(OrderDate, 2) FROM CustomerMaster
TO_CHAR
Converts date given to a format specified
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
Basic SQL
ROUND(n, m)
Returns n rounded to m places SELECT ROUND(Total, 2) FROM OrderItems
Basic SQL
LOWER(string)
Converts all characters of a given string to lower case SELECT LOWER(ShortName) FROM CustomerMaster
REVERSE(string)
Returns the reverse of a string Select REVERSE(ABCD) Output - DCBA
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
Basic SQL
ABS(x)
Returns the absolute values Select ABS(-32) Output = 32
SQRT(x)
Returns the square root a non-negative number Select SQRT(4) Output = 2
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
GETDATE()
Returns the current date Select GETDATE() Output : 11/08/2010 08:30:00
DAY(date)
Returns day of the month, in the range 1 31 SELECT DAY(GETDATE()) Output : 8
Basic SQL
MONTH(date)
To get the month of a given date SELECT MONTH(GETDATE()) Output - 11
Note: This is only a partial list
Basic SQL
SUBQUERIES
A subquery is a SELECT statement within another statement Main advantages of subqueries are
Queries can be structured, so that it is possible to isolate each part of a statement Provide alternate ways to perform operations that would otherwise require complex joins or unions
Ex:
SELECT * FROM Table1 WHERE Column1 = (SELECT Column1 FROM Table2)
A subquery can return a scalar (a single value), a single row, a single column, or a table (one or more rows of one or more columns)
Basic SQL
SUBQUERIES
Used in either SELECT, WHERE or FROM clauses of an SQL statement In the WHERE clause subqueries can become a part of the following predicates
Comparison predicate IN predicate ANY or ALL predicate EXISTS predicate
Basic SQL
NORMAL SUBQUERIES
Does not need data from the outer query Subquery is evaluated only once Subquery generates values that are tested in the predicate of the outer query To list all orders placed for a particular customer
SELECT OrderNo, OrderDate, OrderType FROM OrderReg WHERE UnqId = (SELECT UnqId FROM CustomerMaster WHERE ShortName = PRS);
Basic SQL
CORRELATED SUBQUERY
A correlated subquery uses any data from the FROM clause of the outer query The subquery is evaluated for each row of the outer query The subquery has to result in one value of the same data type as the left-hand side To get order count for each customer
SELECT c.ShortName, c.UnqId, c.RegionCode, (Select count(*) From OrderReg o where c.UnqId = o.UnqId) as OrderCount FROM CustomerMaster c
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
Where
Basic SQL
ANY
SELECT ItemNo, Rate FROM OrderItems WHERE Rate > ANY (SELECT Rate FROM OrderItems WHERE ItemNo = 5510);
EXISTS
SELECT * FROM OrderItems r WHERE EXISTS (SELECT OItemId FROM InvoiceItems i WHERE i.OItemId = r.OItemId);
Copyright 2010 Pratian Technologies www.pratian.com
Basic SQL
Summary
Know how to formulate complex queries using the concept of subqueries Know the types of subqueries
Basic SQL
Question Time
Please try to limit the questions to the topics discussed during the session. Thank you.
Basic SQL