SlideShare a Scribd company logo
1 of 59
Download to read offline
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page1
Pondicherry University Community College
Department of Computer Science
Course : B.Voc [Software Development]
Year : II
Semester : III
Subject : Relational DataBase Management System
Unit III Study Material
Prepared by
D.GAYA
Assistant Professor,
Department of Computer Science,
Pondicherry University Community College,
Lawspet, Puducherry-08.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page2
Unit III
Basic SQL reports and commands – Datatypes and notations – String
functions – Date functions – Unions – Joins – DDL – DML – DCL.
Basic SQL reports and commands
Introduction to SQL
Structure Query Language(SQL) is a database query language used
for storing and managing data in Relational DBMS. SQL was developed at
IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s.
This was initially called SEQUEL(Structured English QUEry Language).
The main objective of SQL is to update, store, manipulate and retrieve
data stored in a relational database. Over the years SQL has undergone a lot
of changes. A lot of functionality such as support for XML, Triggers, Stored
Procedures, Regular Expression Matching, Recursive Queries, Standardised
Sequences and much more are added.
SQL is a standard language which is used to operate on database in
the form of queries. But MySQL is Open Source Database Management
System or simply a Database Software. MySQL will organize and then store
the data in its database.
Advantages:
• SQL has well-defined standards
• SQL is interactive in nature
• With the help of SQL, one can create multiple views
• Portability of code in SQL is a prominent feature
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page3
Data and Database
First and foremost we need to understand what is data. Data is a
collection of facts about the object of interest. A data about a student may
include information like name, unique id, age, address, education, etc. The
software has to store the data as it is required to answer a question e.g,
How many students are of age 25?
Database:
A database is an organized collection of data, which is generally
stored and accessed electronically from a computer system. In simple
words, we can say a database in a place where the data is stored. The best
analogy is the library. The library contains a huge collection of books of
different genres, here library is database and books are the data.
The database can be classified broadly into the following groups:
• Centralized database
• Distributed database
• NoSQL database
• Operational database
• Relational database
• Cloud database
• Object-oriented database
• Graph database
How to Create a database?
We use CREATE DATABASE statement to create a new database.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page4
Syntax:
CREATE DATABASE databasename;
Example:
CREATE DATABASE School;
So the database of name School will be created. If you want to delete
this database, you have to use the following syntax.
How to Drop a database?
Syntax:
DROP DATABASE databasename;
Example:
DROP DATABASE School;
The database with name School will be deleted.
Table
A table in a database is nothing but a collection of data in a tabular
way. It consists of columns and rows.
The table contains data elements also known as values using a model
of vertical columns and horizontal rows.
The point of intersection of a row and a column is called a CELL. A
table can have any number of rows but should have a specified number of
columns.
Comments in SQL
There are two ways in which you can comment in SQL as follows
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page5
• Single-Line Comments
• Multi-Line Comments
Single-Line Comments
The single line comment starts with two hyphens (–). So, any text
mentioned after (–), till the end of a single line will be ignored by the
compiler.
Example:
--Select all:
SELECT * FROM Employee_Info;
Multi-Line Comments
The Multi-line comments start with /* and end with */. So, any text
mentioned between /* and */ will be ignored by the compiler.
Example:
/*Select all the columns
of all the records
from the Employee_Info table:*/
SELECT * FROM Students;
SQL Commands
Structured Query Language(SQL) as we all know is the database
language by the use of which we can perform certain operations on the
existing database and also we can use this language to create a database.
SQL uses certain commands like Create, Drop, Insert etc. to carry out the
required tasks.
These SQL commands are mainly categorized into four categories as:
• DDL – Data Definition Language
• DQl – Data Query Language
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page6
• DML – Data Manipulation Language
• DCL – Data Control Language
DDL(Data Definition Language)
DDL or Data Definition Language actually consists of the SQL
commands that can be used to define the database schema. It simply deals
with descriptions of the database schema and is used to create and modify
the structure of database objects in the database.
Types DDL commands:
• CREATE – is used to create the database or its objects (like
table, index, function, views, store procedure and triggers).
• DROP – is used to delete objects from the database.
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table,
including all spaces allocated for the records are removed.
• COMMENT–is used to add comments to the data dictionary.
• RENAME –is used to rename an object existing in the database.
DQL (Data Query Language) :
DML statements are used for performing queries on the data within
schema objects. The purpose of DQL Command is to get some schema
relation based on the query passed to it.
Types of DQL:
SELECT – is used to retrieve data from the a database.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page7
DML(Data Manipulation Language)
The SQL commands that deals with the manipulation of data present
in the database belong to DML or Data Manipulation Language and this
includes most of the SQL statements.
Types of DML
• INSERT – is used to insert data into a table.
• UPDATE – is used to update existing data within a table.
• DELETE – is used to delete records from a database table.
DCL(Data Control Language)
DCL includes commands such as GRANT and REVOKE which mainly
deals with the rights, permissions and other controls of the database
system.
Types of DCL commands
• GRANT-gives user’s access privileges to database.
• REVOKE-withdraw user’s access privileges given by using the
GRANT command.
TCL(transaction Control Language)
TCL commands deals with the transaction within the database.
Types of TCL commands:
• COMMIT– commits a Transaction.
• ROLLBACK– rollbacks a transaction in case of any error occurs.
• SAVEPOINT–sets a savepoint within a transaction.
• SET TRANSACTION–specify characteristics for the transaction.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page8
SQL Data Types
SQL Data Type is an attribute that specifies the type of data of any
object. Each column, variable and expression has a related data type in SQL.
You can use these data types while creating your tables. You can choose a
data type for a table column based on your requirement.
Binary Data Types
Store raw-byte data, such as IP addresses, up to 65000 bytes. Data
types BINARY and BINARY VARYING (VARBINARY) are collectively
referred to as binary string types and the values of binary string types are
referred to as binary strings. A binary string is a sequence of octets or
bytes.
BYTEA and RAW are synonyms for VARBINARY.
Syntax
• BINARY
• VARBINARY
Parameters
length | max-length Specifies the length of the string or column width, in
bytes (octets).
Binary Operators and Functions
Binary operators &, ~, | and # have special behaviour for binary data
types, as described in Bitwise Operators.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page9
The following aggregate functions are supported for binary data
types:
• BIT_AND
• BIT_OR
• BIT_XOR
• MAX
• MIN
BINARY and VARBINARY Data Types
BINARY and VARBINARY data types have the following attributes:
BINARY
A fixed-width string of length bytes, where the number of bytes is
declared as an optional specifier to the type. If length is omitted, the default
is 1. Where necessary, values are right-extended to the full width of the
column with the zero byte.
Example:
=> SELECT TO_HEX('ab'::BINARY(4));
to_hex
----------
61620000
VARBINARY:
A variable-width string up to a length of max-length bytes, where the
maximum number of bytes is declared as an optional specifier to the type.
The default is the default attribute size, which is 80, and the maximum
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page10
length is 65000 bytes. VARBINARY values are not extended to the full
width of the column.
Example:
=> SELECT TO_HEX('ab'::VARBINARY(4));
to_hex
--------
6162
Binary Versus Character Data Types
Binary data types BINARY and VARBINARY are similar to character
data types CHAR and VARCHAR, respectively. They differ as follows:
• Binary data types contain byte strings—a sequence of octets or bytes.
• Character data types contain character strings (text).
• The lengths of binary data types are measured in bytes, while
character data types are measured in characters.
Examples
The following example
shows VARBINARY HEX_TO_BINARY(VARCHAR) and VARCHAR TO_HEX(V
ARBINARY) usage.
Table t and its projection are created with binary columns:
=> CREATE TABLE t (c BINARY(1));
=> CREATE PROJECTION t_p (c) AS SELECT c FROM t;
Insert minimum byte and maximum byte values:
=> INSERT INTO t values(HEX_TO_BINARY('0x00'));
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page11
=> INSERT INTO t values(HEX_TO_BINARY('0xFF'));
Binary values can then be formatted in hex on output using the TO_HEX
function:
=> SELECT TO_HEX(c) FROM t;
to_hex
--------
00
ff
(2 rows)
The BIT_AND, BIT_OR, and BIT_XORfunctions are interesting when
operating on a group of values. For example, create a sample table and
projections with binary columns:
The example that follows uses table t with a single column
of VARBINARY data type:
=> CREATE TABLE t ( c VARBINARY(2) );
=> INSERT INTO t values(HEX_TO_BINARY('0xFF00'));
=> INSERT INTO t values(HEX_TO_BINARY('0xFFFF'));
=> INSERT INTO t values(HEX_TO_BINARY('0xF00F'));
Query table t to see column c output:
=> SELECT TO_HEX(c) FROM t;
TO_HEX
--------
ff00
ffff
f00f
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page12
(3 rows)
Now issue the bitwise AND operation. Because these are aggregate
functions, an implicit GROUP BY operation is performed on results
using (ff00&(ffff)&f00f):
=> SELECT TO_HEX(BIT_AND(c)) FROM t;
TO_HEX
--------
f000
(1 row)
Issue the bitwise OR operation on (ff00|(ffff)|f00f):
=> SELECT TO_HEX(BIT_OR(c)) FROM t;
TO_HEX
--------
ffff
(1 row)
Issue the bitwise XOR operation on (ff00#(ffff)#f00f):
=> SELECT TO_HEX(BIT_XOR(c)) FROM t;
TO_HEX
--------
f0f0
(1 row)
Boolean Data Type
Vertica provides the standard SQL type BOOLEAN, which has two
states: true and false.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page13
The third state in SQL boolean logic is unknown, which is
represented by the NULL value.
Syntax
BOOLEAN
Parameters
Valid literal data values for input are:
TRUE 't' 'true' 'y' 'yes' '1' 1
FALSE 'f' 'false' 'n' 'no' '0' 0
Notes
• Do not confuse the BOOLEAN data type with Boolean Operators or
the Boolean-Predicate.
• The keywords TRUE and FALSE are preferred and are SQL-compliant.
• A Boolean value of NULL appears last (largest) in ascending order.
• All other values must be enclosed in single quotes.
• Boolean values are output using the letters t and f.
Character Data Types
Stores strings of letters, numbers, and symbols. Data
types CHARACTER (CHAR) and CHARACTER VARYING (VARCHAR) are
collectively referred to as character string types, and the values of
character string types are known as character strings.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page14
Character data can be stored as fixed-length or variable-length
strings. Fixed-length strings are right-extended with spaces on output;
variable-length strings are not extended.
String literals in SQL statements must be enclosed in single quotes.
Syntax
• CHAR
• VARCHAR
Parameters
octet-length Specifies the length of the string or column width, declared in
bytes (octets).
This parameter is optional.
CHAR Versus VARCHAR Data Types
The following differences apply to CHAR and VARCHAR data:
CHAR is conceptually a fixed-length, blank-padded string. Trailing
blanks (spaces) are removed on input, and are restored on output. The
default length is 1, and the maximum length is 65000 octets (bytes).
VARCHAR is a variable-length character data type. The default length
is 80, and the maximum length is 65000 octets. For string values longer
than 65000, use Long Data Types. Values can include trailing spaces.
Normally, you use VARCHAR for all of string data. Use CHAR when
you need fixed-width string output. For example, you can
use CHAR columns for data to be transferred to a legacy system that
requires fixed-width strings.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page15
Setting Maximum Length
When you define character columns, specify the maximum size of any
string to be stored in a column. For example, to store strings up to 24 octets
in length, use one of the following definitions:
• CHAR(24) /* fixed-length */
• VARCHAR(24) /* variable-length */
The maximum length parameter for VARCHAR and CHAR data types
refers to the number of octets that can be stored in that field, not the
number of characters (Unicode code points).
When using multibyte UTF-8 characters, the fields must be sized to
accommodate from 1 to 4 octets per character, depending on the data. If
the data loaded into a VARCHAR/CHAR column exceeds the specified
maximum size for that column, data is truncated on UTF-8 character
boundaries to fit within the specified size.
NULL Versus NUL
NULL and NUL differ as follows:
• NUL represents a character whose ASCII/Unicode code is 0,
sometimes qualified "ASCII NUL".
• NULL means no value, and is true of a field (column) or constant,
not of a character.
• CHAR, LONG VARCHAR, and VARCHAR string data types accept
ASCII NUL values.
• NULL appears last (largest) in ascending order.
The following example casts the input string containing NUL values to
VARCHAR:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page16
=> SELECT 'vert0ica'::CHARACTER VARYING AS VARCHAR;
VARCHAR
---------
vert0ica
(1 row)
The result contains 9 characters:
=> SELECT LENGTH('vert0ica'::CHARACTER VARYING);
length
--------
9
(1 row)
If you use an extended string literal, the length is 8 characters:
=> SELECT E'vert0ica'::CHARACTER VARYING AS VARCHAR;
VARCHAR
---------
vertica
(1 row)
=> SELECT LENGTH(E'vert0ica'::CHARACTER VARYING);
LENGTH
--------
8
(1 row)
Date/Time Data Types
Vertica supports the full set of SQL date and time data types. In most
cases, a combination
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page17
of DATE, DATETIME, SMALLDATETIME, TIME, TIMESTAMP WITHOUT
TIME ZONE, and TIMESTAMP WITH TIME ZONE, and INTERVAL provides a
complete range of date/time functionality required by any application.
In compliance with the SQL standard, Vertica also supports the TIME
WITH TIME ZONE data type.
The following table lists the characteristics about the date/time data types.
All these data types have a size of 8 bytes.
Name
Descriptio
n Low Value High Value
Resolutio
n
DATE Dates only
(no time
of day)
~ 25e+15 BC ~ 25e+15 AD 1 day
TIME [(p)] Time of
day only
(no date)
00:00:00.00 23:59:60.99999
9
1 μs
TIMETZ [(p)] Time of
day only,
with time
zone
00:00:00.00+1
4
23:59:59.99999
9-14
1 μs
TIMESTAMP
[(p)]
Both date
and time,
without
290279-12-22
19:59:05.2241
94 BC
294277-01-09
04:00:54.77580
6 AD
1 μs
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page18
Name
Descriptio
n Low Value High Value
Resolutio
n
time zone
TIMESTAMPT
Z [(p)]
Both date
and time,
with time
zone
290279-12-22
19:59:05.2241
94 BC UTC
294277-01-09
04:00:54.77580
6 AD UTC
1 μs
INTERVAL
[(p)]DAY TO
SECOND
Time
intervals
-106751991
days
04:00:54.7758
07
+-106751991
days
04:00:54.77580
7
1 μs
INTERVAL
[(p)]YEAR TO
MONTH
Time
intervals
~ -768e15 yrs ~ 768e15 yrs 1 month
Time Zone Abbreviations for Input
Vertica recognizes the files in /opt/vertica/share/timezonesets as
date/time input values and defines the default list of strings accepted in the
AT TIME ZONE zone parameter. The names are not necessarily used for
date/time output—output is driven by the official time zone abbreviations
associated with the currently selected time zone parameter setting.
Notes
In Vertica, TIME ZONE is a synonym for TIMEZONE.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page19
Vertica uses Julian dates for all date/time calculations, which can
correctly predict and calculate any date more recent than 4713 BC to far
into the future, based on the assumption that the average length of the year
is 365.2425 days.
• All date/time types are stored in eight bytes.
• A date/time value of NULL appears first (smallest) in ascending
order.
All the date/time data types accept the special literal value NOW to specify
the current date and time. For example:
=> SELECT TIMESTAMP 'NOW';
?column?
----------------------------
2012-03-13 11:42:22.766989
(1 row)
In Vertica, the INTERVAL data type is SQL:2008 compliant and allows
modifiers, called interval qualifiers, that divide the INTERVAL type into two
primary subtypes, DAY TO SECOND (the default) and YEAR TO MONTH.
You use the SET INTERVALSTYLE command to change
the intervalstyle run-time parameter for the current session.
Intervals are represented internally as some number of
microseconds and printed as up to 60 seconds, 60 minutes, 24 hours, 30
days, 12 months, and as many years as necessary. Fields can be positive or
negative.
Long Data Types
Store data up to 32000000 octets. Vertica supports two long data
types:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page20
• LONG VARBINARY: Variable-length raw-byte data, such as spatial
data. LONG VARBINARY values are not extended to the full width of
the column.
• LONG VARCHAR: Variable-length strings, such as log files and
unstructured data. LONG VARCHAR values are not extended to the
full width of the column.
Use LONG data types only when you need to store data greater than the
maximum size of VARBINARY and VARCHAR data types (65 KB). Long data
can include unstructured data, online comments or posts, or small log files.
Flex tables have a default LONG VARBINARY __raw__ column, with
a NOT NULL constraint. For more information, see Using Flex Tables.
Syntax
• LONG VARBINARY
• LONG VARCHAR
Parameters
max-length Specifies the length of the byte string or column width,
declared in bytes (octets).
Maximum value: 32000000
Default value: 1 MB
octet-length Specifies the length of the string or column width, declared in
bytes (octets).
Maximum value: 32000000
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page21
Default value: 1 MB
Optimized Performance
For optimal performance of LONG data types, Vertica recommends that
you:
• Use the LONG data types as storage only containers; Vertica supports
operations on the content of LONG data types, but does not support
all the operations that VARCHAR and VARBINARY take.
• Use VARBINARY and VARCHAR data types, instead of
their LONG counterparts, whenever
possible. VARBINARY and VARCHAR data types are more flexible and
have a wider range of operations.
• Do not sort, segment, or partition projections on LONG data type
columns.
• Do not add constraints, such as a primary key, to any LONG
VARBINARY or LONG VARCHAR columns.
• Do not join or aggregate any LONG data type columns.
Example
The following example creates a table user_comments with a LONG
VARCHAR column and inserts data into it:
=> CREATE TABLE user_comments
(id INTEGER,
username VARCHAR(200),
time_posted TIMESTAMP,
comment_text LONG VARCHAR(200000));
=> INSERT INTO user_comments VALUES
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page22
(1,
'User1',
TIMESTAMP '2013-06-25 12:47:32.62',
'The weather tomorrow will be cold and rainy and
then
on the day after, the sun will come and the
temperature
will rise dramatically.');
Numeric Data Types
Numeric data types are numbers stored in database columns. These
data types are typically grouped by:
Exact numeric types, values where the precision and scale need to be
preserved. The exact numeric types
are INTEGER, BIGINT, DECIMAL, NUMERIC, NUMBER, and MONEY.
Approximate numeric types, values where the precision needs to be
preserved and the scale can be floating. The approximate numeric types
are DOUBLE PRECISION, FLOAT, and REAL.
Implicit casts from INTEGER, FLOAT, and NUMERIC to VARCHAR are
not supported. If you need that functionality, write an explicit cast using
one of the following forms:
• CAST(numeric-expression AS data-type)
• numeric-expression::data-type
For example, you can cast a float to an integer as follows:
=> SELECT(FLOAT '123.5')::INT;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page23
?column?
----------
124
(1 row)
String-to-numeric data type conversions accept formats of quoted
constants for scientific notation, binary scaling, hexadecimal, and
combinations of numeric-type literals:
Scientific notation:
=> SELECT FLOAT '1e10';
?column?
-------------
10000000000
(1 row)
BINARY scaling:
=> SELECT NUMERIC '1p10';
?column?
----------
1024
(1 row)
Hexadecimal:
=> SELECT NUMERIC '0x0abc';
?column?
----------
2748
(1 row)
String functions
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page24
A string function is a function that takes a string value as an input
regardless of the data type of the returned value.
ASCII
The first SQL string function we will describe is ASCII(), which is a
scalar function that takes a string as input and returns the ASCII code of the
first character in this string. Note that ASCII stands for American Standard
Code for Information Interchange.
It’s a 7-bit character code where every single bit represents a unique
character which can be used for different purposes. You can find the whole
ASCII table in the following website: ASCII Code – The extended ASCII table.
Example:
SELECT ASCII('A'), ASCII('AB') , ASCII('B')
Result:
65, 65, 66
As shown in the result ASCII(‘A’) and ASCII(‘AB’) return the same result 65
CHARINDEX
CHARINDEX() is a scalar SQL string function used to return the index
of a specific string expression within a given string. CHARINDEX() has 2
required parameters which are the input string and character and one
optional parameter which is the starting index of the search operation (If
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page25
this argument is not specified or is less or equal than zero (0) value, the
search starts at the beginning of input string).
The function return type depends on the input string length; if it
is NVARCHAR(MAX) then it will return a BIGINT value else it will return
an INT value.
Example:
SELECT CHARINDEX('World','Hello World'),CHARINDEX('World','Hello
World',8)
Result:
7, 0
As shown in the example above, we searched for the
string World within Hello World and it returned 7, but when we specified
the start location as 8, it returned 0 since no occurrence is found after this
index.
CONCAT
CONCAT() is a scalar SQL string function that takes multiple strings
as input and returns on the string after concatenating all inputs. This
function can take a maximum 254 of inputs.
Example:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page26
SELECT CONCAT('Hello',' World')
Result:
Hello World
CONCAT_WS
CONCAT_WS() is very similar to CONCAT() function, but it allows the
user to specify a separator between the concatenated input strings. It can
be used to generate comma-separated values.
Example:
SELECT CONCAT_WS(',','United States','New York')
Result:
United States, New York
LEFT, RIGHT
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page27
LEFT() and RIGHT() functions are one of the most popular SQL string
functions. They are used to extract a specific number of characters from the
left-side or right-side of a string.
Example:
SELECT LEFT('Hello World',5) , RIGHT('Hello Wolrd',5)
Result:
Hello, World
LOWER, UPPER
LOWER() and UPPER() functions are another popular SQL string
functions that are used to change the character case of an input string.
LOWER() is used to change the letter case to a lower case and
UPPER() is used to change the case of the letters into upper case.
Example:
SELECT LOWER('Hello World') , UPPER('Hello World')
Result:
hello world, HELLO WORLD
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page28
LTRIM, RTRIM
The last functions we will illustrate in this article are LTRIM() and
RTRIM() function, which are used to remove additional spaces from the left
side or right side of an input string.
Example:
SELECT RTRIM('Hello ') , LTRIM(' World')
Result:
Hello, World
Unions
The SQL UNION clause/operator is used to combine the results of
two or more SELECT statements without returning any duplicate rows.
• To use this UNION clause, each SELECT statement must have
• The same number of columns selected
• The same number of column expressions
• The same data type and
• Have them in the same order
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page29
Syntax
The basic syntax of a UNION clause is as follows −
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here, the given condition could be any given expression based on your
requirement.
Example
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.
Table 2 − ORDERS Table is as follows.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page30
Now, let us join these two tables in our SELECT statement as follows −
This would produce the following result –
The UNION ALL Clause
The UNION ALL operator is used to combine the results of two
SELECT statements including duplicate rows.
The same rules that apply to the UNION clause will apply to the
UNION ALL operator.
Syntax
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page31
The basic syntax of the UNION ALL is as follows.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here, the given condition could be any given expression based on
your requirement.
Example
Consider the following two tables,
Table 1 − CUSTOMERS Table is as follows.
Table 2 − ORDERS table is as follows.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page32
Now, let us join these two tables in our SELECT statement as follows –
This would produce the following result –
There are two other clauses (i.e., operators), which are like the UNION
clause.
• SQL INTERSECT Clause − This is used to combine two SELECT
statements, but returns rows only from the first SELECT statement
that are identical to a row in the second SELECT statement.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page33
• SQL EXCEPT Clause − This combines two SELECT statements and
returns rows from the first SELECT statement that are not returned
by the second SELECT statement.
SQL Joins
SQL Joins allow you to collate two or more (sometimes just one table)
tables using common identifiers. Take the example of the above two tables
that you created - both the tables have id column in common.
For two tables to be joined there has to be something in common
between the two. Does this mean both the tables have to have at least one
column with the same name?
The tables you wish to join may not have a column with the same
name, but logically they should be the same, i.e., their data-types should be
the same. You cannot join two tables having a column with the same name
but different data-types.
Different types of SQL Joins
• INNER JOIN
o Self-join
• OUTER JOIN
o LEFT JOIN
o RIGHT JOIN
o FULL JOIN
• CROSS JOIN
• Semi-join and Anti-join
You can then create the following two tables with the specifications as
given -
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page34
• student_name (id, name)
• student_stream (id, stream)
Note that both the tables have id column in common. You can use the
following CREATE statements to create the tables -
For student_name -
CREATE TABLE student_name
(
id smallint,
name "char"[]
);
For student_stream -
CREATE TABLE student_stream
(
id smallint,
stream "char"[]
);
Let's now insert some records into the tables.
For student_name -
INSERT INTO student_name(id, name) VALUES (1, 'Sayak');
INSERT INTO student_name(id, name) VALUES (2, 'Alex');
INSERT INTO student_name(id, name) VALUES (3, 'Sameer');
INSERT INTO student_name(id, name) VALUES (4, 'Rick');
For student_stream -
INSERT INTO student_stream(id, stream) VALUES (1, 'CS');
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page35
INSERT INTO student_stream(id, stream) VALUES (1, 'IT');
INSERT INTO student_stream(id, stream) VALUES (2, 'ECE');
INSERT INTO student_stream(id, stream) VALUES (9, 'ECE');
The table entries should be like the following in case you executed
the above queries without changing anything -
You now have two simple tables ready.
INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as
long as the condition satisfies. This keyword will create the result-set by
combining all rows from both the tables where the condition satisfies i.e
value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page36
Take a look at the following diagram in order to understand INNER
JOIN visually -
In the above example, the column under consideration is
the id column. INNER JOIN will ignore rest of the columns for which the
values are not common in both the tables. Let's now execute a query in
PostgreSQL which would perform INNER JOIN between the two tables -
student_name and student_stream.
Upon executing the following query, you get the result as presented in the
above figure -
SELECT s1.id, s1.name, s2.stream
FROM student_name AS s1
INNER JOIN student_stream AS s2
ON s1.id = s2.id;
s1 and s2 are the aliases for the two tables. You used the ON keyword
along with INNER JOIN. The query can be executed using
the USING keyword as well -
SELECT s1.id, s1.name, s2.stream
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page37
FROM student_name AS s1
INNER JOIN student_stream AS s2
USING (id);
Self Join allows you to perform joining the same table. But where this
might be a good option? Suppose you have a table consisting of the
following columns -
• Country
• Continent
Now you want to enlist two countries in a way that their continents
are the same. The following figure should give you a sense of the expected
results -
OUTER JOIN
OUTER JOIN can further be divided into three types -
LEFT JOIN or Left Outer JOIN: The following diagram gives you a fair idea
of LEFT JOIN in SQL -
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page38
Note that unlike INNER JOIN, LEFT JOIN fetches you the records from
the left (w.r.t to the order you specify in your query) table for which there
was not any matching entry in the right table. This, in turn, tells you
that Sameer and Rick have not enrolled in any streams. The respective
query for this will be -
SELECT s1.id, s1.name, s2.stream
FROM student_name AS s1
LEFT JOIN student_stream AS s2
ON s1.id = s2.id;
RIGHT JOIN or Right Outer JOIN : RIGHT JOIN is exactly the opposite
of LEFT JOIN -
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page39
RIGHT JOIN can help you in finding the stream(s) for which no student has
enrolled. The query for this would be -
SELECT s1.id, s1.name, s2.stream
FROM student_name AS s1
RIGHT JOIN student_stream AS s2
ON s1.id = s2.id;
FULL JOIN or Full Outer JOIN: FULL JOIN lets you combine both LEFT
JOIN and RIGHT JOIN into a single compilation -
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page40
The respective query would be -
SELECT s1.id, s1.name, s2.stream
FROM student_name AS s1
FULL JOIN student_stream AS s2
ON s1.id = s2.id;
Note that you can execute all the above OUTER JOIN queries using
the USING keyword. Let's now study CROSS JOIN.
CROSS JOIN
CROSS JOIN is essentially the cartesian product between two
elements expressed using SQL. Suppose, you need to have all the
combinations possible in between two tables or even in a single table. You
will need CROSS JOIN for doing this. The following figure presents this
concept visually -
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page41
You already have two tables to test this out. In order to have all
possible combinations between the id columns of
the student_name and student_stream tables, you can execute the following
query -
SELECT s1.id, s2.id
FROM student_name AS s1
CROSS JOIN student_stream AS s2;
And you get the following result -
Semi-join and Anti-join
Let's consider the tables that you created earlier in the tutorial:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page42
Semi Join queries are generally executed in the form
of subqueries where rows are picked up from the first table with respect to
a condition (or a set of conditions) that is matched in the second table. Let's
assume the left table is the first table, and the right table is the second table.
Anti Join queries are the exact opposite. In Anti Join, rows are picked
up from the first table with respect to a condition (or a set of conditions)
that is not matched in the second table. Here is a diagram for you to
understand this visually -
The query for realizing the Semi Join would be -
select id, name
from student_name
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page43
where id IN
(select id from student_stream where stream
IN ('CS', 'IT', 'ECE'));
Similarly, the query that realizes Anti Join, in this case, would be -
select id, name
from student_name
where id NOT IN
(select id from student_stream where stream
IN ('CS', 'IT', 'ECE'));
DDL
DDL or Data Definition Language actually consists of the SQL
commands that can be used to define the database schema. It simply deals
with descriptions of the database schema and is used to create and modify
the structure of database objects in the database..
DDL commands
• CREATE – is used to create the database or its objects (like table,
index, function, views, store procedure and triggers).
• DROP – is used to delete objects from the database.
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table, including
all spaces allocated for the records are removed.
• COMMENT –is used to add comments to the data dictionary.
• RENAME –is used to rename an object existing in the database.
Create Command
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page44
A Database is defined as a structured set of data. So, in SQL the very
first step to store the data in a well-structured manner is to create a
database. The CREATE DATABASE statement is used to create a new
database in SQL.
There are two CREATE statements available in SQL:
• CREATE DATABASE
• CREATE TABLE
Syntax:
CREATE DATABASE database_name;
database_name: name of the database.
Example Query:
This query will create a new database in SQL and name the database
as my_database.
CREATE DATABASE my_database;
CREATE TABLE
To create a table in the database, a DBA must have certain
information in hand - the table name, column name, column data types, and
column sizes. All this information can be modified later using DDL
commands.
The CREATE TABLE statement is used to create a table in SQL. We
know that a table comprises of rows and columns. So while creating tables
we have to provide all the information to SQL about the names of the
columns, type of data to be stored in columns, size of the data etc.
Table Naming Conventions -
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page45
• The name you choose for a table must follow these standard rules:
• The name must begin with a letter A-Z or a-z
• Can contain numbers and underscores
• Can be in UPPER of lower case
• Can be up to 30 characters in length
• Cannot use the same name of another existing object in your schema
• Must not be a SQL reserved word
Syntax:
CREATE TABLE table_name
(
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);
table_name: name of the table.
column1 name of the first column.
data_type: Type of data we want to store in the particular column.
For example,int for integer data.
size: Size of the data we can store in a particular column. For example if for
a column we specify the data_type as int and size as 10 then this column
can store an integer
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page46
number of maximum 10 digits.
Example Query:
This query will create a table named Students with three columns,
ROLL_NO, NAME and SUBJECT.
CREATE TABLE Students
(
ROLL_NO int(3),
NAME varchar(20),
SUBJECT varchar(20),
);
DROP Command
The SQL DROP TABLE statement is used to remove a table definition
and all the data, indexes, triggers, constraints and permission specifications
for that table.
Syntax
The basic syntax of this DROP TABLE statement is as follows −
DROP TABLE table_name;
Example
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page47
This means that the CUSTOMERS table is available in the database, so
let us now drop it as shown below.
SQL> DROP TABLE CUSTOMERS;
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table, including
all spaces allocated for the records are removed.
• COMMENT –is used to add comments to the data dictionary.
• RENAME –is used to rename an object existing in the database.
ALTER Command
The SQL ALTER TABLE command is used to add, delete or modify
columns in an existing table. You should also use the ALTER TABLE
command to add and drop various constraints on an existing table.
Syntax
The basic syntax of an ALTER TABLE command to add a New
Column in an existing table is as follows.
ALTER TABLE table_name ADD column_name datatype;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page48
The basic syntax of an ALTER TABLE command to DROP COLUMN in
an existing table is as follows.
ALTER TABLE table_name DROP COLUMN column_name;
The basic syntax of an ALTER TABLE command to change the DATA
TYPE of a column in a table is as follows.
ALTER TABLE table_name MODIFY COLUMN column_name
datatype;
The basic syntax of an ALTER TABLE command to add a NOT
NULL constraint to a column in a table is as follows.
ALTER TABLE table_name MODIFY column_name datatype
NOT NULL;
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a
table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1,
column2...);
The basic syntax of an ALTER TABLE command to ADD CHECK
CONSTRAINT to a table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK
(CONDITION);
The basic syntax of an ALTER TABLE command to ADD PRIMARY
KEY constraint to a table is as follows.
Example
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page49
Following is the example to ADD a New Column to an existing table −
ALTER TABLE CUSTOMERS ADD SEX char(1);
Now, the CUSTOMERS table is changed and following would be
output from the SELECT statement.
Following is the example to DROP sex column from the existing table.
ALTER TABLE CUSTOMERS DROP SEX;
Now, the CUSTOMERS table is changed and following would be the
output from the SELECT statement.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page50
TRUNCATE Command
The SQL TRUNCATE TABLE command is used to delete complete data
from an existing table. You can also use DROP TABLE command to delete
complete table but it would remove complete table structure form the
database and you would need to re-create this table once again if you wish
you store some data.
Syntax
The basic syntax of a TRUNCATE TABLE command is as follows.
TRUNCATE TABLE table_name;
Example
Consider a CUSTOMERS table having the following records −
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page51
Following is the example of a Truncate command.
SQL > TRUNCATE TABLE CUSTOMERS;
Now, the CUSTOMERS table is truncated and the output from SELECT
statement will be as shown in the code block below −
SQL> SELECT * FROM CUSTOMERS;
Empty set (0.00 sec)
RENAME COMMAND
RENAME command is used to set a new name for any existing table.
Following is the syntax,
RENAME TABLE old_table_name to new_table_name
Here is an example explaining it.
RENAME TABLE student to students_info;
The above query will rename the table student to students_info
DML (Data Manipulation Language ) Commands:-
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page52
Data manipulation language is used to manipulate the
data. i.e. User can do multiple operations on the data by accessing it. The
data manipulation language is the set of instructions which results into the
required output. Using data manipulation language the data can be
accessed in the following ways:
1) Retrieval of information from the database
2) Adding or inserting new data in the table
3) Deletion of unwanted records or data
4) Modification of the information stored in the database
There are different commands of DML. Those are:-
1) Inserting of data into table:-
After creating table successfully, records can be entered. The insert
command is used to put the records into the table.
Syntax for inserting the values in the table is as follows:
SQL> insert into <table name> values (value1, value2, value3…);
The list of values means the values given one by one for each of
the attribute or may not be for some of the attributes. The values which are
number can written as it is but values which are characters and date types
are specified in ‘ ‘ i.e. In single quotation marks.
E.g.
SQL> insert into student values(101,’abc’,75,’Link road’);
The above statement allows user to enter one by one record by
putting the values along with insert command. To enter multiple values
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page53
continuously one by one we can specify the general command which can be
afterwards run by giving the ‘ / ‘.
e.g.
SQL> insert into student values(&rollno,’&studname’,&marks,’&addr’);
After giving this command the following output will come ,
Enter value for rollno:101
Enter value for name:xyz
Enter value for marks: 80
Enter value for addr: JM road
Old 1: insert into student values(&rollno,’&studname’,&marks,’&addr’);
New 1: insert into student values(102,’xyz’,80,’JM road’);
1 row created.
The statement ‘1 row created’ assures that the record has been
inserted into the table. To run the same command just press ‘ / ‘ on SQL
prompt as follows. You can use this ‘/ ‘to repeat the insertion of values as
many times as you want.
SQL> /
2)Select command:-
Select command is used to view the records from the table. To view
all the columns and all the rows ‘*’can be specified with the select
statement. The name of the table is required while specifying the select.
Syntax :-
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page54
Select * from <tablename>;
e.g.
SQL> select * from student;
Output:-
Select statement is very flexible. If user needs to view only certain
fields or columns, then by specifying those names of the columns in the
form of list, user can view the required output. The general form is as
follows:
Select column1, column2, column3…… column n from
<tablename>;
e.g.
SQL> select rollno, name, marks from student;
Output:-
ROLLNO NAME MARKS
101 ABC 75
ROLLNO NAME MARKS ADDR
101 ABC 75 LINK ROAD
102 XYZ 80 JM ROAD
103 PQR 67 N7
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page55
102 XYZ 80
103 PQR 67
3 rows selected.
To select particular row ‘where clause is used. This clause allows
user to put the condition. The rows or columns which satisfy the condition
will be displayed.
Syntax:-
Select<column1><column2><column3> from <tablename> where
condition;
e.g.
SQL> select * from student where marks=80;
ROLLNO NAME MARKS ADDR
102 XYZ 80 JM ROAD
3)Update the table:-
The tables can be updated using the set clause. Either all rows will be
updated or modified or selected rows can be updated using the where
clause. The set clause is used to define the modifications of a particular
column.
The syntax of update command is:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page56
Update<table name>set
<columnname>=<expression>,<columnname>=<expression>;
e.g.
SQL> update student set marks= 85;
3 rows updated.
SQL> select * from student;
Output:-
4 )Delete operation:-
The delete operation can be performed on the table to remove
or delete the particular records or even all records.
Syntax:-
Delete from student where addr=N7;
1 row deleted
SQL> select * from student;
ROLLNO NAME MARKS ADDR
101 ABC 85 LINK ROAD
102 XYZ 85 JM ROAD
103 PQR 85 N7
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page57
Output:
ROLLNO NAME MARKS ADDR
101 ABC 75
LINK
ROAD
102 XYZ 80 JM ROAD
To delete all records from the table the following command is used.
SQL> delete from student;
3 rows deleted.
Data Control Language (DCL)
Data Control Language (DCL) with Examples in DBMS: A Data Control
Language (DCL) can be defined as a computer language that is used for
controlling privilege in the database. The privileges are required for
performing all the database operations, such as creating sequences, views
or tables. It is a part of the Structured Query Language.
Types of Privileges
There are two main types of privileges in the database:
• System Privileges
o System privileges are used for performing a particular type of
action on objects, such as cache groups, synonyms,
materialized views, tables, views, sequences, indexes,
replication schemes, and PL/SQL procedures & functions.
o This type of privileges can only be granted or revoked by the
instance administrator or a user.
• Object Privileges
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page58
o Object privileges can be defined as the right for performing a
special type of action on objects like materialized views,
sequences, replication schemes, cache groups, synonyms,
tables, views, etc.
o This type of privilege cannot be revoked and the owner of the
object can grant object privileges.
There are two types of commands in the data control languages:
Grant Command
Grant Command is used for offering access or privileges to the users
on the objects of the database. Through this command, the users get access
to the privileges in the database.
The General Syntax for the Grant Command is mentioned below:
GRANT privilege_name
ON object_name
TO {user_name I PUBLIC I role_name}
[WITH GRANT OPTION];
For Example
GRANT ALL ON workers
TO MNO;
[WITH GRANT OPTION]
In the given example, the permission to view and modify the details in the
‘workers table’ has been given to the user MNO.
Revoke Command
The main purpose of the revoke command is canceling the previously
denied or granted permissions. Through the revoke command, the access
to the given privileges can be withdrawn. In simple words, the permission
can be taken back from the user with this command.
The general syntax for the revoke command is mentioned below:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page59
REVOKE<privilege list>
ON <relation name or view name>
From <user name>
For Example
REVOKE UPDATE
ON worker
FROM MNO;
Differences between the Grant and Revoke Command
Grant Command Revoke Command
A user is allowed to perform some
particular activities on the database by
using Grant Command.
A user is disallowed to performing
some particular activities by using the
revoke command.
The access to privileges for database
objects is granted to the other users.
The access to privileges for database
objects that is granted previously to the
users can be revoked.

