Sunteți pe pagina 1din 100

Unit 2:Understand the concept

of SQL
By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.

Outline
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

Explain benefits of SQL


Describe about embedded SQL, Lexical conventions, oracle tools
support for SQL
Describe Naming of the Objects and parts and how to refer them
Explain referring of the object in remote data bases
Explain literals, text and integers
Explain the different data types like character, number long, date,
raw and long raw etc.
Illustrate pseudo-columns
Illustrate the comments within SQL Statement
List and explain the functions like single row, character, conversion
and group functions
Explain date and number format models
Describe commands of SQL like data definition language
commands, data manipulation language commands, transaction
control commands.
Explain Sub queries
Explain Joins and types of Joins

Comments within SQL Statement


Comments can make your application easier for you to read and maintain.
For example, you can include a comment in a statement that describes the purpose of
the statement within your application.
Comments within SQL statements do not affect the statement execution.
A comment can appear between any keywords, parameters, or punctuation marks in a
statement.
You can include a comment in a statement in two ways:
Begin the comment with a slash and an asterisk (/*).
Proceed with the text of the comment.
This text can span multiple lines.
End the comment with an asterisk and a slash (*/).
The opening and terminating characters need not be separated from the text by a
space or a line break.
Begin the comment with -- (two hyphens).
Proceed with the text of the comment.
This text cannot extend to a new line.
End the comment with a line break.
SELECT last_name, salary + NVL(commission_pct, 0), job_id, e.department_id /* Select
all employees whose compensation is greater than that of Pataballa.*/ FROM
employees e, departments d /*The DEPARTMENTS table is used to get the department
name.*/ WHERE e.department_id = d.department_id AND salary +
NVL(commission_pct,0) > /* Subquery: */ (SELECT salary + NVL(commission_pct,0) /*
total compensation is salar + commission_pct */ FROM employees WHERE last_name =

SQL
SQL is a nonprocedural language.

This means that a query formulated in SQL need not specify how a problem is to be
solved nor how data should be accessed by the computing system; instead, an SQL query
states what the query is, i.e., what data are sought.

This leaves the user free to focus on the logic of the query.
Because the DBMS makes use of its internal knowledge, in most cases, the DBMS
generates retrieval procedures that are faster than equivalent retrieval procedures
built directly by the user.
The SQL language consists of three components:
the data definition language (DDL),
the data manipulation language (DML), and
the data control language (DCL).

The first component allows the user to define the structure of the tables of the
database.
The second contains retrieval and update directives.
The last component allows the database administrator to define the access rights
to the database for various categories of users.
SQL syntax is format-free: tabs, carriage returns, and spaces can be included
anywhere a space occurs in the definition of an SQL construct.
Also, case is insignificant in table names, reserved words and keywords.
However, case is significant in character string literals.

Benefits and Drawbacks of SQL


Advantages of SQL:
High Speed:

SQL Queries can be used to retrieve large amounts of records from a database quickly and
efficiently.

Well Defined Standards Exist:

SQL databases use long-established standard, which is being adopted by ANSI & ISO.
Non-SQL databases do not adhere to any clear standard.

No Coding Required:

Using standard SQL it is easier to manage database systems without having to write
substantial amount of code.

Emergence of ORDBMS:

Previously SQL databases were synonymous with relational database.


With the emergence of Object Oriented DBMS, object storage capabilities are extended to
relational databases.

Disadvantages of SQL:

Difficulty in Interfacing:
Interfacing an SQL database is more complex than adding a few lines of code.
More Features Implemented in Proprietary way:
Although SQL databases conform to ANSI & ISO standards, some databases go for
proprietary extensions to standard SQL to ensure vendor lock-in.

Embedded SQL
SQL provides a powerful declarative query language. However, access to
a database from a general-purpose programming language is required
because,
SQL is not as powerful as a general-purpose programming language. There
are queries that cannot be expressed in SQL, but can be programmed in C,
Fortran, Pascal, Cobol, etc.
Nondeclarative actions -- such as printing a report, interacting with a user, or
sending the result to a GUI -- cannot be done from within SQL.

The SQL standard defines embedding of SQL as embedded SQL and the
language in which SQL queries are embedded is referred as host
language.
The result of the query is made available to the program one tuple
(record) at a time.
To identify embedded SQL requests to the preprocessor, we use EXEC
SQL statement:
EXEC SQL embedded SQL statement END-EXEC
Note: A semi-colon is used instead of END-EXEC when SQL is embedded
in C or Pascal.

Embedded SQL Code

Embedded SQL statements: declare cursor, open, and fetch statements.


EXEC SQL
declare c cursor for
select cname, ccity
from deposit, customer
where deposit.cname = customer.cname and deposit.balance > :amount
END-EXEC
here amount is a host-language variable.
EXEC SQL open c END-EXEC
This statement causes the DB system to execute the query and to save the results within a temporary
relation.
A series of fetch statement are executed to make tuples of the results available to the program.
EXEC SQL fetch c into :cn, :cc END-EXEC
The program can then manipulate the variable cn and cc using the features of the host programming
language.
A single fetch request returns only one tuple. We need to use a while loop (or equivalent) to process
each tuple of the result until no further tuples.
We need to use close statement to tell the DB system to delete the temporary relation that held the
result of the query.
EXEC SQL close c END-EXEC
Embedded SQL can execute any valid update, insert, or delete statements.
Dynamic SQL component allows programs to construct and submit SQL queries at run time.

Lexical conventions for issuing SQL


In a SQL statement, you can include one or more tabs, carriage
returns, spaces, or comments anywhere a space occurs within the
definition of the statement.
Thus, Oracle Database evaluates the following two statements in the
same manner:
SELECT last_name,salary*12,MONTHS_BETWEEN(hire_date,
SYSDATE) FROM employees;
SELECT last_name, salary * 12,
MONTHS_BETWEEN( hire_date, SYSDATE )

FROM employees;

Case is insignificant in reserved words, keywords, identifiers and


parameters.
However, case is significant in text literals and quoted names.

Oracle tools support for SQL


Different SQL tools run code, return results, and offer helpful differences.
SQL*Plus

SQL*Plus is a part of all Oracle Database installations.


You can also install SQL*Plus without a database installation by installing the Oracle Database
10g Instant ClientBasic or Basic Lite packageand the SQL*Plus package.
SQL*Plus buffers each line you type, until you do one of two things:
Terminate a line with a semicolon.
Type a forward-slash (/) on a line by itself.

iSQL*Plus

Oracle9i Database introduced a version of SQL*Plus you can access from your Web browser, Called
iSQL*Plus, it's a three-tier application in which the work is done on your behalf by an application service
running on the database server.
Like SQL*Plus, iSQL*Plus can be used to execute SQL*Plus commands, SQL statements, PL/SQL blocks,
and XML queries.
One benefit of iSQL*Plus is that you can provision SQL*Plus access to a group of users without having to
install client software on each user's local PC.

Oracle Application Express's SQL Workshop

The enhanced SQL Workshop in Oracle Application Express 2.0 provides interactive SQL execution,
GUI-based query building (in a browser!), script editing and execution, a very nice object browser, the
easiest comma-separated-values (CSV) importing ever seen, and more.
Query Builder
the drag-and-drop version of a query

SQL Workshop Scripts


Scripts in SQL Workshop can be composed only of SQL statements, PL/SQL blocks, and comments

Object Browser
object browser feature is the ability to view diagrams showing groups of related tables.

Export/Import
SQL Workshop offers a useful set of utilities and canned reports, including one of the neatest utilities for importing
comma-delimited data.

Which Tool to Use?


Oracle Application Express 2.0's SQL
Workshop has a lot to offer in the way of
convenience features.
It's an easy tool for developers to use
when learning about an unfamiliar
schema, and it has probably the most
convenient explain-plan feature of the
three tools.

Naming of the Objects and parts and how to refer them


The general syntax for referring to an object or a part:
database_object_or_part::=
object is the name of the object.
schema is the schema containing the object.

The schema qualifier lets you refer to an object in a schema other than your own.
You must be granted privileges to refer to objects in other schemas.
If you omit schema, then Oracle assumes that you are referring to an object in your own
schema.

part is a part of the object.

This identifier lets you refer to a part of a schema object, such as a column or a partition of a
table.
Not all types of objects have parts.

dblink applies only when you are using the Oracle Database distributed functionality.
This is the name of the database containing the object.
The dblink qualifier lets you refer to an object in a database other than your local database.
If you omit dblink, then Oracle assumes that you are referring to an object in your local
database.
Not all SQL statements allow you to access objects on remote databases.

Referring objects in Other schemas:

schema.object

Schema and NonSchema Objects


Within a namespace, no two objects can
have the same name.
The following schema objects share one
namespace:
Tables
Views
Sequences
Private synonyms
Stand-alone procedures
Stand-alone stored functions
Packages
Materialized views
User-defined types
Each of the following schema objects has
its own namespace:
Indexes
Constraints
Clusters
Database triggers
Private database links
Dimensions

Because tables and views are in the


same namespace, a table and a view
in the same schema cannot have the
same name.
However, tables and indexes are in
different namespaces, and can have
the same name.
Each of the following nonschema
objects also has its own namespace:

User roles
Public synonyms
Public database links
Tablespaces
Profiles
Parameter files (PFILEs) and server
parameter files (SPFILEs)

Because the objects in these


namespaces are not contained in
schemas, these namespaces span the
entire database.

Referring to Objects in Remote Databases


A database link is a schema object that causes Oracle to connect to a remote database to access
an object there.
Creating Database Links
You create a database link with the statement
CREATE DATABASE LINK.

The statement lets you specify this information about the database link:
The name of the database link
The database connect string to access the remote database
The username and password to connect to the remote database

Oracle stores this information in the data dictionary.


dblink::=

database should specify the name portion of the global name of the remote database to which
the database link connects.
This global name is stored in the data dictionary of the remote database;
you can see this name in the GLOBAL_NAME data dictionary view.
domain should specify the domain portion of the global name of the remote database to which
the database link connects.
If you omit domain from the name of a database link, then Oracle qualifies the database link
name with the domain of your local database as it currently exists in the data dictionary.
connect_descriptor lets you further qualify a database link.
Using connect descriptors, you can create multiple database links to the same database.

Literals, Text and Integers


The terms literal and constant value are synonymous and refer to a fixed
data value.
For example, 'JACK', 'BLUE ISLAND', and '101' are all character literals; 5001 is a
numeric literal.

Character literals are enclosed in single quotation marks so that Oracle can distinguish
them from schema object names.

You can specify character literals with the 'text' notation, national character
literals with the N'text' notation (Standard SQL defines NCHAR or NATIONAL
CHAR as a way to indicate that a CHAR column should use some predefined
character set), and numeric literals with the integer, or number notation,
depending on the context of the literal.
Here are some valid text literals:

'Hello'
'ORACLE.dbs'
'Jackie
's raincoat'
'09-MAR-98'
N'nchar literal

Here are some valid integers:


7
+255

Oracle Character Data Types

Oracle Numeric Data Types

Oracle Date Data Types

Oracle Large Object (LOB) Data Types

Oracle Rowid Data Types

Pseudo-columns
A pseudo-column is an Oracle assigned value (pseudo-field) used in the same
context as an Oracle Database column, but not stored on disk.
SQL and PL/SQL recognizes the following SQL pseudocolumns, which return
specific data items:
SYSDATE,

SQL> SELECT sysdate, systimestamp FROM dual;

SYSDATE
SYSTIMESTAMP
--------- ---------------------------------------13-DEC-07
13-DEC-07 10.02.31.956842 AM +02:00

SYSTIMESTAMP,
ROWID - returns the rowid (binary address) of a row in a database table.
ROWNUM - returns a number indicating the order in which a row was selected from a table.
UID,
USER,
SQL> SELECT uid, user FROM dual;
UID
USER
---------- -----------------------------50 MICHEL

LEVEL,
CURRVAL,
NEXTVAL,

sequence_name.CURRVAL
sequence_name.NEXTVAL
INSERT INTO emp VALUES (empno_seq.NEXTVAL, my_ename, ...);

ORA_ROWSCN, etc.

Comments within SQL Statement


In SQL, you can comment your code just like any other language.
Comments can appear on a single line or span across multiple
lines.
Syntax

There are two syntaxes that you can use to create a comment in SQL.

Syntax Using -- symbol


-- comment goes here

A comment started with -- symbol must be at the end of a line in your


SQL statement with a line break after it.
This method of commenting can only span a single line within your
SQL and must be at the end of the line.

Syntax Using /* and */ symbols


/* comment goes here */

A comment that starts with /* symbol and ends with */ and can be
anywhere in your SQL statement.
This method of commenting can span several lines within your SQL.

Examples of Comments within SQL


Statement
SELECT websites.site_name /* Author:
TechOnTheNet.com */ FROM websites;
SELECT /* Author: TechOnTheNet.com */
websites.site_name FROM websites;
SELECT websites.site_name -- Author: TechOnTheNet.com
FROM websites;

SELECT websites.site_name /* Author:


TechOnTheNet.com Purpose: To show a comment that
spans multiple lines in your SQL statement. */ FROM
websites;

SQL provides many built-in functions to perform operations on


data. These functions are useful while performing mathematical
calculations, string concatenations, sub-strings etc.

Types of Oracle SQL Functions


There are two types of functions in Oracle.
1.Single Row Functions:

Single row or Scalar functions


returns a value for every row that is processed in a
query.

2.Group Functions:

These functions group the rows of data based on the


values returned by the query.
The group functions are used to calculate aggregate
values like total or average, which return just one
total or one average value after processing a group of
rows.

Single Row or Scalar Functions


There are four types of single row functions.
1. Numeric Functions:

These are functions that accept numeric input and return numeric values.

2. Character or Text Functions:

These are functions that accept character input and can return both character and number
values.

3. Date Functions:

These are functions that take values that are of datatype DATE as input and return values
of datatype DATE, except for the MONTHS_BETWEEN function, which returns a
number.

4. Conversion Functions:

These are functions that help us to convert a value in one form to another form.
For Example: a null value into an actual value, or a value from one datatype to another
datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc.

What is a DUAL Table in Oracle?


This is a single row and single column dummy table provided by oracle. This is used to perform
mathematical calculations without using a table.
Select * from DUAL
Output:
DUMMY
------X

Select 777 * 888 from Dual


Output:
777 * 888
--------689976

Single Row - Numeric Functions


SELECT ROUND (unit_price) FROM product;

Function
Name
ABS (x)

CEIL (x)

FLOOR (x)

Return Value
Absolute value of the number
'x'

Function Name Examples


ABS (x)

ABS (1)
ABS (-1)

1
-1

CEIL (x)

CEIL (2.83)
CEIL (2.49)
CEIL (-1.6)

3
3
-1

FLOOR (x)

FLOOR (2.83)
FLOOR (2.49)
FLOOR (-1.6)

2
2
-2

TRUNC (x, y)

ROUND (125.456, 1)
ROUND (125.456, 0)
ROUND (124.456, -1)

125.4
125
120

ROUND (x, y)

TRUNC (140.234, 2)
TRUNC (-54, 1)
TRUNC (5.7)
TRUNC (142, -1)

140.23
54
5
140

Integer value that is Greater


than or equal to the number 'x'

Integer value that is Less than


or equal to the number 'x'

TRUNC (x, y)

Truncates value of number 'x'


up to 'y' decimal places

ROUND (x, y)

Rounded off value of the


number 'x' up to the number
'y' decimal places

Return Value

Single Row - Character or Text Functions

Character or text functions are used to manipulate


text strings.
They accept strings or characters as input and can
return both character and number values as output.
SELECT UPPER (product_name) FROM product;

Function Name

Return Value

LOWER (string_value)

All the letters in 'string_value' is converted to lowercase.

UPPER (string_value)

All the letters in 'string_value' is converted to uppercase.

INITCAP (string_value)

All the letters in 'string_value' is converted to mixed case.

LTRIM (string_value, trim_text)

All occurrences of 'trim_text' is removed from the left of string_value'.

RTRIM (string_value, trim_text)

All occurrences of 'trim_text' is removed from the right of string_value' .

TRIM (trim_text FROM string_value)

All occurrences of 'trim_text'from the left and right of string_value' , 'trim_text' can
also be only one character long .

SUBSTR (string_value, m, n)

Returns 'n' number of characters from 'string_value'starting from the 'm' position.

LENGTH (string_value)

Number of characters in'string_value' in returned.

LPAD (string_value, n, pad_value)

Returns 'string_value' left-padded with 'pad_value' . The length of the whole string
will be of 'n' characters.

RPAD (string_value, n, pad_value)

Returns 'string_value' right-padded with 'pad_value' . The length of the whole string
will be of 'n' characters.

Function Name

Examples

Return Value

LOWER(string_value)

LOWER('Good Morning')

good morning

UPPER(string_value)

UPPER('Good Morning')

GOOD MORNING

INITCAP(string_value)

INITCAP('GOOD MORNING')

Good Morning

LTRIM(string_value, trim_text)

LTRIM ('Good Morning', 'Good)

Morning

RTRIM (string_value, trim_text)

RTRIM ('Good Morning', ' Morning') Good

TRIM (trim_text FROM string_value)

TRIM ('o' FROM 'Good Morning')

Gd Mrning

SUBSTR (string_value, m, n)

SUBSTR ('Good Morning', 6, 7)

Morning

LENGTH (string_value)

LENGTH ('Good Morning')

12

LPAD (string_value, n, pad_value)

LPAD ('Good', 6, '*')

**Good

RPAD (string_value, n, pad_value)

RPAD ('Good', 6, '*')

Good**

Single Row - Date Functions

SELECT ADD_MONTHS ('16-Sep-81', 3) FROM product;

Function Name

Return Value

ADD_MONTHS (date, n)

Returns a date value after


adding 'n' months to the date'x'.

MONTHS_BETWEEN (x1, x2)

Returns the number of months


between dates x1 and x2.

ROUND (x, date_format)

Returns the date 'x' rounded off to


the nearest century, year, month,
date, hour, minute, or second as
specified by the'date_format'.

TRUNC (x, date_format)

Returns the date 'x' lesser than or


equal to the nearest century, year,
month, date, hour, minute, or
second as specified by the
'date_format'.

NEXT_DAY (x, week_day)

Returns the next date of


the'week_day' on or after the
date'x' occurs.

LAST_DAY (x)

It is used to determine the


number of days remaining in a
month from the date 'x'specified.

SYSDATE

Returns the systems current date


and time.

NEW_TIME (x, zone1, zone2)

Returns the date and time in


zone2 if date 'x' represents the
time in zone1.

Function Name

Examples

Return
Value

ADD_MONTHS ( )

ADD_MONTHS ('16-Sep-81',
3)

16-Dec-81

MONTHS_BETWEEN( )

MONTHS_BETWEEN ('16Sep-81', '16-Dec-81')

NEXT_DAY( )

NEXT_DAY ('01-Jun-08',
'Wednesday')

04-JUN-08

LAST_DAY( )

LAST_DAY ('01-Jun-08')

30-Jun-08

NEW_TIME( )

NEW_TIME ('01-Jun-08',
'IST', 'EST')

31-May-08

Single Row - Conversion Functions


SELECT NVL (null, 1) FROM product;

Function Name

TO_CHAR (x [,y])

Return Value

Examples

Return
Value

Converts Numeric and Date values to a


character string value. It cannot be used
for calculations since it is a string value.

TO_DATE (x [, date_format])

Converts a valid Numeric and Character


values to a Date value. Date is
formatted to the format specified
by 'date_format'.

NVL (x, y)

If 'x' is NULL, replace it


with 'y'. 'x'and 'y' must be of the same
datatype.

DECODE (a, b, c, d, e,
default_value)

Function
Name

Checks the value of 'a', if a = b, then


returns 'c'. If a = d, then returns 'e'.
Else, returns default_value.

TO_CHAR
(3000, '$9999')
TO_CHAR () TO_CHAR
(SYSDATE, 'Day,
Month YYYY')

$3000
Monday,
June
2008

TO_DATE ()

TO_DATE ('01Jun-08')

01-Jun08

NVL ()

NVL (null, 1)

Group Functions
Group functions are built-in SQL functions that operate on groups of
rows and return one value for the entire group.
COUNT()

Count returns the number of rows present in the table either based on some
condition or without condition.

FIRST()

First function returns first value of a selected column

LAST()

LAST return the return last value from selected column

MAX()

MAX function returns maximum value from selected column of the table.

MIN()

MIN function returns minimum value from a selected column of the table.

AVG()

Average returns average value after calculating from values in a numeric


column.

SUM()

SUM function returns total sum of a selected columns numeric values.

DISTINCT()

This function is used to select the distinct rows.

Group Function AVG() , SUM()

Group Function COUNT()

Group Function FIRST() , LAST()

Group Function MAX() , MIN()

A format model is a character literal that describes the format of datetime or numeric
data stored in a character string.
A format model does not change the internal representation of the value in the database.
For example:
The datetime format model for the string '17:45:29' is 'HH24:MI:SS'.
The datetime format model for the string '11-Nov-1999' is 'DD-Mon-YYYY'.

Number Format Models


You can use number format models in the following functions:

In the TO_CHAR function to translate a value of NUMBER, BINARY_FLOAT,


or BINARY_DOUBLE datatype toVARCHAR2 datatype
In the TO_NUMBER function to translate a value
of CHAR or VARCHAR2 datatype to NUMBER datatype
In the TO_BINARY_FLOAT and TO_BINARY_DOUBLE functions to
translate CHAR and VARCHAR2expressions
to BINARY_FLOAT or BINARY_DOUBLE values

All number format models cause the number to be rounded to the specified
number of significant digits.
If a value has more significant digits to the left of the decimal place than are
specified in the format,
then pound signs (#) replace the value.

If a positive NUMBER value is extremely large and cannot be represented in


the specified format,
then the infinity sign (~) replaces the value.

If a negative NUMBER value is extremely small and cannot be represented


by the specified format,
then the negative infinity sign (-~) replaces the value.

SELECT TO_CHAR(number, 'fmt') FROM DUAL;

Format

Description

Example

Number - (suppress leading/trailing zeros)


Includes a leading - for negative no's or one leading space for pos nos

9999=' 123

Number - including leading/trailing zeros

09999=00123
9999D00=123.00

Supress all leading /trailing blanks

FM9999=123

Include a leading $

$999=$123

Over-ride the '0' format and replace leading 0's with blank spaces ' '

B9999=' 123'

Include poth positive+ and negative - signs

FM

S999 =+123
999S =123+
PR999=<123>
PR999=' 123 '
999MI=123-

PR

Indicate SIGN with <brackets>

MI

Indicate Minus SIGN


Roman numeral
(upper or lower case)
Position of decimal point(.)

Group separator (often a comma) in desired position

9G999=1,234

,
.
C
L

Return a comma in desired position


Return a period in desired position
ISO currency symbol
Local currency symbol

9,999=1,234
99.99=12.34
C99
L99

Return a value using in scientific notation

9.9EEEE= 1.2E+02

Text Minimum
TM9(the default) or TME (Scientific notation)

TM9=12345
TME=1.2E+02

Returns in the specified position the Euro (or other) dual currency symbol.

U9999 = 1234

Return a value multiplied by 10n, wherenis the number of 9's after the V.
(valuewill be rounded up if necessary)

999V99= 123 x 1045

Returns the hexadecimal value of the specified number of digits.

select to_char('64','xx') from dual;

RN or rn

EEEE
TM

RN99=XI
99D99=12.34

Datetime Format Models


You can use datetime format models in the following
functions:

In the TO_* datetime functions to translate a character value


that is in a format other than the default format into a
datetime value.

The TO_* datetime functions


are TO_CHAR, TO_DATE, TO_TIMESTAMP,TO_TIMESTAMP_
TZ, TO_YMINTERVAL, and TO_DSINTERVAL.)

In the TO_CHAR function to translate a datetime value that is


in a format other than the default format into a string (for
example, to print the date from an application)
select TO_CHAR(SYSDATE,'DD-DAY-MONTH-YEAR') LONG_DATE FROM dual;
SELECT TO_CHAR(SYSDATE, 'DDTH')||' of '|| TO_CHAR(SYSDATE, 'Month')||', '||
TO_CHAR(SYSDATE, 'YYYY') "Ides" FROM DUAL;
Ides
----------------------03RD of April , 1998

DDL - CREATE, ALTER, DROP, RENAME, and TRUNCATE


DML - SELECT, INSERT, UPDATE, and DELETE
TCL - COMMIT, ROLLBACK, and SAVEPOINT
DCL - GRANT and REVOKE

SQL Commands Categories


Data Definition Language (DDL)

These SQL commands are used for creating, modifying, and dropping the
structure of database objects.
The commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.

Data Manipulation Language (DML)

These SQL commands are used for storing, retrieving, modifying, and deleting
data.
These commands are SELECT, INSERT, UPDATE, and DELETE.

Transaction Control Language (TCL)

These SQL commands are used for managing changes affecting the data.
These commands are COMMIT, ROLLBACK, and SAVEPOINT.

Data Control Language (DCL)

These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.

SQL is followed by unique set of rules and guidelines called Syntax.

All the SQL statements start with any of the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and the entire
statements end with a semicolon (;).

Important point to be noted is that SQL is case insensitive, which means


SELECT and select have same meaning in SQL statements.

DDL CREATE Command


create is a DDL command used to create a table or a database.
Creating a Database

To create a database in RDBMS, create command is uses. Following is the Syntax,


create database database-name;

Example for Creating Database


create database Test;

The above command will create a database named Test.

Creating a Table

create command is also used to create a table.


We can specify names and datatypes of various columns along.
Following is the Syntax,

create table table-name ( column-name1 datatype1, column-name2


datatype2, column-name3 datatype3, column-name4 datatype4 );

create table command will tell the database system to create a new table with
given table name and column information.

Example for creating Table


create table Student(id int, name varchar, age int);

The above command will create a new table Student in database system with 3
columns, namely id, name and age.

DDL ALTER Command


alter command is used for alteration of table structures.

There are various uses of alter command, such as,


to add a column to existing table
to rename any existing column
to change datatype of any column or to modify its size.
alter is also used to drop a column.

To Add Column to existing Table

Using alter command we can add a column to an existing table. Following is the Syntax,

alter table table-name add(column-name datatype);


Example for this,
alter table Student add(address char);

To Add Multiple Column to existing Table

The above command will add three new columns to the Student table

To Add column with Default Value

Using alter command we can even add multiple columns to an existing table. Following is the Syntax,

alter table table-name add(column-name1 datatype1, column-name2 datatype2, column-name3


datatype3);
Example for this,
alter table Student add(father-name varchar(60), mother-name varchar(60), dob date);

The above command will add a new column address to the Student table

alter command can add a new column to an existing table with default values. Following is the Syntax,

alter table table-name add(column-name1 datatype1 default data);


Example for this,
alter table Student add(dob date default '1-Jan-99');

The above command will add a new column with default value to the Student table

DDL ALTER Command cont


alter command is used for alteration of table structures.
To Modify an existing Column

alter command is used to modify data type of an existing column . Following is the Syntax,

alter table table-name modify(column-name datatype);


Example for this,
alter table Student modify(address varchar(30));

The above command will modify address column of the Student table

To Rename a column

Using alter command you can rename an existing column. Following is the Syntax,

alter table table-name rename old-column-name to column-name;


Example for this,
alter table Student rename address to Location;

The above command will rename address column to Location.

To Drop a Column

alter command is also used to drop columns also. Following is the Syntax,

alter table table-name drop(column-name);


Example for this,
alter table Student drop(address);

The above command will drop address column from the Student table

DDL - Truncate, Drop, Rename


truncate command
truncate command removes all records from a table.
But this command will not destroy the table's structure.
When we apply truncate command on a table its Primary key is initialized.
Following is its Syntax,
truncate table table-name;
Example explaining it.
truncate table Student;
The above query will delete all the records of Student table.
Note: truncate command is different from delete command. delete command will delete all the rows from a table
whereas truncate command re-initializes a table(like a newly created table).
drop command
drop query completely removes a table from database.
This command will also destroy the table structure. Following is its Syntax,
drop table table-name
Example explaining it.
drop table Student;
The above query will delete the Student table completely.
It can also be used on Databases.
Example, to drop a database,
drop database Test;
The above query will drop a database named Test from the system.
rename query
rename command is used to rename a table. Following is its Syntax,
rename table old-table-name to new-table-name
Example explaining it.
rename table Student to Student-record;
The above query will rename Student table to Student-record.

DML command
Data Manipulation Language (DML) statements are used for managing
data in database.
DML commands are not auto-committed.
It means changes made by DML command are not permanent to
database, it can be rolled back.
SELECT Query
Select query is used to retrieve data from a tables.
It is the most used SQL query.
We can retrieve complete tables, or partial by mentioning conditions using
WHERE clause.

INSERT command

Insert command is used to insert data into a table.

UPDATE command

Update command is used to update a row of a table.

DELETE command

Delete command is used to delete data from a table. Delete command can
also be used with condition to delete a particular row.

DML SELECT Query


Select query is used to retrieve data from a tables.
It is the most used SQL query.
We can retrieve complete tables, or partial by
mentioning conditions using WHERE clause.
A special character asterisk * is used to address all the
data(belonging to all columns) in a query.
SELECTstatement uses * character to retrieve all
records from a table.
WHERE clause

Where clause is used to specify condition while retriving


data from table.
Where clause is used mostly with
Select, Update and Delete query.
If condition specified by where clause is true then only the
result from table is returned.

DML INSERT Command

DML UPDATE Command

DML DELETE Command

TCL Commands
Transaction Control Language(TCL) commands are
used to manage transactions in database.
These are used to manage the changes made by
DML statements.
It also allows statements to be grouped together
into logical transactions.
Commit command
Rollback command
Savepoint command

DCL Commands
Data Control Language(DCL) is used to control
privilege in Database.
To perform any operation in the database, such as for
creating tables, sequences or views we need privileges.
Privileges are of two types,
System : creating session, table etc are all types of system
privilege.
Object : any command or query to work on tables comes
under object privilege.

DCL defines two commands,


Grant : Gives user access privileges to database.
Revoke : Take back permissions from user.

NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT

SQL Subquery
Subquery or Inner query or Nested query is a query in
a query.
SQL subquery is usually added in the WHERE Clause of the
SQL statement.
Most of the time, a subquery is used when you know how to
search for a value using a SELECT statement, but do not
know the exact value in the database.
Subqueries are an alternate way of returning data from
multiple tables.
Subqueries can be used with the following SQL statements
along with the comparison operators like =, <, >, >=, <= etc.

SELECT
INSERT
UPDATE
DELETE

SQL Subquery Examples

Usually, a subquery should return only one record, but sometimes it can also return multiple records when used with
operators LIKE IN, NOT IN in the where clause.
The query syntax would be like,

SELECT first_name, last_name, subject


FROM student_details
WHERE games NOT IN ('Cricket', 'Football');
Subquery output would be similar to:
first_name last_name
subject
-----------------------------------Shekar
Gowda
Badminton
Priya
Chandra
Chess

Lets consider the student_details table which we have used earlier. If you know the name of the students who are studying
science subject, you can get their id's by using this query below,

SELECT id, first_name


FROM student_details
WHERE first_name IN ('Rahul', 'Stephen');
but, if you do not know their names, then to get their id's you need to write the query in this manner,

SELECT id, first_name


FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Subquery Output:
id
first_name
--------------------100
Rahul102Stephen

SQL Subquery; INSERT Statement


Subquery can be used with INSERT statement to add rows of data from
one or more tables to another table. Lets try to group all the students
who study Maths in a table 'maths_group'.
INSERT INTO maths_group(id, name)
SELECT id, first_name || ' ' || last_name
FROM student_details WHERE subject= 'Maths'
SQL Subquery; SELECT Statement
A subquery can be used in the SELECT statement as follows. Lets use
the product and order_items table defined in the sql_joins section.
select p.product_name, p.supplier_name, (select order_id from
order_items where product_id = 101) as order_id from product p
where p.product_id = 101
product_name
supplier_name
order_id
--------- ------------------------- ----------Television
Onida
5103

Correlated Subquery
A query is called correlated subquery when both the
inner query and the outer query are interdependent.
For every row processed by the inner query, the outer
query is processed as well.
The inner query depends on the outer query before it
can be processed.

SELECT p.product_name FROM product p


WHERE p.product_id = (SELECT o.product_id
FROM order_items o
WHERE o.product_id = p.product_id);

S-ar putea să vă placă și