Anda di halaman 1dari 45

SQL Basics

By Aswin Subbarayaloo & Sudarson.K

Introduction to SQL

What is SQL?

Structured Query Language allows users to access data in relational database management systems, such as Oracle, Sybase, Informix, Microsoft SQL Server, Access, and others, by allowing users to describe the data the user wishes to see. SQL also allows users to define the data in a database, and manipulate that data.

ORIGIN OF SQL

In the early 1970s E.F. Codd, a mathematician by training and at the time a researcher for IBM, introduced a new concept relational model which is the base for the development of SQL.
Today, SQL is the only database language for relational DBMSs (industry standard) Other languages such as QUEL have died (the language QBE has at least inspired some graphical interfaces to databases, e.g. in Access, and the language Data log has influenced SQL:1999 in certain ways and is still studied and further developed in research).

FEATURES OF SQL

Interactive ad-hoc commands


Application program development (embedded into other languages like C, Java, HTML).

Non-Procedural Language.
We can't Execute more than one statement at a time. Language for any RDBMS. Referential integrity to create relationship between tables and avoid redundancy

Example of a database

CREATE TABLE EMP ( EMPNO NUMBER(4), ENAME VARCHAR2(15), JOB VARCHAR2(10), DOB DATE, SAL NUMBER(7,2),
DEPT NUMBER(7,2) );

BASIC SQL COMMANDS


DDL(Data Definition language)
DML/DRL (Data manipulation or retrieval language) TCL(Transaction control language) DCL(Data Control Language)

Data Definition Language

To Create Objects, To Alter Objects & To Drop Objects.


Commands: CREATE ALTER DROP TRUNCATE

DDL Statements are Auto Commit Statements

Data Manipulation Language

To Maintain information the following Commands: INSERT UPDATE DELETE

Transaction control language

A Transaction is the DBMSs abstract view of a user program: a sequence of reads and writes. Transaction : A Series of Inserts, Updates, Deletes etc., Commands: COMMIT ROLLBACK SAVEPOINT

Data Control Language

To Deal with Privileges. Commands: GRANT REVOKE

INDEX
What is an Index? Is a schema object Is independent of the table it indexes Types of Index: Clustered Index Non-Clustered Index APPLICATIONS OF INDEX Can reduce disk I/O by using a rapid path access method to locate data quickly Is used by the Oracle server to speed up the retrieval of rows by using a pointer

Example for Indexing

Before Indexing:

After Indexing:

Query for creating Index

VIEWS

How to create a View

Query for Views

Types of views

Horizontal Views

Combined Views

Normalization
The process of decomposing relations with anomalies to produce smaller well-structured relations.

Anomalies: Errors or inconsistencies that may result when user attempts to update a table that contains redundant data.
Well-structured relations contains minimal redundancy and allows users to insert, modify, and delete the rows in a table without errors or inconsistencies.

Anomalies

Relations that are not normalized will experience issues known as anomalies

Insertion anomaly Difficulties inserting data into a relation Modification anomaly Difficulties modifying data into a relation

Deletion anomaly Difficulties deleting data from a relation

Stages of Normal Forms


First Normal Form (1NF) Second Normal Form (2NF) Third Normal Form (3NF)

Boyce-Codd Normal Form (BCNF) Fourth Normal Form (4NF) Fifth Normal Form (5NF) Domain/Key Normal Form (DK/NF)

First Normal Form


A relation is in first normal form when it contains no multi-valued attributes. The value at the intersection of each row and column must be atomic.

Example for 1NF

Functional Dependencies And Keys


Normalization is based on the analysis of functional dependencies.
Functional dependency A constraint between two attributes or two sets of attributes. Emp_ID, Course_Name Date_Completed The date a course is completed is determined by the identity of the employee and the name of the course.

Second Normal Form

A relation that is in first normal form and has every non-key attribute functionally dependent on the primary key.

Second Normal Form


A relation that is in first normal form is in second normal form if and only if
1. 2.

3.

The primary key consists of only one attribute. No non-key attribute exists in the relation. Every no-key attribute is functionally dependent on the primary key.

To convert relation into second normal form, we decompose the relation into new relationships.

Example for 2-NF

After applying 2NF

Third Normal Form


Transitive dependency Functional dependency between two or more nonkey attributes.

A relation is in third normal form (3NF), if it is in second normal form and no transitive dependencies exist.

Example for 3NF

Solution to Previous Example

Boyce/Codd normal form

Boyce / Codd normal form Any remaining anomalies that result from functional dependencies have been removed