More Related Content

What's hot

Week 4 The Relational Data Model & The Entity Relationship Data Model
Week 4 The Relational Data Model & The Entity Relationship Data ModelWeek 4 The Relational Data Model & The Entity Relationship Data Model
Week 4 The Relational Data Model & The Entity Relationship Data Modeloudesign
 
L7 data model and dbms architecture
L7  data model and dbms architectureL7  data model and dbms architecture
L7 data model and dbms architectureRushdi Shams
 
Chapter-2 Database System Concepts and Architecture
Chapter-2 Database System Concepts and ArchitectureChapter-2 Database System Concepts and Architecture
Chapter-2 Database System Concepts and ArchitectureKunal Anand
 
Object-Relational Database Systems(ORDBMSs)
Object-Relational Database Systems(ORDBMSs)Object-Relational Database Systems(ORDBMSs)
Object-Relational Database Systems(ORDBMSs)Sahan Walpitagamage
 
Relational Database Design
Relational Database DesignRelational Database Design
Relational Database DesignArchit Saxena
 
Week 3 Classification of Database Management Systems & Data Modeling
Week 3 Classification of Database Management Systems & Data ModelingWeek 3 Classification of Database Management Systems & Data Modeling
Week 3 Classification of Database Management Systems & Data Modelingoudesign
 
