SlideShare una empresa de Scribd logo
1 de 73
SACHIDANANDA M H,
Lecturer in Computer Science
Reference: NCERT Text Book and Internet sources
Introduction
• Structured Query Language helps to make practice on SQL
commands which provides immediate results.
• SQL is a language of database, it includes database creation,
deletion, fetching rows and modifying rows etc..
• SQL is an ANSI standard but there are many different versions
of the SQL language.
• SQL is database language for storing, manipulating and
retrieving data stored in relational database.
• All relational database management systems like MySQL, MS
Access, Oracle, Sybase, Informix and SQL server use SQL as
standard database language.
• MS SQL server using T-SQL.
• Oracle using PL/SQL.
• MS Access version of SQL is called JET SQL(native format) etc..
• Allows users to access data in relational database management
systems.
• Allows users to describe the data.
• Allows user to define the data in database and manipulate that data.
• Allows embedding within other languages using SQL modules,
libraries and pre-compilers.
• Allows users to create and drop databases and tables.
• Allows users to create view, stored procedure, functions in a
database.
• Allows users to set permissions on tables, procedures and views.
History
• 1970: Dr. E.F.Codd of IBM is known as father of relational
databases.
• 1974: SQL appeared.
• 1978:IBM worked to develop Codd’s ideas and released a
product named System/R.
• 1986: IBM developed first prototype of relational database and
standardized by ANSI. The first relational database was
released by Relational Software and its later becoming Oracle.
SQL Architecture
• When you are executing an SQL command for any RDBMS,
the system determines the best way to carry out your request
and SQL engine figure out how to interpret the task.
• There are various components included in the process. These
components are Query Dispatcher, Optimization Engines,
Classic Query Engine and SQL query engine etc..
• Classic query engine handles all non-SQL queries but SQL
query engine won’t handle logical files. These are the
components of SQL: MySQL, MS SQL server, Oracle, MS
Access.
SQL Commands
• The standard SQL commands to interact with relational
databases are CREATE, SELECT, INSERT, UPDATE,
DELETE and DROP. These commands can be grouped based
on their nature.
DDL-Data Definition Language
• DDL defines the conceptual schema providing a link between
the logical(the way the user views the data) and the physical
(the way in which the data is stored physically) structures of
the database.
• The logical structure of a database is called a schema. A
subschema is the way a specific application views the data
from the database.
Functions of DDL
• Defines the physical characteristics of each record, filled in the
record, field’s data type, field’s length. Field’s logical name
and also specify relationship among those records.
• Describes schema and subschema.
• Indicates the keys of records.
• Provides means for associating related records or fields.
• Provides data security measures.
• Provides for the logical and physical data independence.;
• Few of the basic commands of DDL are:
Command Description
CREATE Creates a new table, a view of table or other
object in database.
ALTER Modifies an existing database object, such as
a table.
DROP Deletes an entire table, a view of table or
other object in the database
DML-Data Manipulation Language
• Provides the data manipulation techniques like selection,
insertion, deletion, update, modification, replacement,
retrieval, sorting and display of data or records.
• Facilitates the use of relationship between the records.
• Enables the user and application program to be independent of
the physical data structures and database structures
maintenance by allowing to process data on a logical or
symbolic basis.
• Provides for independence of programming languages by
supporting several high level programming languages like
COBOL. PL/1 an C++.
• Few DML commands are:
DCL-Data Control Language
Command Description
INSERT Creates a record
UPDATE Modifies a record
DELETE Deletes a record
Command Description
GRANT Gives a privilege to user
REVOKE Takes back privileges granted from users
DQL-Data Query Language
Command Description
SELECT Retrieves certain records from one or more tables.
Data types in SQL
• SQL data type is an attribute that specifies type of data of any
object.
• Each column, variable and expression has related data type n
SQL.
• SQL servers offers six categories of data types for your use:
EXACT NUMERIC DATA TYPES
DATA TYPE FROM TO
int -2,147,483,648 2,147,483,647
numeric -10^38+1 10^38-1
Floating point numeric data types:
Date and Time data types:
DATA TYPE FROM TO
Float -179E+308 1.79E+308
Real -3.40E+38 3.40E+38
DATA TYPE FROM TO
datetime Jan 1, 1753 Dec 31, 9999
Date Stores a date like MARCH 26,
2014
Time Stores a time of day like
12:30PM
Note: Here, date time has 3.33 milliseconds accuracy whereas
small datetime has 1 minute accuracy.
Characters, Strings Data Types:
DATA TYPE keyword Description
Char char Maximum length of
8,000
characters(Fixed
length non-Unicode
characters)
Varchar varchar Maximum length of
8,000
characters(Variablel
ength non-Unicode
data)
Operator in SQL
• An operator is a reserved word or a character used primarily in
an SQL statement’s WHERE clause to perform operations(s),
such as comparisons and arithmetic operations.
 Arithmetic operators
 Comparisons Operators
 Logical operators
 Operators used to negate the conditions
