Vous êtes sur la page 1sur 101

Basic SQL

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com

Overview
UNIT 1 Introduction to DBMS
What is a database Characteristics of a database Relational DBMS

UNIT 2 Introduction to SQL


DDL Create, Alter, Drop, Truncate

UNIT 3 Data Manipulation Language


DML Insert, Update, Delete, Transactions Commit, Rollback

Copyright 2010 Pratian Technologies www.pratian.com

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 5 Joins and subqueries


Joins Views Sub queries SQL Functions

UNIT 6 - Exercises

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

UNIT 1
Introduction to Database

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Database Management Systems


Database Management System DBMS is a software system that allows you to manage all your data in a systematic fashion It is a program that allows users to define, create, manipulate, store, maintain, retrieve and process the data in a database in order to produce meaningful information

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Relational DBMS - Properties


Entries of column and row values have to be single valued Entries of attributes [columns] are of same kind No two rows are identical Order of rows and columns are unimportant Every column has to be uniquely defined

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Relational DBMS Database Schema


Organization of information within database for single or multiple users Store of data that describes the content and structure of physical data store It contains various information relationships, access controls etc.. like data types,

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Relational DBMS - Architecture


Users

DATABASE SYSTEM DBMS

Application Programs/Queries

Software to process queries/programs Software to access stored data

Stored Data Defn.

Stored Database

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Relational DBMS - Users


Application Programmers
Responsible for writing application programs that use the database

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Relational DBMS Data Integrity


Data integrity
Refers to wholeness and roundness of the database Achieved by using integrity constraints and domain constraints

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

Name Krishna S Michael Yardy CountryId

DateOfBirth 17-DEC-1990 21-APR-1954 CountryName India England


Basic SQL

CountryId 1 2

Summary
Understand database concepts Know characteristics of a DBMS Understand Relational DBMS concepts

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

UNIT 2
Introduction to SQL

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Standard SQL Statement Groups


Group Statements Description

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Data Types in SQL Server


Data Types
Data type CHAR(n) VARCHAR(n) TEXT or BLOB TINYINT SMALLINT INT Description To store fixed length string. Maximum length = 255 bytes To store variable length string. Maximum length = 255 bytes To store maximum length of 65535 characters. Binary Large Objects Text, images, files etc.. If signed: -128 to 127. If unsigned: 0 to 255. You can specify a width of up to 4 digits. If signed : -32768 to 32767. If unsigned : 0 to 65535. You can specify a width of up to 5 digits. If signed : -2147483648 to 2147483647. If unsigned : 0 to 4294967295. You can specify a width of up to 11 digits.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Data Types in SQL Server


Data Types
Data type FLOAT(M,D) Description You can define the display length (M) and the number of decimals (D). Decimal precision can go to 24 places for a FLOAT. You can define the display length (M) and the number of decimals (D). Decimal precision can go to 53 places for a FLOAT. A date in YYYY-MM-DD format, between 1000-0101 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30 A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00

DOUBLE(M,D)

DATE

DATETIME

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Data Types in SQL Oracle


Data type CHAR(n) VARCHAR2(n) LONG(n) NUMBER(p, s) DATE RAW(n) LONG RAW(n) Description To store fixed length string. Maximum length = 255 bytes To store variable length string. Maximum length = 4000 bytes To store variable length string. Maximum length = 2GB To store numeric data. Maximum number of significant digits = 38 To store date values. Both time and date are stored, require 8 bytes To store data in binary format such as signature, photo. Maximum size = 255 bytes Same as RAW(n). Maximum size = 2GB

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Creation of Database Objects - DDL


Table
Tables are objects which store data A table can have a maximum of 1000 columns

Syntax
CREATE TABLE table_name ( {col_name col_datatype [[CONSTRAINT const_name][col_constraint]]} [table_constraint], ) [AS query]

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Creation of Database Objects - DDL


Example
CREATE TABLE Users ( UserId int, Name varchar(100), DateOfBirth datetime ) CREATE TABLE Countries ( CountryId int, CountryName varchar(50) )

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Creation of Database Objects - DDL


Naming of tables
Name of the table must begin with a letter A-Z or a-z. It may contain numerals and the special character _ (underscore) It can be 30 characters in length It must not be a SQL reserved word

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Specifying Integrity Constraints


A database is said to be integrated if the values in the database are correct according to a set of rules Checking of consistency must be carried out to ensure data integrity The definition of a table may include the specification of integrity constraints

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Specifying Integrity Constraints


Types of Constraints
Column constraints associated with a single column Table constraints associate with more than one column

A constraint can be named If not named, will be automatically generated by DBMS

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Types of Integrity Constraints