What is data model? And types.
What is data model? And types.What is data model? And types.
What is data model? And types.774477
 
Relational database revised
Relational database revisedRelational database revised
Relational database revisedmnodalo
 
Bca examination 2015 dbms
Bca examination 2015 dbmsBca examination 2015 dbms
Bca examination 2015 dbmsAnjaan Gajendra
 
Database Design
Database DesignDatabase Design
Database Designlearnt
 
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtapOverview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtapVikas Jagtap
 
Lesson 2 network database system
Lesson 2 network database systemLesson 2 network database system
Lesson 2 network database systemGiO Friginal
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersAbdul Rahman Sherzad
 

What's hot (20)

Week 4 The Relational Data Model & The Entity Relationship Data Model
Week 4 The Relational Data Model & The Entity Relationship Data ModelWeek 4 The Relational Data Model & The Entity Relationship Data Model
Week 4 The Relational Data Model & The Entity Relationship Data Model
 
L7 data model and dbms architecture
L7  data model and dbms architectureL7  data model and dbms architecture
L7 data model and dbms architecture
 
Chapter-2 Database System Concepts and Architecture
Chapter-2 Database System Concepts and ArchitectureChapter-2 Database System Concepts and Architecture
Chapter-2 Database System Concepts and Architecture
 
Object-Relational Database Systems(ORDBMSs)
Object-Relational Database Systems(ORDBMSs)Object-Relational Database Systems(ORDBMSs)
Object-Relational Database Systems(ORDBMSs)
 