Introduction to Joins

JOINS

Selects Specific Columns from Multiple Tables

JOIN keyword specifies that tables are joined and how to join them ON keyword specifies join condition

Queries Two or More Tables to Produce a Result Set

Use primary and foreign keys as join conditions Use columns common to specified tables to join tables

Inner Joins

Inner joins combine tables by comparing values in columns that are common to both tables.

When you use inner joins, consider the following facts and guidelines:

Inner joins are the SQL Server default. You can abbreviate the INNER JOIN clause to JOIN. Specify the columns that you want to display in your result set by including the qualified column names in the select list. Include a WHERE clause to restrict the rows that are returned in the result set. Do not use a null value as a join condition because null values do not evaluate equally with one another.

Using Inner Joins


USE joindb SELECT buyer_name, sales.buyer_id, qty FROM buyers INNER JOIN sales ON buyers.buyer_id = sales.buyer_id GO

buyers
buyer_name buyer_id

sales
buyer_id prod_id qty

Adam Barr Sean Chai Eva Corets Erin OMelia

1 2 3 4

1 1 4 3 4

2 3 1 5 2

15 5 37 11 1003

Result
buyer_name buyer_id qty Adam Barr Adam Barr Erin OMelia Eva Corets Erin OMelia 1 1 4 3 4 15 5 37 11 1003

Outer Joins
Left or right outer joins combine rows from two tables that match the join condition, plus any unmatched rows of either the left or right table as specified in the JOIN clause. Rows that do not match the join condition display NULL in the result set. You also can use full outer joins to display all rows in the joined tables, regardless of whether the tables have any matching values.

Why to Use Left or Right Outer Joins


Use a left outer join to display all rows from the first-named table (the table on the left of the expression). If you reverse the order in which the tables are listed in the FROM clause, the statement yields the same result as a right outer join.

Using Outer Joins


USE joindb SELECT buyer_name, sales.buyer_id, qty FROM buyers LEFT OUTER JOIN sales ON buyers.buyer_id = sales.buyer_id GO

buyers
buyer_name Adam Barr Sean Chai Eva Corets Erin OMelia buyer_id 1 2 3 4 1 1 4 3 4 qty 15

sales
buyer_id prod_id 2 3 1 5 2 qty 15 5 37 11 1003

Result
buyer_name buyer_id Adam Barr 1

Adam Barr
Erin OMelia

1
4

5
37

Eva Corets Erin OMelia


Sean Chai

3 4
NULL

11 1003
NULL

Cross Joins

Cross joins display every combination of all rows in the joined tables. A common column is not required to use cross joins.
When you use cross joins, SQL Server produces a Cartesian product in which the number of rows in the result set is equal to the number of rows in the first table, multiplied by the number of rows in the second table.

Using Cross Joins


USE joindb SELECT buyer_name, qty FROM buyers CROSS JOIN sales GO

buyers
buyer_id buyer_name 1 Adam Barr 1

sales
buyer_id prod_id 2 qty 15

Result
buyer_name Adam Barr qty 15

2
3 4

Sean Chai
Eva Corets Erin OMelia

1
4 3 4

3
1 5 2

5
37 11 1003

Adam Barr
Adam Barr Adam Barr Adam Barr Sean Chai Sean Chai Sean Chai Sean Chai Sean Chai Eva Corets ...

5
37 11 1003 15 5 37 11 1003 15 ...

Stored Procedures
A stored procedure is a set of commands that automatically updates, executes, selects or deletes from tables.

Features of stored procedures Run faster than the same commands executed interactively as a batch. Reduce network traffic. Enforce consistency throughout the database. Help provide security. Reduce operator error

Example for stored procedures


Inventory Table ID 28 29 30 Product Beans carrot Beetroot Warehouse FY NY FY Qty 10 20 30

SELECT Product, Quantity FROM Inventory WHERE Warehouse = 'FL This resulted in very inefficient performance at the SQL Server

Let's create a procedure called sp_GetInventory that retrieves the inventory levels for a given warehouse. Here's the SQL code: CREATE PROCEDURE sp_GetInventory @location varchar(10) AS SELECT Product, Quantity FROM Inventory WHERE Warehouse = @location

Florida warehouse manager can then access inventory levels by issuing the command EXECUTE sp_GetInventory 'FL'

The New York warehouse manager can use the same stored procedure to access that area's inventory. EXECUTE sp_GetInventory 'NY'

THANK YOU

Anda mungkin juga menyukai