Comparison operators
Logical operators
SQL arithmetic operators
SQL expression
• SQL EXPRESSIONs are like formulas and they are written in
query language.
• An expression is a combination of one or more values,
operators, and SQL functions that evaluate to a value.
• Syntax:
SELECT column1, column2, columnN
FROM table_name
WHERE [CONDITION|EXPRESSION];
SQL-Boolean expressions
• SQL Boolean expressions fetch the data on the basis of
matching single value.
• Syntax:
SELECT column1,column2,columnN
FROM table_name
WHERE SINGLE VALUE MATCHIING EXPRESSION;
Consider an employee table having the following records:
SQL>SELECT * FROM EMP WHERE age=45;
empid empname age address salary
333 Srinivas 45 Mangalore 25000
Numerical expression
• This expression is used to perform any mathematical operation
in any query. Following is the syntax:
SELECT numerical_expression as OPERATION_NAME
[FROM table_name
WHERE CONDITION];
Example:
SQL>SELECT (15+6) AS ADDITION
ADDITION
21
• There are several built-in functions like avg(), sum(), count()
etc.. to perform what is known as aggregate data calculations
against a table or a specific table column.
SQL> SELECT COUNT(*) AS “RECORDS” FROM EMP;
RECORDS
7
1 row inset(0.00 sec)
SQL Constraints
• Constraints are the rules enforced on data columns on table.
• These are used to limit the type of data that can go into a table.
• Constraints could be column level or table level. Column level
constraints are applied only to one column, whereas table level
constraints are applied to the whole table.
SQL Primary Key
• Primary key constraint uniquely identifies each record in a
database. A Primary Key must contain unique value and it
must not contain null value.
• Example using PRIMARY KEY constraint at Table Level:
CREATE table Student (s_id int PRIMARY KEY, Name
varchar(60) NOT NULL, Age int);
• Example using PRIMARY KEY constraint at Column Level
ALTER table Student add PRIMARY KEY (s_id);
Foreign Key Constraint
• FOREIGN KEY is used to relate two tables. FOREIGN KEY
constraint is also used to restrict actions that would destroy
links between tables. To understand FOREIGN KEY, let's see
it using two table.
• Example using FOREIGN KEY constraint at Table Level:
CREATE table Order_Detail(order_id int PRIMARY
KEY,order_name varchar(60) NOT NULL, c_id int
FOREIGN KEY REFERENCES Customer_Detail(c_id));
• In this query, c_id in table Order_Detail is made as foriegn
key, which is a reference of c_id column of Customer_Detail.
• Example using FOREIGN KEY constraint at Column Level:
ALTER table Order_Detail add FOREIGN KEY (c_id)
REFERENCES Customer_Detail(c_id);
NOT NULL Constraint
• NOT NULL constraint restricts a column from having a NULL
value.
• Once NOT NULL constraint is applied to a column, you cannot
pass a null value to that column.
• NOT NULL constraint is that it cannot be defined at table level.
• Example using NOT NULL constraint:
CREATE table Student(s_id int NOT NULL, Name varchar(60), Age
int);
The above query will declare that the s_id field of Student table
will not take NULL value
UNIQUE Key Constraint
• UNIQUE constraint ensures that a field or column will only
have unique values. A UNIQUE constraint field will not have
duplicate data.
• Example using UNIQUE constraint when creating a Table
(Table Level)
CREATE table Student(s_id int NOT NULL UNIQUE, Name
varchar(60), Age int);
The above query will declare that the s_id field of Student
table will only have unique values and wont take NULL value.
Example using UNIQUE constraint after Table is created
(Column Level):
ALTER table Student add UNIQUE(s_id);
• The above query specifies that s_id field of Student table will
only have unique value.
Check Constraint
• This constraint defines a business rule on a column. All the
rows must satisfy this rule.
• CHECK constraint is used to restrict the value of a column
between a range. It performs check on the values, before
storing them into the database.
Example using CHECK constraint at Table Level:
create table Student(s_id int NOT NULL CHECK(s_id > 0),Name
varchar(60) NOT NULL, Age int);
Example using CHECK constraint at Column Level:
ALTER table Student add CHECK(s_id > 0);
Implementation of SQL Commands
• Basic syntax of CREATE TABLE statement is as follows”
CREATE TABLE table_name(
column1 datataype1,
column2 datatype2,
:
:
columnN datatype,
PRIMARY KEY(one or more columns)
);
• CREATE TABLE is the keyword telling the database system
what you want to do.
• A copy of an existing table can be created using a combination
of the CREATE TABLE statement and the SELECT statement.
• You can verify if your table has been created successfully by
looking at the message displayed by the SQL server, otherwise
you can use DESC command as follows:
DESC EMPLOYEE;
Alter Statement
• The table can be modified or changed by using the Alter
command.
• ALTER TABLE table_name (columnname datatype(size);
• ALTER TABLE table_name ADD column_name datatype;
EX: SQL>alter table employee modify salary number(15,2);
Table altered.
ID NAME AGE ADDRESS SALARY
1 RAMESH 32 Shimoga 10000
2 KIRAN 25 Davangere 12000
3 KOUSHIK 23 Mangalare 11000
4 CHETHAN 34 Chitradurga 10500
ALTER TABLE CUSTOMERS ADD GENDER char(1);
ID NAME AGE ADDRESS SALARY GENDER
1 RAMESH 32 Shimoga 10000 NULL
2 KIRAN 25 Davangere 12000 NULL
3 KOUSHIK 23 Mangalare 11000 NULL
4 CHETHAN 34 Chitradurga 10500 NULL
DROP statement
• The SQL DROP TABLE statement is used to remove a table
definition and all data, indexes, triggers, constraints, and
permission specifications for that table.
• Basic syntax of DROP table statement:
DROP TABLE table_name;
Ex:
SQL>DROP TABLE Student;
Table dropped
Insert
• The SQL INSERT INTO Statement is used to add new rows of
data to a table in the database.
• Syntax is :
INSERT INTO TABLE_NAME (Column1,Column2….ColumnN
VALUES(value1,value2….valueN);
• Here you may not need to specify the column(s) name in the
SQL query if you are adding the values for all the columns of
the table.
Populate one table using another table
INSERT INTO first_table_name[(col1,col2…colN)]
SELECT col1,col2…colN
FROM second_table
[WHERE CONDITION];
Select
• SELECT statement is used to fetch the data from a database
table which returns data in the form of result table.
• These result tables are called result-sets.
• Syntax is:
SELECT column1,column2…..columnN FROM table_name;
• WHERE clause to filter the records and fetching only
necessary records.
• Syntax is:
SELECT column1,column2…columnN
FROM table_name
WHERE [condition];
• SELECT EmployeeID, FirstName, LastName, HireDate, City
FROM Employees WHERE City = 'London'
The SQL AND & OR Operators
• The AND operator displays a record if both the first condition
AND the second condition are true.
• The OR operator displays a record if either the first condition
OR the second condition is true.
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
SELECT * FROM Customers
WHERE City='Berlin'
OR City='München';
• Syntax for AND
SELECT column1,column2, columnN
FROM table_name
WHERE [CONDITION1] AND [CONDITION2];
• Syntax for OR
SELECT column1,column2, columnN
FROM table_name
WHERE [CONDITION1] OR [CONDITION2];
Update
• The SQL update Query is used to modifying the existing
records in a table.
• You can use WHERE clause with UPDATE query with
WHERE clause is as follows:
UPDATE table_name
SET column1=value1,column2=value2…columnN=valueN
WHERE[condition];
ID NAME ADDRESS SALARY
1 Sachin Tumkur 9000
2 Rahul Bangalore 10000
3 Sourav Mysore 11000
4 Anil Shimoga 12000
Example: Consider the above table Employee.
We can update ADDRESS for a customer whose ID is 2
SQL> UPDATE EMPLOYEE SET ADDRESS=‘Bengaluru’
WHERE ID=2;
The resultant table is:
ID NAME ADDRESS SALARY
1 Sachin Tumkur 9000
2 Rahul Bengaluru 10000
3 Sourav Mysore 11000
4 Anil Shimoga 12000
DELETE
• DELETE Query is used to delete the existing records from a
table.
• You can use WHERE clause with DELETE query to delete
selected rows, otherwise all the records should be deleted.
• The syntax of WHERE clause is:
DELETE FROM table_name
WHERE [condition];
Example: Consider the given table EMPLOYEE
ID NAME ADDRESS SALARY
1 Sachin Tumkur 9000
2 Rahul Bengaluru 10000
3 Sourav Mysore 11000
4 Anil Shimoga 12000
SQL> DELETE FROM EMPLOYEES WHERE ID=3;
ID NAME ADDRESS SALARY
1 Sachin Tumkur 9000
2 Rahul Bengaluru 10000
4 Anil Shimoga 12000
Order By Clause
• Order By clause is used to sort the data in ascending or
descending order, based on one or more columns.
• Some database sorts query results in ascending order by
default.
• Syntax is :
SELECT column_list
FROM table_name
[WHERE condition]
[ORDER BY column1,column2,…columnN [ASC|DESC] ;
• Consider the EMPLOYEE table having the following records:
SQL> select id, name, salary from employees order by salary;
id name salary
6 Sachin 15000
5 Rahul 16000
4 Sourav 18000
9 Anil 19000
GROUP BY
• The SQL GROUP BY clause is used in collaboration with the
SELECT statement to arrange identical data into groups.
• The GROUP BY clause follows the WHERE clause in a
SELECT statement and precedes the ORDER BY clause.
• Syntax is:
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
DISTINCT
• The SQL DISTINCT keyword is used in conjunction with
SELECT statement to eliminate all the duplicate records and
fetching only unique records.
• There may be a situation when you have multiple duplicate
records in a table. While fetching such records, it makes more
sense to fetch only unique records instead of fetching duplicate
records.
• Syntax:
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
JOINS
• The SQL Joins clause is used to combine records from two or
more tables in a database.
• A JOIN is a means for combining fields from two tables by
using values common to each.
• It is noticeable that the join is performed in the WHERE
clause. Several operators can be used to join tables, such as =,
<, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can
all be used to join tables. However, the most common operator
is the equal symbol.
SQL JOIN TYPES
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are
no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there
are no matches in the left table.
FULL JOIN: returns rows when there is a match in one of the
tables.
SELF JOIN: is used to join a table to itself as if the table were
two tables, temporarily renaming at least one table in the SQL
statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of
records from the two or more joined tables.
• Group functions are built-in functions that operate on groups
of rows and return one value for the entire group. These
functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT.
SQL COUNT() : This function returns the number of rows in the
table that satisfies the conditions specified in the WHERE
condition.
Example: SELECT COUNT(*) FROM employee
WHERE dept=‘Computer Science’;
SQL DISTINCT(): This function is used to select all the distinct
rows.
Example: SELECT DISTINCT dept FROM employee;
SQL MAX(): This function is used to get the maximum value
from a column.
Example: SELECT MAX(Salary) FROM EMPLOYEE;
SQL MIN(): This function is used to get the minimum value from
a column.
Example: SELECT MIN(Salary) FROM EMPLOYEE:
SQL AVG(): Used to get the average value of a numeric column.
Example: SELECT AVG(Salary) FROM EMPLOYEE:
SQL SUM(): Used to get the sum of the numeric problem.
Example: SELECT SUM(SALARY) FROM EMPLOYEE;
Creating Views:
• Database views are created using the CREATE VIEW
statement. Views can be created from a single table, multiple
tables, or another view.
• To create a view, a user must have the appropriate system
privilege according to the specific implementation.
• Syntax is :
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
The COMMIT command
• The COMMIT command is the transactional command used to
save changes invoked by a transaction to the database.
• COMMIT command saves all transactions to the database
since the last COMMIT or ROLLBACK command.
DCL commands are used to enforce database security in a
multiple server database environments.
GRANT
REVOKE
• GRANT is used to provide access or previleges on the database objects to the
users.
• Syntax is :
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
• privilege_name is the access right or privilege granted to the user.
Some of the access rights are ALL, EXECUTE, and SELECT.
• object_name is the name of an database object like TABLE, VIEW,
STORED PROC and SEQUENCE.
• user_name is the name of the user to whom an access right is being
granted.
• user_name is the name of the user to whom an access right is being
granted.
• PUBLIC is used to grant access rights to all users.
• ROLES are a set of privileges grouped together.
• WITH GRANT OPTION - allows a user to grant access rights
to other users.
SQL REVOKE Command:
• The REVOKE command removes user access rights or
privileges to the database objects.
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
Privileges and Roles:
• Privileges: Privileges defines the access rights provided to a
user on a database object. There are two types of privileges.
• 1) System privileges - This allows the user to CREATE,
ALTER, or DROP database objects.
2) Object privileges - This allows the user to EXECUTE,
SELECT, INSERT, UPDATE, or DELETE data from database
objects to which the privileges apply.
• Few CREATE system privileges are listed
below:
System Privileges Description
CREATE object
allows users to
create the specified
object in their own
schema.
CREATE ANY object
allows users to
create the specified
object in any
schema.
• The above rules also apply for ALTER and DROP system
privileges.
Object Privileges Description
INSERT
allows users to insert
rows into a table.
SELECT
allows users to select
data from a database
object.
UPDATE
allows user to update
data in a table.
EXECUTE
allows user to execute
a stored procedure or
a function.
System Role Privileges Granted to the Role
CONNECT
CREATE TABLE, CREATE VIEW, CREATE
SYNONYM, CREATE SEQUENCE, CREATE
SESSION etc.
RESOURCE
CREATE PROCEDURE, CREATE SEQUENCE,
CREATE TABLE, CREATE TRIGGER etc. The
primary usage of the RESOURCE role is to
restrict access to database objects.
DBA ALL SYSTEM PRIVILEGES
Oracle Built in Functions
• There are two types of functions in Oracle.
1) Single Row Functions: Single row or Scalar functions
return a value for every row that is processed in a query.
2) Group Functions: These functions group the rows of data
based on the values returned by the query.
• There are four types of single row functions. They are:
1) Numeric Functions: These are functions that accept
numeric input and return numeric values.
2) Character or Text Functions: These are functions that
accept character input and can return both character and
number values.
3) Date Functions: These are functions that take values that
are of datatype DATE as input and return values of datatype
DATE, except for the MONTHS_BETWEEN function, which
returns a number.
4) Conversion Functions: These are functions that help us to
convert a value in one form to another form. For Example: a
null value into an actual value, or a value from one datatype to
another datatype like NVL, TO_CHAR, TO_NUMBER,
TO_DATE etc.
What is a DUAL Table in Oracle?
• What is a DUAL Table in Oracle?
This is a single row and single column dummy table provided by
oracle. This is used to perform mathematical calculations without
using a table.
• Example: Select * from DUAL
Output:
DUMMY
-------
X
Select 777 * 888 from Dual;
Output:
777 * 888
---------
689976
1) Numeric Functions:
• Numeric functions are used to perform operations on numbers.
Function Name Return Value Function Name
ABS (x)
Absolute value of the
number 'x'
ABS (x)
CEIL (x)
Integer value that is
Greater than or equal to
the number 'x'
CEIL (x)
FLOOR (x)
Integer value that is Less
than or equal to the
number 'x'
FLOOR (x)
TRUNC (x, y)
Truncates value of number
'x' up to 'y' decimal places
TRUNC (x, y)
ROUND (x, y)
Rounded off value of the
number 'x' up to the ROUND (x, y)
Function Name Examples Return Value
ABS (x)
ABS (1)
ABS (-1)
1
-1
CEIL (x)
CEIL (2.83)
CEIL (2.49)
CEIL (-1.6)
3
3
-1
FLOOR (x)
FLOOR (2.83)
FLOOR (2.49)
FLOOR (-1.6)
2
2
-2
TRUNC (x, y)
ROUND (125.456,
1)
ROUND (125.456,
0)
ROUND (124.456, -
1)
125.4
125
120
ROUND (x, y)
TRUNC (140.234, 2)
TRUNC (-54, 1)
TRUNC (5.7)
TRUNC (142, -1)
140.23
54
5
140
2) Character or Text Functions:
• Character or text functions are used to manipulate text strings.
They accept strings or characters as input and can return both
character and number values as output.
Function Name Return Value
LOWER (string_value)
All the letters in 'string_value' is converted to
lowercase.
UPPER (string_value)
All the letters in 'string_value' is converted to
uppercase.
INITCAP (string_value)
All the letters in 'string_value' is converted to
mixed case.
LTRIM (string_value, trim_text)
All occurrences of 'trim_text' is removed from
the left of 'string_value'.
RTRIM (string_value, trim_text)
All occurrences of 'trim_text' is removed from
the right of 'string_value' .
TRIM (trim_text FROM string_value)
All occurrences of 'trim_text' from the left and
right of 'string_value' , 'trim_text' can also be
only one character long .
SUBSTR (string_value, m, n)
Returns 'n' number of characters from
'string_value' starting from the 'm' position.
Number of characters in 'string_value' in
DATE FUNCTIONS
• These are functions that take values that are of datatype DATE
as input and return values of datatypes DATE, except for the
MONTHS_BETWEEN function, which returns a number as
output.
Function Name Examples Return Value
ADD_MONTHS ( )
ADD_MONTHS ('16-Sep-
81', 3)
16-Dec-81
MONTHS_BETWEEN( )
MONTHS_BETWEEN
('16-Sep-81', '16-Dec-81')
3
NEXT_DAY( )
NEXT_DAY ('01-Jun-08',
'Wednesday')
04-JUN-08
LAST_DAY( ) LAST_DAY ('01-Jun-08') 30-Jun-08
NEW_TIME( )
NEW_TIME ('01-Jun-08',
'IST', 'EST')
31-May
Conversions Functions
• These are functions that help us to convert a value in one form
to another form. For Ex: a null value into an actual value, or a
value from one datatype to another datatype like NVL,
TO_CHAR, TO_NUMBER, TO_DATE.
Function Name Return Value
TO_CHAR (x [,y])
Converts Numeric and Date values to a
character string value. It cannot be used
for calculations since it is a string value.
TO_DATE (x [, date_format])
Converts a valid Numeric and Character
values to a Date value. Date is formatted
to the format specified by 'date_format'.
NVL (x, y)
If 'x' is NULL, replace it with 'y'. 'x' and 'y'
must be of the same datatype.
DECODE (a, b, c, d, e, default_value)
Checks the value of 'a', if a = b, then
returns 'c'. If a = d, then returns 'e'. Else,
returns default_value.
SQL Commands

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Sql commands
Sql commandsSql commands
Sql commands
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)ppt
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 