NOT NULL UNIQUE PRIMARY KEY CHECK FOREIGN KEY

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

NOT NULL CONSTRAINT


User will not be allowed to enter null values Example:
CREATE TABLE Users ( UserId int, Name varchar(100) NOT NULL, DateOfBirth datetime NOT NULL );

Copyright 2010 Pratian Technologies www.pratian.com

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 );

Copyright 2010 Pratian Technologies www.pratian.com

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 );

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PRIMARY KEY CONSTRAINT


A primary key constraint enables a unique identification of each record in a table Example:
CREATE TABLE Users ( UserId int NOT NULL pk_emp PRIMARY KEY IDENTITY(1,1), Name varchar(50), DateOfBirth datetime, City varchar(100) );

Copyright 2010 Pratian Technologies www.pratian.com

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) );

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FOREIGN KEY CONSTRAINT


This constraint specifies a column or list of columns as a foreign key of the referencing table Referencing table is called Child table, referenced table is called Parent table Example:
CREATE TABLE Users ( UserId int, Name varchar(100), DateOfBirth datetime, CountryId int not null FOREIGN KEY Countries(CountryId) );
Copyright 2010 Pratian Technologies www.pratian.com

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];

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

DROP A TABLE
To remove the definition of a table from the database DROP TABLE command is used Example:
DROP TABLE Countries

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

UNIT 3
Data Manipulation

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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);

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

INSERT STATEMENT
Insert using parameter substitution
Example: INSERT INTO Countries (CountryId, CountryName) VALUES (&CountryId, &CountryName);

Insert using query output


INSERT INTO Countries (CountryId, CountryName) SELECT 1, Brazil

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

INSERT STATEMENT GENERAL RULES


Values should match data type of the respective columns Number of values should match the number of column names mentioned All columns declared as NOT NULL should be supplied with a value Character strings should be enclosed in quotes DATE values should be enclosed in quotes

Copyright 2010 Pratian Technologies www.pratian.com

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];

Copyright 2010 Pratian Technologies www.pratian.com

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]

Update only certain rows


UPDATE Users SET DateOfBirth = 17-MAY-1990 WHERE Name = Krishna;

Update multiple columns


UPDATE Users SET DateOfBirth = 17-MAY-1990, Name = Krishna S WHERE UserId = 1001;
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

DELETE STATEMENT
DELETE statement is used to delete rows from a table Syntax:
DELETE [FROM] {table_name | alias } [WHERE Condition];

Delete all rows from table


DELETE FROM Users

Delete particular row from table


DELETE FROM Users WHERE UserId = 1002

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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;

Copyright 2010 Pratian Technologies www.pratian.com

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;

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

UNIT 4
SELECT STATEMENT

Copyright 2010 Pratian Technologies www.pratian.com

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

SELECT STATEMENT - more options


Logical operators AND, OR, NOT IN BETWEEN IS NULL / IS NOT NULL GROUP BY / ORDER BY Note: Sample database will be created and all queries
can be executed on that database to see the result
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SALES ORDER DATABASE

Copyright 2010 Pratian Technologies www.pratian.com

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];

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

COLUMN ALIAS AND DISTINCT


Giving alias
SELECT RunningId, OrderNo, OrderDate DatePlaced FROM OrderReg;

DISTINCT To get unique values


SELECT DISTINCT ShortName FROM CustomerMaster;

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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 no is greater than a value


SELECT * FROM OrderReg WHERE OrderNo > 8750109;

To get all rows where order date is greater than or equal to a date
SELECT * FROM OrderReg WHERE OrderDate >= 20-JAN-2010;

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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%;

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

IN PREDICATE
To select rows from defined set of values
SELECT * FROM OrderReg WHERE UnqId IN (879, 2343);

Copyright 2010 Pratian Technologies www.pratian.com

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;

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

UNIT 5
JOINS AND SUBQUERIES

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

JOINS AND SUBQUERIES


We will be looking at the following What are Joins? Types of Joins
Equi join Self join Outer join [Left, Right]

Unions SQL Functions What are subqueries? Types of subqueries


Normal Correlated
Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SELF JOIN
Employees table
EmployeeId 1001 1002 Name Krishna S Raghav V Age 18 19 Gender Male Male ManagerId NULL 1001

Result of the query


EmployeeName Raghav V ManagerName Krishna S

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

LEFT OUTER JOIN


A left outer join extends the result of a simple join Returns all rows that satisfy the join conditions and those rows from left table for which no rows from the other satisfy the join condition For Example: We need customers with or without orders
SELECT c,ShortName, o.OrderNo FROM CustomerMaster c LEFT OUTER JOIN OrderReg o ON c.UnqId = o.UnqId

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

