sql
DESCRIPTION
lets you know all the sql queriesTRANSCRIPT
ROHAN CHAUBEY - 1310 SOHAM PATEL – 1306 ANKIT PANCHAL - 1337
o SQL is a standard language for accessing and manipulating databases.o IBM developed the original version of sql,originally called sequel, as a part of R project in the early 1970’s.o The sequel language is evolved since then, and its name has changed to SQL(structured query language).oANSI and ISO standard SQL:
>> SQL-86, SQL-89, SQL-92 >> SQL:1999, SQL:2003, SQL:2008,SQL:2011
SQL
INTRODUCTION TO SQL
SQL can retrieve data from a database.•SQL can insert records in a database.•SQL can update records in a database.•SQL can delete records from a database.•SQL can create new tables in a database.•SQL can create views in a database.•SQL can set permissions on tables, procedures, and views.•SQL can execute queries against a database.•And many more……….
What Can SQL do?
SQL
Different Types of SQL Languages:
COMMANDS
Data Definition Language (DDL) statements are used to define the database structure or schema.
CREATE :- to create objects in the databaseALTER: - alters the structure of the databaseDROP: - delete objects from the databaseTRUNCATE: - remove all records from a table, including all spaces allocated for the records are removedCOMMENT :- add comments to the data dictionaryRENAME: - rename an object
Data Manipulation Language (DML) statements are used for managing data within schema objects. SELECT - retrieve data from the a database
INSERT: - insert data into a tableUPDATE: - updates existing data within a tableDELETE: - deletes all records from a table, the space for the records remainMERGE: - UPSERT operation (insert or update)CALL: - call a PL/SQL or Java subprogramEXPLAIN PLAN: - explain access path to dataLOCK TABLE :- control concurrency
Different Types of SQL Languages:
COMMANDS
Data Control Language (DCL) statements.
GRANT: - gives user's access privileges to databaseREVOKE: - withdraw access privileges given with the GRANT command
Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
COMMIT: - save work doneSAVEPOINT: - identify a point in a transaction to which you can later roll backROLLBACK: - restore database to original since the last COMMITSET TRANSACTION :- Change transaction options like isolation level and what rollback segment to use
1. SELECT Clause-The SELECT statement is used to select data from a database. SELECT <column_name>from <table_name>;
2. SELECT DISTINCT Clause-The SELECT DISTINCT statement is used to return only distinct (different) values. SELECT DISTINCT <column_name> from <table_name>;
Different types of Clause:
3.WITH Clause-The WITH clause provides a way of defining a temporary view whose definition is available only to the query in which the with clause occurs. WITH max_budget (value) as (select max(budget) from department) select budget from department, max_budget where department.budget = max_budget.value;
4.ORDER BY Clause-The ORDER BY keyword is used to sort the result-set. SELECT column_name,column_name from table_name ORDER BY column_name,column_name ASC|DESC;
SQL
5.GROUP BY Clause-Aggregate functions often need an added GROUP BY statement. SELECT column_name,aggregate_function(column_name) from table_name WHERE column_name operator value GROUP BY column_name;
6.HAVE Clause-The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value;
SQL
SET OPERATION:1.UNION:
The UNION operator is used to combine the result-set of two or more SELECT statements. SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; SQL
2.INTERSECT:Intersect operation is used to combine two select statement but it only returns the record which are common from both select statement. Select * from first INTERSECT Select * from second;
3.MINUS:Minus operation combines result of two select statement and return only those result which belongs to first set of result. Select * from first MINUS Select * from second;
SQL
Different types of KEYS:
1.UNIQUE Key-The UNIQUE constraint uniquely identifies each record in a database table. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName) )
SQL
Different types of KEYS(cont.):
2. PRIMARY Key -The PRIMARY KEY constraint uniquely identifies each record in a database table . Primary keys must contain unique values. A primary key column cannot contain NULL values. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY(P_Id,LastName) )
SQL
Different types of KEYS(cont.):
3. FOREIGN Key-The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to. CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )
SQL
• SQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patterns that are described using two special characters:• percent (%). The % character matches any
substring.• underscore (_). The _ character matches
any character.• Find the names of all instructors whose
name includes the substring “dar”. select namefrom instructorwhere name like '%dar%'
String Operations:
SQL
String Operations:(cont.)Patters are case sensitive. Pattern matching examples:
• ‘Intro%’ matches any string beginning with “Intro”.
• ‘%Comp%’ matches any string containing “Comp” as a substring.
• ‘_ _ _’ matches any string of exactly three characters.
• ‘_ _ _ %’ matches any string of at least three characters.
SQL supports a variety of string operations such as
• concatenation (using “||”)• converting from upper to lower case (and
vice versa)• finding string length, extracting substrings,
etc.
SQL
Domain Types in SQL-char(n). Fixed length character string,
with user-specified length n.varchar(n). Variable length character
strings, with user-specified maximum length n.
int. Integer (a finite subset of the integers that is machine-dependent).
smallint. Small integer (a machine-dependent subset of the integer domain type).
numeric(p,d). Fixed point number, with user-specified precision of p digits, with n digits to the right of decimal point.
real, double precision. Floating point and double-precision floating point numbers, with machine-dependent precision.
float(n). Floating point number, with user-specified precision of at least n digits.
SQL
Joined Relations• Join operations take two relations and return as
a result another relation.• These additional operations are typically used
as subquery expressions in the from clause• Join condition – defines which tuples in the two
relations match, and what attributes are present in the result of the join.
• Join type – defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated.
SQL
• In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.)
• Consider a person who needs to know an instructors name and department, but not the salary. This person should see a relation described, in SQL, by
select ID, name, dept_name from instructor
• A view provides a mechanism to hide certain data from the view of certain users.
• Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view.
Views
• A view is defined using the create view statement which has the form
create view v as < query expression >
where <query expression> is any legal SQL expression. The view name is represented by v.
• Once a view is defined, the view name can be used to refer to the virtual relation that the view generates.
• View definition is not the same as creating a new relation by evaluating the query expression – Rather, a view definition causes the saving of an
expression; the expression is substituted into queries using the view.
View Definition
SQL
• A view of instructors without their salary: create view faculty as select ID, name, dept_name from instructor
Taylor
SQL
Example Views
• Add a new tuple to faculty view which we defined earlier:
insert into faculty values (’30765’, ’Green’, ’Music’);This insertion must be represented by the insertion of the tuple:
(’30765’, ’Green’, ’Music’, null)into the instructor relation
Update of a ViewPreviously defined view
• A view of instructors without their salary: create view faculty as select ID, name, dept_name from instructor
SQL
• One view may be used in the expression defining another view
• A view relation v1 is said to depend directly on a view relation v2 if v2 is used in the expression defining v1
• A view relation v1 is said to depend on view relation v2 if either v1 depends directly to v2 or there is a path of dependencies from v1 to v2
• A view relation v is said to be recursive if it depends on itself.
Views Defined Using Other Views
SQL
• Unit of work• Atomic transaction
– either fully executed or rolled back as if it never occurred
• Isolation from concurrent transactions• Transactions begin implicitly
– Ended by commit work or rollback work• But default on most databases: each SQL
statement commits automatically– Can turn off auto commit for a session (e.g.
using API)– In SQL:1999, can use: begin atomic ….
end• Not supported on most databases
Transactions
SQL
• Integrity constraints guard against accidental damage to the database, by ensuring that authorized changes to the database do not result in a loss of data consistency. –A checking account must have a
balance greater than $10,000.00–A salary of a bank employee must be at
least $4.00 an hour–A customer must have a (non-null)
phone number
Integrity Constraints
SQL
Integrity Constraints on a Single Relation
• not null• primary key• unique• check (P), where P is a predicate SQL
Not Null and Unique Constraints • not null
– Declare name and budget to be not null
name varchar(20) not null budget numeric(12,2) not null
• unique ( A1, A2, …, Am)
– The unique specification states that the attributes A1, A2, … Amform a candidate key.
– Candidate keys are permitted to be null (in contrast to primary keys).
SQL
The check clause• check (P) where P is a predicateExample: ensure that semester is one of fall, winter, spring or summer:
create table section ( course_id varchar (8), sec_id varchar (8), semester varchar (6), year numeric (4,0), building varchar (15), room_number varchar (7), time slot id varchar (4), primary key (course_id, sec_id, semester, year), check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’)));
SQL
• Ensures that a value that appears in one relation for a given set of attributes also appears for a certain set of attributes in another relation.– Example: If “Biology” is a
department name appearing in one of the tuples in the instructor relation, then there exists a tuple in the department relation for “Biology”.
• Let A be a set of attributes. Let R and S be two relations that contain attributes A and where A is the primary key of S. A is said to be a foreign key of R if for any values of A appearing in R these values also appear in S.
Referential Integrity
Taylor
SQL
Example of Referential Integrity
• create table course (
course_id char(5) primary key, title varchar(20), dept_name varchar(20) references department
) SQL
Built-in Data Types in SQL • date: Dates, containing a (4 digit) year, month and
date– Example: date ‘2005-7-27’
• time: Time of day, in hours, minutes and seconds.– Example: time ‘09:00:30’ time ‘09:00:30.75’
• timestamp: date plus time of day– Example: timestamp ‘2005-7-27 09:00:30.75’
• interval: period of time– Example: interval ‘1’ day– Subtracting a date/time/timestamp value from
another gives an interval value– Interval values can be added to date/time/timestamp
values
Index Creation• create table student
(ID varchar (5),name varchar (20) not null,dept_name varchar (20),tot_cred numeric (3,0) default 0,primary key (ID))
• create index studentID_index on student(ID)• Indices are data structures used to speed up access to
records with specified values for index attributes– e.g. select *
from student where ID = ‘12345’
can be executed by using the index to find the required record, without looking at all records of student
SQL
Large-Object Types• Large objects (photos, videos, CAD files, etc.) are stored as
a large object:– blob: binary large object -- object is a large collection of
uninterpreted binary data (whose interpretation is left to an application outside of the database system)
– clob: character large object -- object is a large collection of character data
– When a query returns a large object, a pointer is returned rather than the large object itself.
– For example :Book_review clob(10KB)Image blob(10MB)Movie blob(2GB)
SQL
What is SQL TRIM?The SQL Trim feature is / are functions (LTRIM and RTRIM) that remove leading and trailing blanks from a string.
SQL TRIM Syntax : SELECT RTRIM(<value_1>) SELECT LTRIM(<value_1>)SQL TRIM Example :
The LTRIM function removes the leading blanks in the string ' Bob'. SELECT LTRIM(' Bob ') as trimmed_string The result is shown in fig 1 .
Fig 1
The SQL Substring feature is a function that enables parts of strings to be accessed.
For example, the function SUBSTRING('212-555-1234', 9 , 4) returns:'1234' .It returns 4 characters starting in position 9.
SQL SUBSTRING Syntax: SELECT SUBSTRING(<column_name>, position, length) FROM <table_name>;
What is SQL SUBSTRING?
SQL
What is SQL SUBSTRING? (CONT.)This SQL Statement with SUBSTRING is executed:
SELECT region, SUBSTRING (region_name, 2, 3) as substring_nameFROM region;
table output SQL
ACCESSING SQL FROM A PROGRAMING LANGUAGE
DYNAMIC SQL
EMBEDDED SQL
SR.No. Static (embedded) SQL Dynamic (interactive) SQL
1. In static SQL how database will be accessed is predetermined in the embedded SQL statement.
In dynamic SQL, how database will be accessed is determined at run time.
2. It is more swift and efficient. It is less swift and efficient.
3. SQL statements are compiled at compile time.
SQL statements are compiled at run time.
4. It is generally used for situations where data is distributed uniformly.
It is generally used for situations where data is distributed non-uniformly.
5. It is less flexible. It is more flexible.
o A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database.o The database trigger are used for following purposes:
1.To enforce complex constraint.2.To customize complex security
authorization.3.To maintain replicate table.4.To audit the process.for example:to
keep track of changes made to a table.
TRIGGERS
Defining a trigger:Create(or replace) trigger <trigger name>[before/after][insert/update]of columnsOr {delete/insert}of columnsOn table {for each row(when condition)}[referencing (old as new)(new as old)]PL/SQL block
Drop trigger syntax:Drop trigger<trigger_name> SQL
Types of triggerstypes discription
1.statement-level trigger Fired only once for DML statement irrespective of no. of rows affected.it is the default type of trigger.
2.row-level trigger Fired once for each row affected by DML command.
3.Before triggers While definning a trigger , we can specify whether the trigger is to be fired before or after the commands are execuetd.
4.After triggers It is fired after the triggering action is completed.
create trigger timeslot_check1 after insert on sectionreferencing new row as nrowfor each rowwhen (nrow.time_slot_id not in ( select time_slot_id from time_slot)) /* time_slot_id not present in time_slot */begin rollbackend;
Create(or replace) trigger <trigger name>[before/after][insert/update]of columnsOr {delete/insert}of columnsOn table {for each row(when condition)}[referencing (old as new)(new as old)]PL/SQL block
Example of trigger
Ranking may leave gaps: e.g. if 2 students have the same top GPA, both have rank 1, and the next rank is 3o dense_rank does not leave gaps, so next dense rank would be 2
RankingRanking is done in conjunction with an order by specification.
Suppose we are given a relation student_grades(ID, GPA) giving the grade-point average of each student
Find the rank of each student. select ID, rank() over (order by GPA
desc) as s_rank from student_grades
Limit clauseTo find the top n tuples we use the clause “limit”.
For example:select id,GPAFrom student_gradesOrder by GPALimit 10;
REFERENCES1.WWW.DB-BOOKS.COM2.WWW.GOOGLE.COM3.WIKEPEDIA4.DATABASE SYSTEM CONCEPTS-
SIXTH EDITION5.WWW.W3SCHOOLS.COM6.WWW.YAHOO.COM