Similar a SQL Commands

SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptxSheethal Aji Mani
 
Lecture 2 sql {basics date type, constrains , integrity types etc.}
Lecture 2 sql {basics  date type, constrains , integrity types etc.}Lecture 2 sql {basics  date type, constrains , integrity types etc.}
Lecture 2 sql {basics date type, constrains , integrity types etc.}Shubham Shukla
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusChhom Karath
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slidesenosislearningcom
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)Nalina Kumari
 
Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptxStructure Query Language (SQL).pptx
Structure Query Language (SQL).pptxNalinaKumari2
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETEAbrar ali
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfstudy material
 
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptxFayChan8
 
Lesson-02 (1).pptx
Lesson-02 (1).pptxLesson-02 (1).pptx
Lesson-02 (1).pptxssuserc24e05
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfDraguClaudiu
 

Similar a SQL Commands (20)

SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 
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
 
Lecture 2 sql {basics date type, constrains , integrity types etc.}
Lecture 2 sql {basics  date type, constrains , integrity types etc.}Lecture 2 sql {basics  date type, constrains , integrity types etc.}
Lecture 2 sql {basics date type, constrains , integrity types etc.}
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*Plus
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slides
 
Structure query language (sql)
Structure query language (sql)Structure query language (sql)
Structure query language (sql)
 