Relational Database Design
Relational Database DesignRelational Database Design
Relational Database Design
 
Week 3 Classification of Database Management Systems & Data Modeling
Week 3 Classification of Database Management Systems & Data ModelingWeek 3 Classification of Database Management Systems & Data Modeling
Week 3 Classification of Database Management Systems & Data Modeling
 
Dbms Lecture Notes
Dbms Lecture NotesDbms Lecture Notes
Dbms Lecture Notes
 
Unit 02 dbms
Unit 02 dbmsUnit 02 dbms
Unit 02 dbms
 
What is data model? And types.
What is data model? And types.What is data model? And types.
What is data model? And types.
 
Database Lecture Notes
Database Lecture NotesDatabase Lecture Notes
Database Lecture Notes
 
Dbms notesization 2014
Dbms notesization 2014Dbms notesization 2014
Dbms notesization 2014
 
Relational database revised
Relational database revisedRelational database revised
Relational database revised
 
Bca examination 2015 dbms
Bca examination 2015 dbmsBca examination 2015 dbms
Bca examination 2015 dbms
 
Database Design
Database DesignDatabase Design
Database Design
 
Dbms viva questions
Dbms viva questionsDbms viva questions
Dbms viva questions
 
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtapOverview of Object-Oriented Concepts Characteristics by vikas jagtap
Overview of Object-Oriented Concepts Characteristics by vikas jagtap
 
