View
665
Download
0
Category
Tags:
Preview:
Citation preview
SQLBy
Balraj and Ziya
RDBMS is an acronym for Relational Database Management System. The data in RDBMS is stored in database objects called tables. The database tables are the primary data storage for every RDBMS and essentially they are collections of related data entries.
For example a table called Users might store information about many persons, and each entry in this table will represent one unique user. Even though all user entries in the Users table are unique, they are related in the sense that they describe similar objects.
RDBMS
Table Users
Each database table consists of columns and rows.
Continued..
First name
Last name Date of birth
John Smith 12/12/1969
David Stonewall 01/03/1954
Susan Grant 03/03/1970
Each table column defines the type of data stored in it, and this data type is valid for all rows in this table. A table row is a collection of data having 1 entry for each column in this particular table.
DBMS store the data into group of tables, which might or might not be related by common fields (database table columns).
RDBMS also provide relational operators to insert/update/delete information stored into the database tables.
MS SQL Server, DB2, Oracle and MySQL are all Relational Database Management Systems.
Continued..
Introduction to SQL Types of languages DDL DML DCL Aggregate functions JOINS
Contents
Insert Select Update Delete
DML commands
SQL is used to make a request to retrieve data from a Database.
The DBMS processes the SQL request, retrieves the requested data from
the Database, and returns it.
This process of requesting data from a Database and receiving back the
results is called a Database Query and hence the name Structured Query
Language.
• SQL is a non-procedural language aimed to store, manipulate and retrieve
data
stored in a relational database.
This language was developed by IBM corporation for processing data
contained in mainframe computer database.
By Dr.E.F.CODD.
Introduction to SQL
There are three types of languages in SQL.
Data Definition Language (DDL) Data Modification Language(DML) Data Control Language (DCL)
Types of languages
DDL contains the commands used to create, modify and drop the database, tables and other objects in the database.
CREATE USE ALTER DROP
Data Definition Language (DDL)
Syntax:
CREATE TABLE tablename
(column_name data_ type constraint, column_name data_ type constraint);
CREATE TABLE Customer_Details
(Cust_ID Number(5), Cust_Last_Name VarChar(20), Cust_Mid_Name VarChar(4), Cust_First_Name VarChar(20), Account_No Int, Account_Type VarChar(10), Bank_Branch VarChar(25), Cust_Email VarChar(30));
Create -SQL
Syntax
SQL - ALTER TABLE
ALTER TABLE Customer_Details ADD Contact_Phone int;
ALTER TABLE Customer_Details DROP (Contact_Phone);
ALTER TABLE tablename (ADD/MODIFY/DROP) column_name
ALTER TABLE Customer_Details
MODIFY Contact_Phone int;
PRIMARY KEY: Uniquely identifies each row of the table and prevents NULL values. A table can have only one primary key constraint.
NOT NULL: Prevents NULL values from being entered into the column. These types of constraints are defined on a single column. By default, Oracle allows NULL values in any column. A NOT NULL constraint is defined at the column level; it cannot be defined at the table level.
Definations
DROP TABLE◦ Deletes table structure◦ Cannot be recovered◦ Use with caution
TO DELETE A FIELD FROM THE TABLE STRUCTURE :◦ alter table tablename drop column columnname;◦ sql> alter table Customer_Details drop column
Cust_Last_Name ; Drop :
◦ IT IS USED TO DELETE THE STRUCTURE OF THE TABLE.◦ EX: drop table tablename;◦ sql > drop table Customer_Details
Drop Table-SQL
Deleting All Rows of a table
TRUNCATE TABLE Customer Details;
TRUNCATE: The TRUNCATE statement is similar to a DELETE statement
without a WHERE clause, except for the following:
TRUNCATE is very fast on both large and small tables. DELETE will generate undo information, in case a rollback is issued, but TRUNCATE will not generate undo.
TRUNCATE is DDL and, like all DDL, performs an implicit commit – a TRUNCATE cannot be rolled back. Any uncommitted DML changes will also be committed with the TRUNCATE.
Truncate Table
DELETE TRUNCATE
Data can be recovered Data cannot be recovered.
DML statement DDL statement
DELETE does not release the memory occupied by the records of the table
TRUNCATE releases the memory occupied by the records of the table
Difference between Delete and Truncate
Select: It has 5 main clauses to choose from
SELECT [ALL|DISTINCT] col1[,col2]
FROM table1[,table2]
[WHERE condition]
[GROUP BY column-list]
[HAVING conditions]
[ORDER BY column-list [ASC|DSC]]
Note:[]-Optional
Select-command
O_id Order date Order price customer
1 12/11/2008 1000 Ram
2 23/10/2008 1600 Ravi
3 02/09/2008 700 Ram
4 03/09/2008 300 Ram
5 30/08/2008 2000 John
6 04/10/2008 100 Ravi
Group by -example
Select customer, sum(order price) from orders Group by customer
Out put
Continued..
Customer Order price
Ram 2000
Ravi 1700
John 2000
The Having clause was added to SQL, because the where keyword can not be used with aggregate functions.
The same example with Having clause. Select customer, sum(order price) from orders
Group by customer Having sum(order price) >1700.
Having Clause
Customer Order price
Ram 2000
John 2000
Update: Syntax: UPDATE table name
SET Column name=[new value]WHERE {condition}
Delete: Syntax: DELETE from table name
WHERE {condition}
Update and Delete
DCL statements are used for securing the database and control the access to database.
Grant Revoke USE Dtabase_name
Grant select on table nameto public
USE Dtabase_nameRevoke select on table nameto public
DCL-Commands
Aggregate functions operate against a collection of values, but return a single value.
Min Max Sum Count(column) Count(*) Avg
Aggregate functions
1. JOIN is a query clause that can be used with the SELECT, UPDATE, and DELETE
data query statements to simultaneously affect rows from multiple tables.
There are several distinct types of JOIN statements that return different data
result sets.
2. Joined tables must each include at least one field in both tables that contain
comparable data.
For example, if you want to join a Customer table and a
Transaction table, they both must contain a common element, such as
CustomerID column, to serve as a key on which the data can be matched. Tables can be joined on multiple columns so long as the columns have the potential to supply matching information. Column names across tables don't have to be the same, although for readability this standard is generally preferred.
The JOIN concept
1. SELECT Customer.CustomerID, TransID, TransAmt FROM Customer JOIN Transaction
ON Customer.CustomerID = Transaction.CustomerID;
In practice, you'd never use the example above because the type of join is not specified. In this case,
SQL Server assumes an INNER JOIN. You can get the equivalent to this query by using the
Statement:
The basic JOIN statement
In relational databases, a join operation matches records in two tables. The two tables must be joined by at least one common field. That is, the join field is a member of both tables. Typically, a join operation is part of a SELECT query.
select * from A, B where A.x = B.y
The column names (x and y in this example) are often, but not necessarily, the same.
Inner join
(database)outer join - A less commonly used variant of the inner join relational database operation. An inner join selects rows from two tables such that the value in one column of the first table also appears in a certain column of the second table. For an outer join, the result also includes all rows from the first operand ("left outer join", "*="), or the second operand ("right outer join", "=*"), or both ("full outer join", "*=*"). A field in a result row will be null if the corresponding input table did not contain a matching row.
For example, if we want to list all employees and their employee number, but not all employees have a number, then we could say (in SQL):
SELECT employee.name, empnum.number WHERE employee.id *= empnum.id
The "*=" means "left outer join" and means that all rows from the "employee" table will appear in the result, even if there is no match for their ID in the empnum table.
Outer Join
The CROSS JOIN has earned a bad reputation because it’s very resource intensive and returns results of questionable usefulness. When you use the
CROSSJOIN, you're given a result set containing every possible combination of the
rowsreturned from each table. Take the following example:
SELECT Customer Name, TransDate, TransAmt FROM Customer CROSS JOIN Transaction;
With the CROSS JOIN, you aren’t actually free to limit the results, but you can use
The ORDER BY clause to control the way they are returned. If the tables joined in
this example contained only five rows each, you would get 25 rows of results.Every Customer Name would be listed as associated with every TransDate
andTransAmt.I really did try to come up with examples where this function was useful, and
theywere all very contrived. However, I’m sure someone out there is generating
lists ofall their products in all possible colors or something similar, or we wouldn’t
havethis wonderful but dangerous feature.
The notorious CROSS JOIN
OUTER JOINs, sometimes called “complex joins,” aren’t actuallycomplicated. They are so called because SQL Server performs two functionsfor each OUTER JOIN.
The first function performed is an INNER JOIN. The second function includesthe rows that the INNERJOIN would have dropped. Which rows are includeddepends on the type of OUTER JOIN that is used and the order the tableswere presented.
There are three types of an OUTER JOIN: LEFT, RIGHT, and FULL. As you’veProbably guessed, the LEFT OUTER JOIN keeps the stray rows from the “left”table (the one listed first in your query statement). In the result set, columnsfrom the other table that have no corresponding data are filled with NULLvalues.Similarly, the RIGHT OUTER JOIN keeps stray rows from the right table, filling columns from the left table with NULL values. The FULL OUTER JOIN keeps allstray rows as part of the result set. Here is your example:
The OUTER JOIN can include mismatched rows
SELECT Customer Name, TransDate, TransAmt FROM Customer LEFTOUTER JOIN Transaction ON Customer. CustomerID =Transaction. CustomerID;
Customer names that have no associated transactions will still bedisplayed. However, transactions with no corresponding customers
willnot, because we used a LEFT OUTER JOIN and the Customer table
waslisted first.
In SQL Server, the word OUTER is actually optional.
The clauses LEFT JOIN, RIGHT JOIN, and FULL JOIN are equivalent toLEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN,respectively.
Continued..
THE END
Recommended