RIGHT OUTER JOIN


A right outer join extends the result of a simple join Returns all rows that satisfy the join conditions and those rows from right table for which no rows from the other satisfy the join condition For Example: We need orders with or without customer information [If any dummy customer id has been added]
SELECT o.OrderNo, c.ShortName FROM OrderReg o RIGHT OUTER JOIN CustomerMaster c ON o.UnqId = c.UnqId

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

FULL OUTER JOIN


A full outer join is union of LEFT and RIGHT outer join Returns all rows from right and left table. This includes both matching and non-matching data For Example: Customers with/without orders and orders with/without customers
SELECT o.OrderNo, c.ShortName FROM OrderReg o FULL OUTER JOIN CustomerMaster c ON o.UnqId = c.UnqId

Copyright 2010 Pratian Technologies www.pratian.com

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

Copyright 2010 Pratian Technologies www.pratian.com

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

SQL FUNCTIONS Oracle


Apart from aggregate functions there are some single row functions which can be used in queries UPPER (string)
Converts all characters in string to upper case SELECT UPPER(ShortName) FROM CustomerMaster

LOWER(string)
Converts all characters of a given string to lower case SELECT LOWER(ShortName) FROM CustomerMaster

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS Oracle


INITCAP(string)
Converts the first character of a given string to upper case and the rest to lower case SELECT INITCAP(ShortName) FROM CustomerMaster

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS Oracle


LTRIM(string, CHAR set)
Removes chars from beginning of a string as long as the character matches one of the chars in the CHAR set SELECT LTRIM(ShortName, SK) FROM CustomerMaster

RPAD(string)
Similar to LPAD. Adds to the right end of string

RTRIM(string, CHAR set)


Similar to LTRIM. Removes at the right end

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS Oracle


SYSDATE
Returns the current DATE and TIME

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

SQL FUNCTIONS Oracle


Format YYYY YY MM MONTH MON DD D DAY HH HH24 MI SS TH Meaning Four digit year Last two digits of a year Month (01-12) Name of month stored as nine characters Month in three letter format Day of month (01-31) Day of week Name of day stored as nine characters Hour of the day Hour in the twenty four hour format Minute of the day Seconds of the minute Suffix used with day

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS Oracle


TO_CHAR
SELECT TO_CHAR(OrderDate, ddth, Month, YYYY) OrderDate FROM OrderReg

ROUND(n, m)
Returns n rounded to m places SELECT ROUND(Total, 2) FROM OrderItems

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS SQL SERVER


UPPER (string)
Converts all characters of a given string to upper case SELECT UPPER(ShortName) FROM CustomerMaster

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

SQL FUNCTIONS SQL SERVER


SUBSTRING(expression, start, length) Extracts substring from a given string considering the position and length provided Select SUBSTRING(Krishna, 2, 5) Output rishn REPLACE(string expression, string pattern, string replacement) Replaces a string after finding the pattern in the string provided Arguments passed cannot be null Select REPLACE(My first job, job, training) Output My first training

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS SQL SERVER


ROUND(x, d) or ROUND(x)
Rounds the argument x to d decimal places Select ROUND(150.222, 2) Output 150.22

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

SQL FUNCTIONS SQL SERVER


DATEPART(date part, date)
Returns the part of the date from a given date and time value Select DATEPART(date, 11/08/2010 08:30:00) Output : 11/08/2010

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS SQL SERVER


DATEADD(date part, number, date)
Function performs date arithmetic SELECT DATEADD(DAY, 2, 11/08/2010 23:59:59) Output - 11/10/2010 23:59:59

MONTH(date)
To get the month of a given date SELECT MONTH(GETDATE()) Output - 11
Note: This is only a partial list

Copyright 2010 Pratian Technologies www.pratian.com

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)

Copyright 2010 Pratian Technologies www.pratian.com

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

Subqueries cannot have ORDER BY clause

Copyright 2010 Pratian Technologies www.pratian.com

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);

Copyright 2010 Pratian Technologies www.pratian.com

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

PREDICATES WITH SUBQUERIES


Predicates that can be used with subqueries are
IN EXISTS ALL ANY/SOME IN SELECT OrderNo, OrderDate, OrderType FROM OrderReg WHERE UnqId IN (Select UnqId From CustomerMaster RegionCode = BA)

Where

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PREDICATES WITH SUBQUERIES


ALL
SELECT ItemNo, Rate FROM OrderItems WHERE Rate > ALL (SELECT Rate FROM OrderItems WHERE ItemNo = 5510);

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

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Question Time
Please try to limit the questions to the topics discussed during the session. Thank you.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Vous aimerez peut-être aussi