Lesson 2 network database system
Lesson 2 network database systemLesson 2 network database system
Lesson 2 network database system
 
D B M S Animate
D B M S AnimateD B M S Animate
D B M S Animate
 
Dbms
DbmsDbms
Dbms
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 

Similar to Unit 3 rdbms study_materials-converted

Database system concepts
Database system conceptsDatabase system concepts
Database system conceptsKumar
 
Lecture 2 DATABASE LANGUAGE.pptx
Lecture 2 DATABASE LANGUAGE.pptxLecture 2 DATABASE LANGUAGE.pptx
Lecture 2 DATABASE LANGUAGE.pptxsazia7
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMSonia Pahuja
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
csedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfcsedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfSameerKhanPathan7
 
Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)Rakibul Hasan Pranto
 
Database-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxDatabase-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxAnmolThakur67
 
DBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL CommandsDBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL CommandsBHARATH KUMAR
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Vidyasagar Mundroy
 
Bank mangement system
Bank mangement systemBank mangement system
Bank mangement systemFaisalGhffar
 

Similar to Unit 3 rdbms study_materials-converted (20)

Dbms Basics
Dbms BasicsDbms Basics
Dbms Basics
 
Database system concepts
Database system conceptsDatabase system concepts
Database system concepts
 
Lecture 2 DATABASE LANGUAGE.pptx
Lecture 2 DATABASE LANGUAGE.pptxLecture 2 DATABASE LANGUAGE.pptx
Lecture 2 DATABASE LANGUAGE.pptx
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEM
 
Pl sql content
Pl sql contentPl sql content
Pl sql content
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
csedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfcsedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdf
 
Database Management System ppt
Database Management System pptDatabase Management System ppt
Database Management System ppt
 
Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)Islamic University Previous Year Question Solution 2018 (ADBMS)
Islamic University Previous Year Question Solution 2018 (ADBMS)
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
DATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEMDATABASE MANAGEMENT SYSTEM
DATABASE MANAGEMENT SYSTEM
 
Database-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxDatabase-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptx
 
DBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL CommandsDBMS languages/ Types of SQL Commands
DBMS languages/ Types of SQL Commands
 
Week 1
Week 1Week 1
Week 1
 
Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)
 
Bank mangement system
Bank mangement systemBank mangement system
Bank mangement system
 
sql-commands.pdf
sql-commands.pdfsql-commands.pdf
sql-commands.pdf
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql commands
Sql commandsSql commands
Sql commands
 

Recently uploaded

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 

Recently uploaded (20)

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