SQL_NOTES.pdf
SQL_NOTES.pdfSQL_NOTES.pdf
SQL_NOTES.pdf
 
Structure Query Language (SQL).pptx
Structure Query Language (SQL).pptxStructure Query Language (SQL).pptx
Structure Query Language (SQL).pptx
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
UNIT2.ppt
UNIT2.pptUNIT2.ppt
UNIT2.ppt
 
DBMS UNIT 3
DBMS UNIT 3DBMS UNIT 3
DBMS UNIT 3
 
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
20190326165338_ISYS6508-PPT5-W5-S6-R0.pptx
 
Lesson-02 (1).pptx
Lesson-02 (1).pptxLesson-02 (1).pptx
Lesson-02 (1).pptx
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
Module02
Module02Module02
Module02
 

Último

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 

Último (20)

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

SQL Commands

  • 1. SACHIDANANDA M H, Lecturer in Computer Science Reference: NCERT Text Book and Internet sources
  • 2. Introduction • Structured Query Language helps to make practice on SQL commands which provides immediate results. • SQL is a language of database, it includes database creation, deletion, fetching rows and modifying rows etc.. • SQL is an ANSI standard but there are many different versions of the SQL language. • SQL is database language for storing, manipulating and retrieving data stored in relational database. • All relational database management systems like MySQL, MS Access, Oracle, Sybase, Informix and SQL server use SQL as standard database language.
  • 3. • MS SQL server using T-SQL. • Oracle using PL/SQL. • MS Access version of SQL is called JET SQL(native format) etc.. • Allows users to access data in relational database management systems. • Allows users to describe the data. • Allows user to define the data in database and manipulate that data. • Allows embedding within other languages using SQL modules, libraries and pre-compilers. • Allows users to create and drop databases and tables. • Allows users to create view, stored procedure, functions in a database. • Allows users to set permissions on tables, procedures and views.
  • 4. History • 1970: Dr. E.F.Codd of IBM is known as father of relational databases. • 1974: SQL appeared. • 1978:IBM worked to develop Codd’s ideas and released a product named System/R. • 1986: IBM developed first prototype of relational database and standardized by ANSI. The first relational database was released by Relational Software and its later becoming Oracle.
  • 6. • When you are executing an SQL command for any RDBMS, the system determines the best way to carry out your request and SQL engine figure out how to interpret the task. • There are various components included in the process. These components are Query Dispatcher, Optimization Engines, Classic Query Engine and SQL query engine etc.. • Classic query engine handles all non-SQL queries but SQL query engine won’t handle logical files. These are the components of SQL: MySQL, MS SQL server, Oracle, MS Access.
  • 7. SQL Commands • The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be grouped based on their nature. DDL-Data Definition Language • DDL defines the conceptual schema providing a link between the logical(the way the user views the data) and the physical (the way in which the data is stored physically) structures of the database. • The logical structure of a database is called a schema. A subschema is the way a specific application views the data from the database.
  • 8. Functions of DDL • Defines the physical characteristics of each record, filled in the record, field’s data type, field’s length. Field’s logical name and also specify relationship among those records. • Describes schema and subschema. • Indicates the keys of records. • Provides means for associating related records or fields. • Provides data security measures. • Provides for the logical and physical data independence.;
  • 9. • Few of the basic commands of DDL are: Command Description CREATE Creates a new table, a view of table or other object in database. ALTER Modifies an existing database object, such as a table. DROP Deletes an entire table, a view of table or other object in the database
  • 10. DML-Data Manipulation Language • Provides the data manipulation techniques like selection, insertion, deletion, update, modification, replacement, retrieval, sorting and display of data or records. • Facilitates the use of relationship between the records. • Enables the user and application program to be independent of the physical data structures and database structures maintenance by allowing to process data on a logical or symbolic basis. • Provides for independence of programming languages by supporting several high level programming languages like COBOL. PL/1 an C++.
  • 11. • Few DML commands are: DCL-Data Control Language Command Description INSERT Creates a record UPDATE Modifies a record DELETE Deletes a record Command Description GRANT Gives a privilege to user REVOKE Takes back privileges granted from users
  • 12. DQL-Data Query Language Command Description SELECT Retrieves certain records from one or more tables.
  • 13. Data types in SQL • SQL data type is an attribute that specifies type of data of any object. • Each column, variable and expression has related data type n SQL. • SQL servers offers six categories of data types for your use: EXACT NUMERIC DATA TYPES DATA TYPE FROM TO int -2,147,483,648 2,147,483,647 numeric -10^38+1 10^38-1
  • 14. Floating point numeric data types: Date and Time data types: DATA TYPE FROM TO Float -179E+308 1.79E+308 Real -3.40E+38 3.40E+38 DATA TYPE FROM TO datetime Jan 1, 1753 Dec 31, 9999 Date Stores a date like MARCH 26, 2014 Time Stores a time of day like 12:30PM
  • 15. Note: Here, date time has 3.33 milliseconds accuracy whereas small datetime has 1 minute accuracy. Characters, Strings Data Types: DATA TYPE keyword Description Char char Maximum length of 8,000 characters(Fixed length non-Unicode characters) Varchar varchar Maximum length of 8,000 characters(Variablel ength non-Unicode data)
  • 16. Operator in SQL • An operator is a reserved word or a character used primarily in an SQL statement’s WHERE clause to perform operations(s), such as comparisons and arithmetic operations.  Arithmetic operators  Comparisons Operators  Logical operators  Operators used to negate the conditions
  • 20. SQL expression • SQL EXPRESSIONs are like formulas and they are written in query language. • An expression is a combination of one or more values, operators, and SQL functions that evaluate to a value. • Syntax: SELECT column1, column2, columnN FROM table_name WHERE [CONDITION|EXPRESSION];
  • 21. SQL-Boolean expressions • SQL Boolean expressions fetch the data on the basis of matching single value. • Syntax: SELECT column1,column2,columnN FROM table_name WHERE SINGLE VALUE MATCHIING EXPRESSION;
  • 22. Consider an employee table having the following records: SQL>SELECT * FROM EMP WHERE age=45; empid empname age address salary 333 Srinivas 45 Mangalore 25000
  • 23. Numerical expression • This expression is used to perform any mathematical operation in any query. Following is the syntax: SELECT numerical_expression as OPERATION_NAME [FROM table_name WHERE CONDITION]; Example: SQL>SELECT (15+6) AS ADDITION ADDITION 21
  • 24. • There are several built-in functions like avg(), sum(), count() etc.. to perform what is known as aggregate data calculations against a table or a specific table column. SQL> SELECT COUNT(*) AS “RECORDS” FROM EMP; RECORDS 7 1 row inset(0.00 sec)
  • 25. SQL Constraints • Constraints are the rules enforced on data columns on table. • These are used to limit the type of data that can go into a table. • Constraints could be column level or table level. Column level constraints are applied only to one column, whereas table level constraints are applied to the whole table.
  • 26. SQL Primary Key • Primary key constraint uniquely identifies each record in a database. A Primary Key must contain unique value and it must not contain null value. • Example using PRIMARY KEY constraint at Table Level: CREATE table Student (s_id int PRIMARY KEY, Name varchar(60) NOT NULL, Age int); • Example using PRIMARY KEY constraint at Column Level ALTER table Student add PRIMARY KEY (s_id);
  • 27. Foreign Key Constraint • FOREIGN KEY is used to relate two tables. FOREIGN KEY constraint is also used to restrict actions that would destroy links between tables. To understand FOREIGN KEY, let's see it using two table. • Example using FOREIGN KEY constraint at Table Level: CREATE table Order_Detail(order_id int PRIMARY KEY,order_name varchar(60) NOT NULL, c_id int FOREIGN KEY REFERENCES Customer_Detail(c_id)); • In this query, c_id in table Order_Detail is made as foriegn key, which is a reference of c_id column of Customer_Detail.
  • 28. • Example using FOREIGN KEY constraint at Column Level: ALTER table Order_Detail add FOREIGN KEY (c_id) REFERENCES Customer_Detail(c_id); NOT NULL Constraint • NOT NULL constraint restricts a column from having a NULL value. • Once NOT NULL constraint is applied to a column, you cannot pass a null value to that column. • NOT NULL constraint is that it cannot be defined at table level. • Example using NOT NULL constraint: CREATE table Student(s_id int NOT NULL, Name varchar(60), Age int); The above query will declare that the s_id field of Student table will not take NULL value
  • 29. UNIQUE Key Constraint • UNIQUE constraint ensures that a field or column will only have unique values. A UNIQUE constraint field will not have duplicate data. • Example using UNIQUE constraint when creating a Table (Table Level) CREATE table Student(s_id int NOT NULL UNIQUE, Name varchar(60), Age int); The above query will declare that the s_id field of Student table will only have unique values and wont take NULL value. Example using UNIQUE constraint after Table is created (Column Level): ALTER table Student add UNIQUE(s_id); • The above query specifies that s_id field of Student table will only have unique value.
  • 30. Check Constraint • This constraint defines a business rule on a column. All the rows must satisfy this rule. • CHECK constraint is used to restrict the value of a column between a range. It performs check on the values, before storing them into the database. Example using CHECK constraint at Table Level: create table Student(s_id int NOT NULL CHECK(s_id > 0),Name varchar(60) NOT NULL, Age int); Example using CHECK constraint at Column Level: ALTER table Student add CHECK(s_id > 0);
  • 31. Implementation of SQL Commands • Basic syntax of CREATE TABLE statement is as follows” CREATE TABLE table_name( column1 datataype1, column2 datatype2, : : columnN datatype, PRIMARY KEY(one or more columns) );
  • 32. • CREATE TABLE is the keyword telling the database system what you want to do. • A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. • You can verify if your table has been created successfully by looking at the message displayed by the SQL server, otherwise you can use DESC command as follows: DESC EMPLOYEE;
  • 33. Alter Statement • The table can be modified or changed by using the Alter command. • ALTER TABLE table_name (columnname datatype(size); • ALTER TABLE table_name ADD column_name datatype; EX: SQL>alter table employee modify salary number(15,2); Table altered.
  • 34. ID NAME AGE ADDRESS SALARY 1 RAMESH 32 Shimoga 10000 2 KIRAN 25 Davangere 12000 3 KOUSHIK 23 Mangalare 11000 4 CHETHAN 34 Chitradurga 10500 ALTER TABLE CUSTOMERS ADD GENDER char(1); ID NAME AGE ADDRESS SALARY GENDER 1 RAMESH 32 Shimoga 10000 NULL 2 KIRAN 25 Davangere 12000 NULL 3 KOUSHIK 23 Mangalare 11000 NULL 4 CHETHAN 34 Chitradurga 10500 NULL
  • 35.
  • 36. DROP statement • The SQL DROP TABLE statement is used to remove a table definition and all data, indexes, triggers, constraints, and permission specifications for that table. • Basic syntax of DROP table statement: DROP TABLE table_name; Ex: SQL>DROP TABLE Student; Table dropped
  • 37. Insert • The SQL INSERT INTO Statement is used to add new rows of data to a table in the database. • Syntax is : INSERT INTO TABLE_NAME (Column1,Column2….ColumnN VALUES(value1,value2….valueN); • Here you may not need to specify the column(s) name in the SQL query if you are adding the values for all the columns of the table.
  • 38. Populate one table using another table INSERT INTO first_table_name[(col1,col2…colN)] SELECT col1,col2…colN FROM second_table [WHERE CONDITION];
  • 39. Select • SELECT statement is used to fetch the data from a database table which returns data in the form of result table. • These result tables are called result-sets. • Syntax is: SELECT column1,column2…..columnN FROM table_name; • WHERE clause to filter the records and fetching only necessary records. • Syntax is: SELECT column1,column2…columnN FROM table_name WHERE [condition];
  • 40.
  • 41. • SELECT EmployeeID, FirstName, LastName, HireDate, City FROM Employees WHERE City = 'London'
  • 42. The SQL AND & OR Operators • The AND operator displays a record if both the first condition AND the second condition are true. • The OR operator displays a record if either the first condition OR the second condition is true. SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin'; SELECT * FROM Customers WHERE City='Berlin' OR City='München';
  • 43. • Syntax for AND SELECT column1,column2, columnN FROM table_name WHERE [CONDITION1] AND [CONDITION2]; • Syntax for OR SELECT column1,column2, columnN FROM table_name WHERE [CONDITION1] OR [CONDITION2];
  • 44. Update • The SQL update Query is used to modifying the existing records in a table. • You can use WHERE clause with UPDATE query with WHERE clause is as follows: UPDATE table_name SET column1=value1,column2=value2…columnN=valueN WHERE[condition]; ID NAME ADDRESS SALARY 1 Sachin Tumkur 9000 2 Rahul Bangalore 10000 3 Sourav Mysore 11000 4 Anil Shimoga 12000
  • 45. Example: Consider the above table Employee. We can update ADDRESS for a customer whose ID is 2 SQL> UPDATE EMPLOYEE SET ADDRESS=‘Bengaluru’ WHERE ID=2; The resultant table is: ID NAME ADDRESS SALARY 1 Sachin Tumkur 9000 2 Rahul Bengaluru 10000 3 Sourav Mysore 11000 4 Anil Shimoga 12000
  • 46. DELETE • DELETE Query is used to delete the existing records from a table. • You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records should be deleted. • The syntax of WHERE clause is: DELETE FROM table_name WHERE [condition]; Example: Consider the given table EMPLOYEE
  • 47. ID NAME ADDRESS SALARY 1 Sachin Tumkur 9000 2 Rahul Bengaluru 10000 3 Sourav Mysore 11000 4 Anil Shimoga 12000 SQL> DELETE FROM EMPLOYEES WHERE ID=3; ID NAME ADDRESS SALARY 1 Sachin Tumkur 9000 2 Rahul Bengaluru 10000 4 Anil Shimoga 12000
  • 48. Order By Clause • Order By clause is used to sort the data in ascending or descending order, based on one or more columns. • Some database sorts query results in ascending order by default. • Syntax is : SELECT column_list FROM table_name [WHERE condition] [ORDER BY column1,column2,…columnN [ASC|DESC] ;
  • 49. • Consider the EMPLOYEE table having the following records: SQL> select id, name, salary from employees order by salary; id name salary 6 Sachin 15000 5 Rahul 16000 4 Sourav 18000 9 Anil 19000
  • 50. GROUP BY • The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. • The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause. • Syntax is: SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1, column2 ORDER BY column1, column2
  • 51. DISTINCT • The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records. • There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records. • Syntax: SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition]
  • 52. JOINS • The SQL Joins clause is used to combine records from two or more tables in a database. • A JOIN is a means for combining fields from two tables by using values common to each. • It is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal symbol.
  • 53. SQL JOIN TYPES There are different types of joins available in SQL: INNER JOIN: returns rows when there is a match in both tables. LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table. RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table. FULL JOIN: returns rows when there is a match in one of the tables. SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
  • 54. • Group functions are built-in functions that operate on groups of rows and return one value for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT. SQL COUNT() : This function returns the number of rows in the table that satisfies the conditions specified in the WHERE condition. Example: SELECT COUNT(*) FROM employee WHERE dept=‘Computer Science’; SQL DISTINCT(): This function is used to select all the distinct rows. Example: SELECT DISTINCT dept FROM employee;
  • 55. SQL MAX(): This function is used to get the maximum value from a column. Example: SELECT MAX(Salary) FROM EMPLOYEE; SQL MIN(): This function is used to get the minimum value from a column. Example: SELECT MIN(Salary) FROM EMPLOYEE: SQL AVG(): Used to get the average value of a numeric column. Example: SELECT AVG(Salary) FROM EMPLOYEE: SQL SUM(): Used to get the sum of the numeric problem. Example: SELECT SUM(SALARY) FROM EMPLOYEE;
  • 56. Creating Views: • Database views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables, or another view. • To create a view, a user must have the appropriate system privilege according to the specific implementation. • Syntax is : CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition];
  • 57. The COMMIT command • The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. • COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command. DCL commands are used to enforce database security in a multiple server database environments. GRANT REVOKE
  • 58. • GRANT is used to provide access or previleges on the database objects to the users. • Syntax is : GRANT privilege_name ON object_name TO {user_name |PUBLIC |role_name} [WITH GRANT OPTION]; • privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE, and SELECT. • object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE. • user_name is the name of the user to whom an access right is being granted. • user_name is the name of the user to whom an access right is being granted.
  • 59. • PUBLIC is used to grant access rights to all users. • ROLES are a set of privileges grouped together. • WITH GRANT OPTION - allows a user to grant access rights to other users. SQL REVOKE Command: • The REVOKE command removes user access rights or privileges to the database objects. REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}
  • 60. Privileges and Roles: • Privileges: Privileges defines the access rights provided to a user on a database object. There are two types of privileges. • 1) System privileges - This allows the user to CREATE, ALTER, or DROP database objects. 2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or DELETE data from database objects to which the privileges apply.
  • 61. • Few CREATE system privileges are listed below: System Privileges Description CREATE object allows users to create the specified object in their own schema. CREATE ANY object allows users to create the specified object in any schema.
  • 62. • The above rules also apply for ALTER and DROP system privileges. Object Privileges Description INSERT allows users to insert rows into a table. SELECT allows users to select data from a database object. UPDATE allows user to update data in a table. EXECUTE allows user to execute a stored procedure or a function.
  • 63. System Role Privileges Granted to the Role CONNECT CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE SEQUENCE, CREATE SESSION etc. RESOURCE CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE TRIGGER etc. The primary usage of the RESOURCE role is to restrict access to database objects. DBA ALL SYSTEM PRIVILEGES
  • 64. Oracle Built in Functions • There are two types of functions in Oracle. 1) Single Row Functions: Single row or Scalar functions return a value for every row that is processed in a query. 2) Group Functions: These functions group the rows of data based on the values returned by the query.
  • 65. • There are four types of single row functions. They are: 1) Numeric Functions: These are functions that accept numeric input and return numeric values. 2) Character or Text Functions: These are functions that accept character input and can return both character and number values. 3) Date Functions: These are functions that take values that are of datatype DATE as input and return values of datatype DATE, except for the MONTHS_BETWEEN function, which returns a number. 4) Conversion Functions: These are functions that help us to convert a value in one form to another form. For Example: a null value into an actual value, or a value from one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc.
  • 66. What is a DUAL Table in Oracle? • What is a DUAL Table in Oracle? This is a single row and single column dummy table provided by oracle. This is used to perform mathematical calculations without using a table. • Example: Select * from DUAL Output: DUMMY ------- X Select 777 * 888 from Dual; Output: 777 * 888 --------- 689976
  • 67. 1) Numeric Functions: • Numeric functions are used to perform operations on numbers. Function Name Return Value Function Name ABS (x) Absolute value of the number 'x' ABS (x) CEIL (x) Integer value that is Greater than or equal to the number 'x' CEIL (x) FLOOR (x) Integer value that is Less than or equal to the number 'x' FLOOR (x) TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places TRUNC (x, y) ROUND (x, y) Rounded off value of the number 'x' up to the ROUND (x, y)
  • 68. Function Name Examples Return Value ABS (x) ABS (1) ABS (-1) 1 -1 CEIL (x) CEIL (2.83) CEIL (2.49) CEIL (-1.6) 3 3 -1 FLOOR (x) FLOOR (2.83) FLOOR (2.49) FLOOR (-1.6) 2 2 -2 TRUNC (x, y) ROUND (125.456, 1) ROUND (125.456, 0) ROUND (124.456, - 1) 125.4 125 120 ROUND (x, y) TRUNC (140.234, 2) TRUNC (-54, 1) TRUNC (5.7) TRUNC (142, -1) 140.23 54 5 140
  • 69. 2) Character or Text Functions: • Character or text functions are used to manipulate text strings. They accept strings or characters as input and can return both character and number values as output. Function Name Return Value LOWER (string_value) All the letters in 'string_value' is converted to lowercase. UPPER (string_value) All the letters in 'string_value' is converted to uppercase. INITCAP (string_value) All the letters in 'string_value' is converted to mixed case. LTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the left of 'string_value'. RTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the right of 'string_value' . TRIM (trim_text FROM string_value) All occurrences of 'trim_text' from the left and right of 'string_value' , 'trim_text' can also be only one character long . SUBSTR (string_value, m, n) Returns 'n' number of characters from 'string_value' starting from the 'm' position. Number of characters in 'string_value' in
  • 70. DATE FUNCTIONS • These are functions that take values that are of datatype DATE as input and return values of datatypes DATE, except for the MONTHS_BETWEEN function, which returns a number as output. Function Name Examples Return Value ADD_MONTHS ( ) ADD_MONTHS ('16-Sep- 81', 3) 16-Dec-81 MONTHS_BETWEEN( ) MONTHS_BETWEEN ('16-Sep-81', '16-Dec-81') 3 NEXT_DAY( ) NEXT_DAY ('01-Jun-08', 'Wednesday') 04-JUN-08 LAST_DAY( ) LAST_DAY ('01-Jun-08') 30-Jun-08 NEW_TIME( ) NEW_TIME ('01-Jun-08', 'IST', 'EST') 31-May
  • 71. Conversions Functions • These are functions that help us to convert a value in one form to another form. For Ex: a null value into an actual value, or a value from one datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE.
  • 72. Function Name Return Value TO_CHAR (x [,y]) Converts Numeric and Date values to a character string value. It cannot be used for calculations since it is a string value. TO_DATE (x [, date_format]) Converts a valid Numeric and Character values to a Date value. Date is formatted to the format specified by 'date_format'. NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y' must be of the same datatype. DECODE (a, b, c, d, e, default_value) Checks the value of 'a', if a = b, then returns 'c'. If a = d, then returns 'e'. Else, returns default_value.