Unit 3 rdbms study_materials-converted

  • 1. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page1 Pondicherry University Community College Department of Computer Science Course : B.Voc [Software Development] Year : II Semester : III Subject : Relational DataBase Management System Unit III Study Material Prepared by D.GAYA Assistant Professor, Department of Computer Science, Pondicherry University Community College, Lawspet, Puducherry-08.
  • 2. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page2 Unit III Basic SQL reports and commands – Datatypes and notations – String functions – Date functions – Unions – Joins – DDL – DML – DCL. Basic SQL reports and commands Introduction to SQL Structure Query Language(SQL) is a database query language used for storing and managing data in Relational DBMS. SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This was initially called SEQUEL(Structured English QUEry Language). The main objective of SQL is to update, store, manipulate and retrieve data stored in a relational database. Over the years SQL has undergone a lot of changes. A lot of functionality such as support for XML, Triggers, Stored Procedures, Regular Expression Matching, Recursive Queries, Standardised Sequences and much more are added. SQL is a standard language which is used to operate on database in the form of queries. But MySQL is Open Source Database Management System or simply a Database Software. MySQL will organize and then store the data in its database. Advantages: • SQL has well-defined standards • SQL is interactive in nature • With the help of SQL, one can create multiple views • Portability of code in SQL is a prominent feature
  • 3. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page3 Data and Database First and foremost we need to understand what is data. Data is a collection of facts about the object of interest. A data about a student may include information like name, unique id, age, address, education, etc. The software has to store the data as it is required to answer a question e.g, How many students are of age 25? Database: A database is an organized collection of data, which is generally stored and accessed electronically from a computer system. In simple words, we can say a database in a place where the data is stored. The best analogy is the library. The library contains a huge collection of books of different genres, here library is database and books are the data. The database can be classified broadly into the following groups: • Centralized database • Distributed database • NoSQL database • Operational database • Relational database • Cloud database • Object-oriented database • Graph database How to Create a database? We use CREATE DATABASE statement to create a new database.
  • 4. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page4 Syntax: CREATE DATABASE databasename; Example: CREATE DATABASE School; So the database of name School will be created. If you want to delete this database, you have to use the following syntax. How to Drop a database? Syntax: DROP DATABASE databasename; Example: DROP DATABASE School; The database with name School will be deleted. Table A table in a database is nothing but a collection of data in a tabular way. It consists of columns and rows. The table contains data elements also known as values using a model of vertical columns and horizontal rows. The point of intersection of a row and a column is called a CELL. A table can have any number of rows but should have a specified number of columns. Comments in SQL There are two ways in which you can comment in SQL as follows
  • 5. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page5 • Single-Line Comments • Multi-Line Comments Single-Line Comments The single line comment starts with two hyphens (–). So, any text mentioned after (–), till the end of a single line will be ignored by the compiler. Example: --Select all: SELECT * FROM Employee_Info; Multi-Line Comments The Multi-line comments start with /* and end with */. So, any text mentioned between /* and */ will be ignored by the compiler. Example: /*Select all the columns of all the records from the Employee_Info table:*/ SELECT * FROM Students; SQL Commands Structured Query Language(SQL) as we all know is the database language by the use of which we can perform certain operations on the existing database and also we can use this language to create a database. SQL uses certain commands like Create, Drop, Insert etc. to carry out the required tasks. These SQL commands are mainly categorized into four categories as: • DDL – Data Definition Language • DQl – Data Query Language
  • 6. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page6 • DML – Data Manipulation Language • DCL – Data Control Language DDL(Data Definition Language) DDL or Data Definition Language actually consists of the SQL commands that can be used to define the database schema. It simply deals with descriptions of the database schema and is used to create and modify the structure of database objects in the database. Types DDL commands: • CREATE – is used to create the database or its objects (like table, index, function, views, store procedure and triggers). • DROP – is used to delete objects from the database. • ALTER-is used to alter the structure of the database. • TRUNCATE–is used to remove all records from a table, including all spaces allocated for the records are removed. • COMMENT–is used to add comments to the data dictionary. • RENAME –is used to rename an object existing in the database. DQL (Data Query Language) : DML statements are used for performing queries on the data within schema objects. The purpose of DQL Command is to get some schema relation based on the query passed to it. Types of DQL: SELECT – is used to retrieve data from the a database.
  • 7. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page7 DML(Data Manipulation Language) The SQL commands that deals with the manipulation of data present in the database belong to DML or Data Manipulation Language and this includes most of the SQL statements. Types of DML • INSERT – is used to insert data into a table. • UPDATE – is used to update existing data within a table. • DELETE – is used to delete records from a database table. DCL(Data Control Language) DCL includes commands such as GRANT and REVOKE which mainly deals with the rights, permissions and other controls of the database system. Types of DCL commands • GRANT-gives user’s access privileges to database. • REVOKE-withdraw user’s access privileges given by using the GRANT command. TCL(transaction Control Language) TCL commands deals with the transaction within the database. Types of TCL commands: • COMMIT– commits a Transaction. • ROLLBACK– rollbacks a transaction in case of any error occurs. • SAVEPOINT–sets a savepoint within a transaction. • SET TRANSACTION–specify characteristics for the transaction.
  • 8. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page8 SQL Data Types SQL Data Type is an attribute that specifies the type of data of any object. Each column, variable and expression has a related data type in SQL. You can use these data types while creating your tables. You can choose a data type for a table column based on your requirement. Binary Data Types Store raw-byte data, such as IP addresses, up to 65000 bytes. Data types BINARY and BINARY VARYING (VARBINARY) are collectively referred to as binary string types and the values of binary string types are referred to as binary strings. A binary string is a sequence of octets or bytes. BYTEA and RAW are synonyms for VARBINARY. Syntax • BINARY • VARBINARY Parameters length | max-length Specifies the length of the string or column width, in bytes (octets). Binary Operators and Functions Binary operators &, ~, | and # have special behaviour for binary data types, as described in Bitwise Operators.
  • 9. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page9 The following aggregate functions are supported for binary data types: • BIT_AND • BIT_OR • BIT_XOR • MAX • MIN BINARY and VARBINARY Data Types BINARY and VARBINARY data types have the following attributes: BINARY A fixed-width string of length bytes, where the number of bytes is declared as an optional specifier to the type. If length is omitted, the default is 1. Where necessary, values are right-extended to the full width of the column with the zero byte. Example: => SELECT TO_HEX('ab'::BINARY(4)); to_hex ---------- 61620000 VARBINARY: A variable-width string up to a length of max-length bytes, where the maximum number of bytes is declared as an optional specifier to the type. The default is the default attribute size, which is 80, and the maximum
  • 10. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page10 length is 65000 bytes. VARBINARY values are not extended to the full width of the column. Example: => SELECT TO_HEX('ab'::VARBINARY(4)); to_hex -------- 6162 Binary Versus Character Data Types Binary data types BINARY and VARBINARY are similar to character data types CHAR and VARCHAR, respectively. They differ as follows: • Binary data types contain byte strings—a sequence of octets or bytes. • Character data types contain character strings (text). • The lengths of binary data types are measured in bytes, while character data types are measured in characters. Examples The following example shows VARBINARY HEX_TO_BINARY(VARCHAR) and VARCHAR TO_HEX(V ARBINARY) usage. Table t and its projection are created with binary columns: => CREATE TABLE t (c BINARY(1)); => CREATE PROJECTION t_p (c) AS SELECT c FROM t; Insert minimum byte and maximum byte values: => INSERT INTO t values(HEX_TO_BINARY('0x00'));
  • 11. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page11 => INSERT INTO t values(HEX_TO_BINARY('0xFF')); Binary values can then be formatted in hex on output using the TO_HEX function: => SELECT TO_HEX(c) FROM t; to_hex -------- 00 ff (2 rows) The BIT_AND, BIT_OR, and BIT_XORfunctions are interesting when operating on a group of values. For example, create a sample table and projections with binary columns: The example that follows uses table t with a single column of VARBINARY data type: => CREATE TABLE t ( c VARBINARY(2) ); => INSERT INTO t values(HEX_TO_BINARY('0xFF00')); => INSERT INTO t values(HEX_TO_BINARY('0xFFFF')); => INSERT INTO t values(HEX_TO_BINARY('0xF00F')); Query table t to see column c output: => SELECT TO_HEX(c) FROM t; TO_HEX -------- ff00 ffff f00f
  • 12. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page12 (3 rows) Now issue the bitwise AND operation. Because these are aggregate functions, an implicit GROUP BY operation is performed on results using (ff00&(ffff)&f00f): => SELECT TO_HEX(BIT_AND(c)) FROM t; TO_HEX -------- f000 (1 row) Issue the bitwise OR operation on (ff00|(ffff)|f00f): => SELECT TO_HEX(BIT_OR(c)) FROM t; TO_HEX -------- ffff (1 row) Issue the bitwise XOR operation on (ff00#(ffff)#f00f): => SELECT TO_HEX(BIT_XOR(c)) FROM t; TO_HEX -------- f0f0 (1 row) Boolean Data Type Vertica provides the standard SQL type BOOLEAN, which has two states: true and false.
  • 13. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page13 The third state in SQL boolean logic is unknown, which is represented by the NULL value. Syntax BOOLEAN Parameters Valid literal data values for input are: TRUE 't' 'true' 'y' 'yes' '1' 1 FALSE 'f' 'false' 'n' 'no' '0' 0 Notes • Do not confuse the BOOLEAN data type with Boolean Operators or the Boolean-Predicate. • The keywords TRUE and FALSE are preferred and are SQL-compliant. • A Boolean value of NULL appears last (largest) in ascending order. • All other values must be enclosed in single quotes. • Boolean values are output using the letters t and f. Character Data Types Stores strings of letters, numbers, and symbols. Data types CHARACTER (CHAR) and CHARACTER VARYING (VARCHAR) are collectively referred to as character string types, and the values of character string types are known as character strings.
  • 14. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page14 Character data can be stored as fixed-length or variable-length strings. Fixed-length strings are right-extended with spaces on output; variable-length strings are not extended. String literals in SQL statements must be enclosed in single quotes. Syntax • CHAR • VARCHAR Parameters octet-length Specifies the length of the string or column width, declared in bytes (octets). This parameter is optional. CHAR Versus VARCHAR Data Types The following differences apply to CHAR and VARCHAR data: CHAR is conceptually a fixed-length, blank-padded string. Trailing blanks (spaces) are removed on input, and are restored on output. The default length is 1, and the maximum length is 65000 octets (bytes). VARCHAR is a variable-length character data type. The default length is 80, and the maximum length is 65000 octets. For string values longer than 65000, use Long Data Types. Values can include trailing spaces. Normally, you use VARCHAR for all of string data. Use CHAR when you need fixed-width string output. For example, you can use CHAR columns for data to be transferred to a legacy system that requires fixed-width strings.
  • 15. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page15 Setting Maximum Length When you define character columns, specify the maximum size of any string to be stored in a column. For example, to store strings up to 24 octets in length, use one of the following definitions: • CHAR(24) /* fixed-length */ • VARCHAR(24) /* variable-length */ The maximum length parameter for VARCHAR and CHAR data types refers to the number of octets that can be stored in that field, not the number of characters (Unicode code points). When using multibyte UTF-8 characters, the fields must be sized to accommodate from 1 to 4 octets per character, depending on the data. If the data loaded into a VARCHAR/CHAR column exceeds the specified maximum size for that column, data is truncated on UTF-8 character boundaries to fit within the specified size. NULL Versus NUL NULL and NUL differ as follows: • NUL represents a character whose ASCII/Unicode code is 0, sometimes qualified "ASCII NUL". • NULL means no value, and is true of a field (column) or constant, not of a character. • CHAR, LONG VARCHAR, and VARCHAR string data types accept ASCII NUL values. • NULL appears last (largest) in ascending order. The following example casts the input string containing NUL values to VARCHAR:
  • 16. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page16 => SELECT 'vert0ica'::CHARACTER VARYING AS VARCHAR; VARCHAR --------- vert0ica (1 row) The result contains 9 characters: => SELECT LENGTH('vert0ica'::CHARACTER VARYING); length -------- 9 (1 row) If you use an extended string literal, the length is 8 characters: => SELECT E'vert0ica'::CHARACTER VARYING AS VARCHAR; VARCHAR --------- vertica (1 row) => SELECT LENGTH(E'vert0ica'::CHARACTER VARYING); LENGTH -------- 8 (1 row) Date/Time Data Types Vertica supports the full set of SQL date and time data types. In most cases, a combination
  • 17. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page17 of DATE, DATETIME, SMALLDATETIME, TIME, TIMESTAMP WITHOUT TIME ZONE, and TIMESTAMP WITH TIME ZONE, and INTERVAL provides a complete range of date/time functionality required by any application. In compliance with the SQL standard, Vertica also supports the TIME WITH TIME ZONE data type. The following table lists the characteristics about the date/time data types. All these data types have a size of 8 bytes. Name Descriptio n Low Value High Value Resolutio n DATE Dates only (no time of day) ~ 25e+15 BC ~ 25e+15 AD 1 day TIME [(p)] Time of day only (no date) 00:00:00.00 23:59:60.99999 9 1 μs TIMETZ [(p)] Time of day only, with time zone 00:00:00.00+1 4 23:59:59.99999 9-14 1 μs TIMESTAMP [(p)] Both date and time, without 290279-12-22 19:59:05.2241 94 BC 294277-01-09 04:00:54.77580 6 AD 1 μs
  • 18. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page18 Name Descriptio n Low Value High Value Resolutio n time zone TIMESTAMPT Z [(p)] Both date and time, with time zone 290279-12-22 19:59:05.2241 94 BC UTC 294277-01-09 04:00:54.77580 6 AD UTC 1 μs INTERVAL [(p)]DAY TO SECOND Time intervals -106751991 days 04:00:54.7758 07 +-106751991 days 04:00:54.77580 7 1 μs INTERVAL [(p)]YEAR TO MONTH Time intervals ~ -768e15 yrs ~ 768e15 yrs 1 month Time Zone Abbreviations for Input Vertica recognizes the files in /opt/vertica/share/timezonesets as date/time input values and defines the default list of strings accepted in the AT TIME ZONE zone parameter. The names are not necessarily used for date/time output—output is driven by the official time zone abbreviations associated with the currently selected time zone parameter setting. Notes In Vertica, TIME ZONE is a synonym for TIMEZONE.
  • 19. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page19 Vertica uses Julian dates for all date/time calculations, which can correctly predict and calculate any date more recent than 4713 BC to far into the future, based on the assumption that the average length of the year is 365.2425 days. • All date/time types are stored in eight bytes. • A date/time value of NULL appears first (smallest) in ascending order. All the date/time data types accept the special literal value NOW to specify the current date and time. For example: => SELECT TIMESTAMP 'NOW'; ?column? ---------------------------- 2012-03-13 11:42:22.766989 (1 row) In Vertica, the INTERVAL data type is SQL:2008 compliant and allows modifiers, called interval qualifiers, that divide the INTERVAL type into two primary subtypes, DAY TO SECOND (the default) and YEAR TO MONTH. You use the SET INTERVALSTYLE command to change the intervalstyle run-time parameter for the current session. Intervals are represented internally as some number of microseconds and printed as up to 60 seconds, 60 minutes, 24 hours, 30 days, 12 months, and as many years as necessary. Fields can be positive or negative. Long Data Types Store data up to 32000000 octets. Vertica supports two long data types:
  • 20. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page20 • LONG VARBINARY: Variable-length raw-byte data, such as spatial data. LONG VARBINARY values are not extended to the full width of the column. • LONG VARCHAR: Variable-length strings, such as log files and unstructured data. LONG VARCHAR values are not extended to the full width of the column. Use LONG data types only when you need to store data greater than the maximum size of VARBINARY and VARCHAR data types (65 KB). Long data can include unstructured data, online comments or posts, or small log files. Flex tables have a default LONG VARBINARY __raw__ column, with a NOT NULL constraint. For more information, see Using Flex Tables. Syntax • LONG VARBINARY • LONG VARCHAR Parameters max-length Specifies the length of the byte string or column width, declared in bytes (octets). Maximum value: 32000000 Default value: 1 MB octet-length Specifies the length of the string or column width, declared in bytes (octets). Maximum value: 32000000
  • 21. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page21 Default value: 1 MB Optimized Performance For optimal performance of LONG data types, Vertica recommends that you: • Use the LONG data types as storage only containers; Vertica supports operations on the content of LONG data types, but does not support all the operations that VARCHAR and VARBINARY take. • Use VARBINARY and VARCHAR data types, instead of their LONG counterparts, whenever possible. VARBINARY and VARCHAR data types are more flexible and have a wider range of operations. • Do not sort, segment, or partition projections on LONG data type columns. • Do not add constraints, such as a primary key, to any LONG VARBINARY or LONG VARCHAR columns. • Do not join or aggregate any LONG data type columns. Example The following example creates a table user_comments with a LONG VARCHAR column and inserts data into it: => CREATE TABLE user_comments (id INTEGER, username VARCHAR(200), time_posted TIMESTAMP, comment_text LONG VARCHAR(200000)); => INSERT INTO user_comments VALUES
  • 22. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page22 (1, 'User1', TIMESTAMP '2013-06-25 12:47:32.62', 'The weather tomorrow will be cold and rainy and then on the day after, the sun will come and the temperature will rise dramatically.'); Numeric Data Types Numeric data types are numbers stored in database columns. These data types are typically grouped by: Exact numeric types, values where the precision and scale need to be preserved. The exact numeric types are INTEGER, BIGINT, DECIMAL, NUMERIC, NUMBER, and MONEY. Approximate numeric types, values where the precision needs to be preserved and the scale can be floating. The approximate numeric types are DOUBLE PRECISION, FLOAT, and REAL. Implicit casts from INTEGER, FLOAT, and NUMERIC to VARCHAR are not supported. If you need that functionality, write an explicit cast using one of the following forms: • CAST(numeric-expression AS data-type) • numeric-expression::data-type For example, you can cast a float to an integer as follows: => SELECT(FLOAT '123.5')::INT;
  • 23. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page23 ?column? ---------- 124 (1 row) String-to-numeric data type conversions accept formats of quoted constants for scientific notation, binary scaling, hexadecimal, and combinations of numeric-type literals: Scientific notation: => SELECT FLOAT '1e10'; ?column? ------------- 10000000000 (1 row) BINARY scaling: => SELECT NUMERIC '1p10'; ?column? ---------- 1024 (1 row) Hexadecimal: => SELECT NUMERIC '0x0abc'; ?column? ---------- 2748 (1 row) String functions
  • 24. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page24 A string function is a function that takes a string value as an input regardless of the data type of the returned value. ASCII The first SQL string function we will describe is ASCII(), which is a scalar function that takes a string as input and returns the ASCII code of the first character in this string. Note that ASCII stands for American Standard Code for Information Interchange. It’s a 7-bit character code where every single bit represents a unique character which can be used for different purposes. You can find the whole ASCII table in the following website: ASCII Code – The extended ASCII table. Example: SELECT ASCII('A'), ASCII('AB') , ASCII('B') Result: 65, 65, 66 As shown in the result ASCII(‘A’) and ASCII(‘AB’) return the same result 65 CHARINDEX CHARINDEX() is a scalar SQL string function used to return the index of a specific string expression within a given string. CHARINDEX() has 2 required parameters which are the input string and character and one optional parameter which is the starting index of the search operation (If
  • 25. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page25 this argument is not specified or is less or equal than zero (0) value, the search starts at the beginning of input string). The function return type depends on the input string length; if it is NVARCHAR(MAX) then it will return a BIGINT value else it will return an INT value. Example: SELECT CHARINDEX('World','Hello World'),CHARINDEX('World','Hello World',8) Result: 7, 0 As shown in the example above, we searched for the string World within Hello World and it returned 7, but when we specified the start location as 8, it returned 0 since no occurrence is found after this index. CONCAT CONCAT() is a scalar SQL string function that takes multiple strings as input and returns on the string after concatenating all inputs. This function can take a maximum 254 of inputs. Example:
  • 26. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page26 SELECT CONCAT('Hello',' World') Result: Hello World CONCAT_WS CONCAT_WS() is very similar to CONCAT() function, but it allows the user to specify a separator between the concatenated input strings. It can be used to generate comma-separated values. Example: SELECT CONCAT_WS(',','United States','New York') Result: United States, New York LEFT, RIGHT
  • 27. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page27 LEFT() and RIGHT() functions are one of the most popular SQL string functions. They are used to extract a specific number of characters from the left-side or right-side of a string. Example: SELECT LEFT('Hello World',5) , RIGHT('Hello Wolrd',5) Result: Hello, World LOWER, UPPER LOWER() and UPPER() functions are another popular SQL string functions that are used to change the character case of an input string. LOWER() is used to change the letter case to a lower case and UPPER() is used to change the case of the letters into upper case. Example: SELECT LOWER('Hello World') , UPPER('Hello World') Result: hello world, HELLO WORLD
  • 28. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page28 LTRIM, RTRIM The last functions we will illustrate in this article are LTRIM() and RTRIM() function, which are used to remove additional spaces from the left side or right side of an input string. Example: SELECT RTRIM('Hello ') , LTRIM(' World') Result: Hello, World Unions The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. • To use this UNION clause, each SELECT statement must have • The same number of columns selected • The same number of column expressions • The same data type and • Have them in the same order
  • 29. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page29 Syntax The basic syntax of a UNION clause is as follows − SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] Here, the given condition could be any given expression based on your requirement. Example Consider the following two tables. Table 1 − CUSTOMERS Table is as follows. Table 2 − ORDERS Table is as follows.
  • 30. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page30 Now, let us join these two tables in our SELECT statement as follows − This would produce the following result – The UNION ALL Clause The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. The same rules that apply to the UNION clause will apply to the UNION ALL operator. Syntax
  • 31. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page31 The basic syntax of the UNION ALL is as follows. SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION ALL SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] Here, the given condition could be any given expression based on your requirement. Example Consider the following two tables, Table 1 − CUSTOMERS Table is as follows. Table 2 − ORDERS table is as follows.
  • 32. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page32 Now, let us join these two tables in our SELECT statement as follows – This would produce the following result – There are two other clauses (i.e., operators), which are like the UNION clause. • SQL INTERSECT Clause − This is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement.
  • 33. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page33 • SQL EXCEPT Clause − This combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement. SQL Joins SQL Joins allow you to collate two or more (sometimes just one table) tables using common identifiers. Take the example of the above two tables that you created - both the tables have id column in common. For two tables to be joined there has to be something in common between the two. Does this mean both the tables have to have at least one column with the same name? The tables you wish to join may not have a column with the same name, but logically they should be the same, i.e., their data-types should be the same. You cannot join two tables having a column with the same name but different data-types. Different types of SQL Joins • INNER JOIN o Self-join • OUTER JOIN o LEFT JOIN o RIGHT JOIN o FULL JOIN • CROSS JOIN • Semi-join and Anti-join You can then create the following two tables with the specifications as given -
  • 34. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page34 • student_name (id, name) • student_stream (id, stream) Note that both the tables have id column in common. You can use the following CREATE statements to create the tables - For student_name - CREATE TABLE student_name ( id smallint, name "char"[] ); For student_stream - CREATE TABLE student_stream ( id smallint, stream "char"[] ); Let's now insert some records into the tables. For student_name - INSERT INTO student_name(id, name) VALUES (1, 'Sayak'); INSERT INTO student_name(id, name) VALUES (2, 'Alex'); INSERT INTO student_name(id, name) VALUES (3, 'Sameer'); INSERT INTO student_name(id, name) VALUES (4, 'Rick'); For student_stream - INSERT INTO student_stream(id, stream) VALUES (1, 'CS');
  • 35. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page35 INSERT INTO student_stream(id, stream) VALUES (1, 'IT'); INSERT INTO student_stream(id, stream) VALUES (2, 'ECE'); INSERT INTO student_stream(id, stream) VALUES (9, 'ECE'); The table entries should be like the following in case you executed the above queries without changing anything - You now have two simple tables ready. INNER JOIN The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be same. Syntax: SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 INNER JOIN table2 ON table1.matching_column = table2.matching_column; table1: First table. table2: Second table matching_column: Column common to both the tables.
  • 36. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page36 Take a look at the following diagram in order to understand INNER JOIN visually - In the above example, the column under consideration is the id column. INNER JOIN will ignore rest of the columns for which the values are not common in both the tables. Let's now execute a query in PostgreSQL which would perform INNER JOIN between the two tables - student_name and student_stream. Upon executing the following query, you get the result as presented in the above figure - SELECT s1.id, s1.name, s2.stream FROM student_name AS s1 INNER JOIN student_stream AS s2 ON s1.id = s2.id; s1 and s2 are the aliases for the two tables. You used the ON keyword along with INNER JOIN. The query can be executed using the USING keyword as well - SELECT s1.id, s1.name, s2.stream
  • 37. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page37 FROM student_name AS s1 INNER JOIN student_stream AS s2 USING (id); Self Join allows you to perform joining the same table. But where this might be a good option? Suppose you have a table consisting of the following columns - • Country • Continent Now you want to enlist two countries in a way that their continents are the same. The following figure should give you a sense of the expected results - OUTER JOIN OUTER JOIN can further be divided into three types - LEFT JOIN or Left Outer JOIN: The following diagram gives you a fair idea of LEFT JOIN in SQL -
  • 38. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page38 Note that unlike INNER JOIN, LEFT JOIN fetches you the records from the left (w.r.t to the order you specify in your query) table for which there was not any matching entry in the right table. This, in turn, tells you that Sameer and Rick have not enrolled in any streams. The respective query for this will be - SELECT s1.id, s1.name, s2.stream FROM student_name AS s1 LEFT JOIN student_stream AS s2 ON s1.id = s2.id; RIGHT JOIN or Right Outer JOIN : RIGHT JOIN is exactly the opposite of LEFT JOIN -
  • 39. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page39 RIGHT JOIN can help you in finding the stream(s) for which no student has enrolled. The query for this would be - SELECT s1.id, s1.name, s2.stream FROM student_name AS s1 RIGHT JOIN student_stream AS s2 ON s1.id = s2.id; FULL JOIN or Full Outer JOIN: FULL JOIN lets you combine both LEFT JOIN and RIGHT JOIN into a single compilation -
  • 40. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page40 The respective query would be - SELECT s1.id, s1.name, s2.stream FROM student_name AS s1 FULL JOIN student_stream AS s2 ON s1.id = s2.id; Note that you can execute all the above OUTER JOIN queries using the USING keyword. Let's now study CROSS JOIN. CROSS JOIN CROSS JOIN is essentially the cartesian product between two elements expressed using SQL. Suppose, you need to have all the combinations possible in between two tables or even in a single table. You will need CROSS JOIN for doing this. The following figure presents this concept visually -
  • 41. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page41 You already have two tables to test this out. In order to have all possible combinations between the id columns of the student_name and student_stream tables, you can execute the following query - SELECT s1.id, s2.id FROM student_name AS s1 CROSS JOIN student_stream AS s2; And you get the following result - Semi-join and Anti-join Let's consider the tables that you created earlier in the tutorial:
  • 42. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page42 Semi Join queries are generally executed in the form of subqueries where rows are picked up from the first table with respect to a condition (or a set of conditions) that is matched in the second table. Let's assume the left table is the first table, and the right table is the second table. Anti Join queries are the exact opposite. In Anti Join, rows are picked up from the first table with respect to a condition (or a set of conditions) that is not matched in the second table. Here is a diagram for you to understand this visually - The query for realizing the Semi Join would be - select id, name from student_name
  • 43. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page43 where id IN (select id from student_stream where stream IN ('CS', 'IT', 'ECE')); Similarly, the query that realizes Anti Join, in this case, would be - select id, name from student_name where id NOT IN (select id from student_stream where stream IN ('CS', 'IT', 'ECE')); DDL DDL or Data Definition Language actually consists of the SQL commands that can be used to define the database schema. It simply deals with descriptions of the database schema and is used to create and modify the structure of database objects in the database.. DDL commands • CREATE – is used to create the database or its objects (like table, index, function, views, store procedure and triggers). • DROP – is used to delete objects from the database. • ALTER-is used to alter the structure of the database. • TRUNCATE–is used to remove all records from a table, including all spaces allocated for the records are removed. • COMMENT –is used to add comments to the data dictionary. • RENAME –is used to rename an object existing in the database. Create Command
  • 44. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page44 A Database is defined as a structured set of data. So, in SQL the very first step to store the data in a well-structured manner is to create a database. The CREATE DATABASE statement is used to create a new database in SQL. There are two CREATE statements available in SQL: • CREATE DATABASE • CREATE TABLE Syntax: CREATE DATABASE database_name; database_name: name of the database. Example Query: This query will create a new database in SQL and name the database as my_database. CREATE DATABASE my_database; CREATE TABLE To create a table in the database, a DBA must have certain information in hand - the table name, column name, column data types, and column sizes. All this information can be modified later using DDL commands. The CREATE TABLE statement is used to create a table in SQL. We know that a table comprises of rows and columns. So while creating tables we have to provide all the information to SQL about the names of the columns, type of data to be stored in columns, size of the data etc. Table Naming Conventions -
  • 45. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page45 • The name you choose for a table must follow these standard rules: • The name must begin with a letter A-Z or a-z • Can contain numbers and underscores • Can be in UPPER of lower case • Can be up to 30 characters in length • Cannot use the same name of another existing object in your schema • Must not be a SQL reserved word Syntax: CREATE TABLE table_name ( column1 data_type(size), column2 data_type(size), column3 data_type(size), .... ); table_name: name of the table. column1 name of the first column. data_type: Type of data we want to store in the particular column. For example,int for integer data. size: Size of the data we can store in a particular column. For example if for a column we specify the data_type as int and size as 10 then this column can store an integer
  • 46. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page46 number of maximum 10 digits. Example Query: This query will create a table named Students with three columns, ROLL_NO, NAME and SUBJECT. CREATE TABLE Students ( ROLL_NO int(3), NAME varchar(20), SUBJECT varchar(20), ); DROP Command The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers, constraints and permission specifications for that table. Syntax The basic syntax of this DROP TABLE statement is as follows − DROP TABLE table_name; Example
  • 47. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page47 This means that the CUSTOMERS table is available in the database, so let us now drop it as shown below. SQL> DROP TABLE CUSTOMERS; • ALTER-is used to alter the structure of the database. • TRUNCATE–is used to remove all records from a table, including all spaces allocated for the records are removed. • COMMENT –is used to add comments to the data dictionary. • RENAME –is used to rename an object existing in the database. ALTER Command The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table. You should also use the ALTER TABLE command to add and drop various constraints on an existing table. Syntax The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype;
  • 48. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page48 The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows. ALTER TABLE table_name DROP COLUMN column_name; The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a table is as follows. ALTER TABLE table_name MODIFY COLUMN column_name datatype; The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows. ALTER TABLE table_name MODIFY column_name datatype NOT NULL; The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...); The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a table is as follows. ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION); The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a table is as follows. Example
  • 49. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page49 Following is the example to ADD a New Column to an existing table − ALTER TABLE CUSTOMERS ADD SEX char(1); Now, the CUSTOMERS table is changed and following would be output from the SELECT statement. Following is the example to DROP sex column from the existing table. ALTER TABLE CUSTOMERS DROP SEX; Now, the CUSTOMERS table is changed and following would be the output from the SELECT statement.
  • 50. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page50 TRUNCATE Command The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data. Syntax The basic syntax of a TRUNCATE TABLE command is as follows. TRUNCATE TABLE table_name; Example Consider a CUSTOMERS table having the following records −
  • 51. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page51 Following is the example of a Truncate command. SQL > TRUNCATE TABLE CUSTOMERS; Now, the CUSTOMERS table is truncated and the output from SELECT statement will be as shown in the code block below − SQL> SELECT * FROM CUSTOMERS; Empty set (0.00 sec) RENAME COMMAND RENAME command is used to set a new name for any existing table. Following is the syntax, RENAME TABLE old_table_name to new_table_name Here is an example explaining it. RENAME TABLE student to students_info; The above query will rename the table student to students_info DML (Data Manipulation Language ) Commands:-
  • 52. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page52 Data manipulation language is used to manipulate the data. i.e. User can do multiple operations on the data by accessing it. The data manipulation language is the set of instructions which results into the required output. Using data manipulation language the data can be accessed in the following ways: 1) Retrieval of information from the database 2) Adding or inserting new data in the table 3) Deletion of unwanted records or data 4) Modification of the information stored in the database There are different commands of DML. Those are:- 1) Inserting of data into table:- After creating table successfully, records can be entered. The insert command is used to put the records into the table. Syntax for inserting the values in the table is as follows: SQL> insert into <table name> values (value1, value2, value3…); The list of values means the values given one by one for each of the attribute or may not be for some of the attributes. The values which are number can written as it is but values which are characters and date types are specified in ‘ ‘ i.e. In single quotation marks. E.g. SQL> insert into student values(101,’abc’,75,’Link road’); The above statement allows user to enter one by one record by putting the values along with insert command. To enter multiple values
  • 53. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page53 continuously one by one we can specify the general command which can be afterwards run by giving the ‘ / ‘. e.g. SQL> insert into student values(&rollno,’&studname’,&marks,’&addr’); After giving this command the following output will come , Enter value for rollno:101 Enter value for name:xyz Enter value for marks: 80 Enter value for addr: JM road Old 1: insert into student values(&rollno,’&studname’,&marks,’&addr’); New 1: insert into student values(102,’xyz’,80,’JM road’); 1 row created. The statement ‘1 row created’ assures that the record has been inserted into the table. To run the same command just press ‘ / ‘ on SQL prompt as follows. You can use this ‘/ ‘to repeat the insertion of values as many times as you want. SQL> / 2)Select command:- Select command is used to view the records from the table. To view all the columns and all the rows ‘*’can be specified with the select statement. The name of the table is required while specifying the select. Syntax :-
  • 54. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page54 Select * from <tablename>; e.g. SQL> select * from student; Output:- Select statement is very flexible. If user needs to view only certain fields or columns, then by specifying those names of the columns in the form of list, user can view the required output. The general form is as follows: Select column1, column2, column3…… column n from <tablename>; e.g. SQL> select rollno, name, marks from student; Output:- ROLLNO NAME MARKS 101 ABC 75 ROLLNO NAME MARKS ADDR 101 ABC 75 LINK ROAD 102 XYZ 80 JM ROAD 103 PQR 67 N7
  • 55. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page55 102 XYZ 80 103 PQR 67 3 rows selected. To select particular row ‘where clause is used. This clause allows user to put the condition. The rows or columns which satisfy the condition will be displayed. Syntax:- Select<column1><column2><column3> from <tablename> where condition; e.g. SQL> select * from student where marks=80; ROLLNO NAME MARKS ADDR 102 XYZ 80 JM ROAD 3)Update the table:- The tables can be updated using the set clause. Either all rows will be updated or modified or selected rows can be updated using the where clause. The set clause is used to define the modifications of a particular column. The syntax of update command is:
  • 56. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page56 Update<table name>set <columnname>=<expression>,<columnname>=<expression>; e.g. SQL> update student set marks= 85; 3 rows updated. SQL> select * from student; Output:- 4 )Delete operation:- The delete operation can be performed on the table to remove or delete the particular records or even all records. Syntax:- Delete from student where addr=N7; 1 row deleted SQL> select * from student; ROLLNO NAME MARKS ADDR 101 ABC 85 LINK ROAD 102 XYZ 85 JM ROAD 103 PQR 85 N7
  • 57. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page57 Output: ROLLNO NAME MARKS ADDR 101 ABC 75 LINK ROAD 102 XYZ 80 JM ROAD To delete all records from the table the following command is used. SQL> delete from student; 3 rows deleted. Data Control Language (DCL) Data Control Language (DCL) with Examples in DBMS: A Data Control Language (DCL) can be defined as a computer language that is used for controlling privilege in the database. The privileges are required for performing all the database operations, such as creating sequences, views or tables. It is a part of the Structured Query Language. Types of Privileges There are two main types of privileges in the database: • System Privileges o System privileges are used for performing a particular type of action on objects, such as cache groups, synonyms, materialized views, tables, views, sequences, indexes, replication schemes, and PL/SQL procedures & functions. o This type of privileges can only be granted or revoked by the instance administrator or a user. • Object Privileges
  • 58. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page58 o Object privileges can be defined as the right for performing a special type of action on objects like materialized views, sequences, replication schemes, cache groups, synonyms, tables, views, etc. o This type of privilege cannot be revoked and the owner of the object can grant object privileges. There are two types of commands in the data control languages: Grant Command Grant Command is used for offering access or privileges to the users on the objects of the database. Through this command, the users get access to the privileges in the database. The General Syntax for the Grant Command is mentioned below: GRANT privilege_name ON object_name TO {user_name I PUBLIC I role_name} [WITH GRANT OPTION]; For Example GRANT ALL ON workers TO MNO; [WITH GRANT OPTION] In the given example, the permission to view and modify the details in the ‘workers table’ has been given to the user MNO. Revoke Command The main purpose of the revoke command is canceling the previously denied or granted permissions. Through the revoke command, the access to the given privileges can be withdrawn. In simple words, the permission can be taken back from the user with this command. The general syntax for the revoke command is mentioned below:
  • 59. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page59 REVOKE<privilege list> ON <relation name or view name> From <user name> For Example REVOKE UPDATE ON worker FROM MNO; Differences between the Grant and Revoke Command Grant Command Revoke Command A user is allowed to perform some particular activities on the database by using Grant Command. A user is disallowed to performing some particular activities by using the revoke command. The access to privileges for database objects is granted to the other users. The access to privileges for database objects that is granted previously to the users can be revoked.