SQL Commands

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 75

SQL

COMMANDS
WHAT IS SQL?
 SQL is Structured Query Language, which is a computer language

for storing, manipulating and retrieving data stored in relational


database.
 SQL helps to make practice on SQL commands which provides

immediate results.
 SQL is the standard language for Relation Database System. All

relational database management systems like MySQL, MS Access,


Oracle, Sybase, Informix, postgres and SQL Server use SQL as
standard database language.
DIALECTS OF SQL
1. MS SQL Server using T-SQL
2. Oracle using PL/SQL
3. SQL Lite
4. MS Access version of SQL is called JET SQL
WHY MS SQL?
 Allows users to create and drop databases and tables.
 Allows users to describe the data.
 Allows users to define the data in database and
manipulate that data.
 Allows users to access data in relational database
management systems
SQL COMMANDS
The standard SQL commands to interact with relational
databases are CREATE, SELECT, INSERT, UPDATE, DELETE
and DROP. These commands can be classified into groups
based on their nature:
1. DDL - Data Definition Language commands
2. DML - Data Manipulation Language commands
3. DCL - Data Control Language commands
4. TCL - Transaction Control Language commands
DATA DEFINITION LANGUAGE
 DDL commands are used to define the database schema, alter
the database schema and drop the database schema.
 Few of the basic DDL commands are:
1. CREATE:
 Create command is used to create a new table.

Syntax:
CREATE TABLE table_name
(
column1 datatype,
column2 datatype,
column3 datatype,
…………………
columnN datatype
);
Example:
SQL>
create table Student
(
id number(5),
name varchar(20),
age number(2)
);
The above command will create a new table Student in database
system with 3 columns id, name and age.
2. ALTER:
 Alter command is used for alteration of table structures.
 There are various uses of alter command such as,
i. to add a column to existing table.
ii. to change datatype of any column or to modify its size.

Syntax & Example:


i. alter table table_name add(column-name datatype);
ex: alter table Student add(fees number(5));
ii. alter table table_name modify(column-name datatype);
ex: alter table Student modify(fees number(5,2));
3. DROP:
 The SQL drop command is used to delete a table from the
database permanently.

Syntax :
drop table table_name;
Example:
drop table Student;
DATA MANIPULATION LANGUAGE
 DML commands are used to manipulate the data in the
database.
 It provides the data manipulation techniques like selection,
insertion, deletion, updation, modification, replacement,
sorting and display of data or records.
 Few of the basic DML commands are:
1. INSERT:
 Insert command is used to add new rows of data to a table.
 There are two basic syntaxes for insert command.

Syntax & Example:

insert into table_name(column1, column2 …. columnN)


values(value1,value2….valueN);
Ex: insert into Student(id,name,age)values(101,'Alex‘,15);

insert into table_name values(value1,value2……valueN);


Ex: insert into Student values(102,'Adam',15);
insert into Student values(103,’Karthik’,20);
2. UPDATE:
 Update command is used to update a row of a table.

Syntax:
update table_name set column_name = value where condition;

Example:
update Student set name=‘Abhi’ where id=102;
3. SELECT:
 Select command is used to fetch the data from the database.
 To fetch the data of complete table the syntax is:
Select column_name1, column_name2…..column-nameN from
table_name;
Select * from tablename;
Example:
Select * from student;

 To fetch the data of one row, the syntax is:


Select column1,column2…..columnN from table_name where
condition;
Example:
Select id,name,age from Student where id=101;
4. DELETE:
 Delete command is used to delete data from a table.
 Delete command can also be used with condition to delete a
particular row.

Syntax & example to delete all records from a table:


Delete from table_name;
Delete from Student;

Syntax & example to delete data of one row using condition:


Delete from table_name where condition;
Delete from Student where id=103;
DATA CONTROL LANGUAGE
 DCL commands are used to provide security to the data in a
database.
 Allows permission for the user and withdraws the permission
from the user to access the database.
 The different DCL commands are:
1. GRANT:
 Used to provide access or privileges to the users on the

database.
Syntax:
GRANT privilege_name ON object_name TO user_name;
Ex:
SQL>GRANT SELECT ON employee TO user1;
This command grants a SELECT permission on employee table
to user1.
2. REVOKE:
 Used to remove access or privileges from the users on the database.

Syntax:

REVOKE privilege_name ON object_name FROM user_name;

Ex:

SQL>REVOKE SELECT ON employee FROM user1;

This command revoke a SELECT privilege on employee table from


user1.

When you revoke SELECT privilege on a table for an user, the user
will not be able to select data from employee data.
TRANSACTION CONTROL
LANGUAGE
 It includes commands to control the transactions in a database
system.
 It makes changes permanent or cancels the changes without
affecting the data.
 The commonly used commands are:
1. COMMIT:
 The COMMIT command is the transactional command used to
save changes invoked by a transaction to the database.

Syntax:
COMMIT;

Ex: Consider the STUDENT table

.
Write a query to delete students record whose result is FAIL and
COMMIT changes.

SQL>DELETE from STUDENT where result=“FAIL”;


SQL>COMMIT;
2. ROLLBACK:
 ROLLBACK command is the transactional command used to
undo transactions that have not already been saved to the
database.

Syntax:
ROLLBACK;
Ex: Consider the STUDENT table
Write a query to delete students record whose result is FAIL and
then ROLLBACK the changes.

SQL>DELETE from STUDENT where result=“FAIL”;


SQL>ROLLBACK;
DATA TYPES IN SQL
 SQL data type is an attribute that specifies type of data of any
object.
 We use data types while creating the tables.
 The following are the most common data types of SQL:
1. NUMBER
2. CHAR
3. VARCHAR/VARCHAR2
4. DATE
5. TIME
1. NUMBER:
 Used to store a numeric value in a field column.

 It may be decimal, integer or real value.

 General syntax: number(n,d)

 Where n specifies the number of digits and d specifies the

number of digits to right of the decimal point.


Example:
marks number(3)
average number(2,3)
2. CHAR:
 Used to store a character type data in a column.

 General syntax: char(size)

 Where size represents the maximum (255 Characters) number

of characters in a column.
Example: name char(15)
3. VARCHAR/VARCHAR2:
 It is used to store variable length alphanumeric data.

 General syntax: varchar(size) / varchar2(size)

 Where size represents the maximum(2000 Characters) number

of characters in a column.
Example: address varchar2(50)
4. DATE:
 It is used to store date in columns.

 SQL supports the various date formats other than the standard

DD-MON-YY.
 DATE data type stores a date like march 26, 2018

Example: dob DATE


5. TIME:
 It is used to store time in columns.

 SQL supports the various time formats other than the standard

hh-mm-ss.
 It stores a time of day like 12.30 P.M
OPERATORS IN SQL
An operator is a reserved word or a character used in a SQL
statement's to perform operation, such as comparisons and
arithmetic operations.
Different types of operators in SQL are:
1. Arithmetic operators
2. Relational operators
3. Logical operators
ARITHMETIC OPERATORS
Assume variable a holds 10 and variable b holds 20, then
RELATIONAL OPERATORS
Assume variable a holds 10 and variable b holds 20, then
LOGICAL OPERATORS
1. ALL:
 The ALL operator in SQL returns true when value matches with all

values in single column set of values.


 It’s like AND operator it will compare value against with all values

in column.

Syntax:
SELECT column1, column2…columnN FROM tablename1
WHERE column1 = ALL(SELECT column1 FROM tablename2);
Ex:

SELECT id,name from example1 WHERE id >=ALL


(SELECT id from example2);
2. AND:
 When we have multiple conditions in SQL statement, we use
AND operator to combine the conditions.
 Query will be executed only if all the conditions is true.

Syntax:
SELECT column1, column2,…columnN
FROM Table_name
WHERE [condition1] AND [condition2]...AND [conditionN];

Example:
SELECT * from employees WHERE salary>15000 AND
age>30;
3. OR:
 When we have multiple conditions in SQL statement, we use
OR operator to combine the conditions.
 Query will be executed if any one of the condition is true.

Syntax:
SELECT column1, column2,…columnN
FROM Table_name
WHERE [condition1] OR [condition2]...OR [conditionN];

Example:
SELECT * from employees WHERE salary>15000 OR age>30;
4. BETWEEN:
 Used to search for values that are within a set of values, given
the minimum value and maximum value.

Syntax:
SELECT column1, column2,…columnN
FROM Table_name
WHERE column_name BETWEEN value_1 AND value_2;

Example:
SELECT * from employees WHERE salary BETWEEN
5000 AND 10000;
5. NOT:
 Reverses the meaning of logical operator with which it is used.
 Ex: NOT EXISTS, NOT BETWEEN, NOT IN etc.
 Called as negate operator.

Syntax:
SELECT column1, column2,…columnN
FROM Table_name
WHERE column_name NOT BETWEEN value_1 AND value_2;

Example:
SELECT * from employees WHERE salary NOT BETWEEN
5000 AND 10000;
6. LIKE:
 Used to compare a value to similar values using wildcard
operators.
 Ex for wildcard operators are % and _

Examples:
Select name from Student where name=‘A%’;
Select * from employees where dept=‘S_ _ _ S’;
Select * from employees where salary=‘2_ _ _0’
7. ANY:
 The ANY operator in SQL returns true when value matches

with any value in single column set of values.


 It’s like OR operator it will compare value against with any

value in column.

Syntax:
SELECT column1, column2 from tablename1 WHERE
column1 = ANY(SELECT column1 from tablename2);
Ex:

SELECT id,name from example1


WHERE id = ANY(SELECT id from example2);
8. IN:
 The IN operator in SQL is used to search for specified value
matches any value in set of multiple values.

Syntax:
SELECT column1, column2 FROM tablename WHERE column
1 IN ('value1','value2','value3');
Ex:
The following SQL query will return all employees where
location in 'chennai', 'guntur'.

SELECT * FROM EmployeeDetails WHERE Location


IN('chennai','guntur');

Output:
2. AND:
 When we have multiple conditions in SQL statement, we use
AND operator to combine the conditions.
 Query will be executed only if all the conditions is true.

Syntax:
SELECT column1, column2,…columnN
FROM Table_name
WHERE [condition1] AND [condition2]...AND [conditionN];

Example:
SELECT * from employees WHERE salary>15000 AND
age>30;
3. OR:
 When we have multiple conditions in SQL statement, we use
OR operator to combine the conditions.
 Query will be executed if any one of the condition is true.

Syntax:
SELECT column1, column2,…columnN
FROM Table_name
WHERE [condition1] OR [condition2]...OR [conditionN];

Example:
SELECT * from employees WHERE salary>15000 OR age>30;
SQL BUILT-IN FUNCTIONS
 Used for performing processing on string or numeric data.
Basically there are two types of functions:
1. Single row functions: These functions are applicable to
a particular row of a table. Types of single row functions are
Numeric functions, Text functions, Date & Time functions
and Conversion functions.
2. Group functions: These functions operate on group of
rows and return one value for the entire group. Ex: COUNT,
MAX, MIN, AVG and SUM.
ARITHMETIC FUNCTIONS
Consider the following STUDENT TABLE:
REG NO NAME COMB TOTAL RESULT
121 Anusha PCMC 363 Pass
122 Ashok PCMC 179 Fail
123 Kalashre PCMB 523 Pass
e
1. AVG( ): It calculates the average of specified column.
Syntax:
SELECT AVG(column_name) FROM table_name;
Ex: SELECT AVG(total) FROM student;
Output: AVG
355
2. COUNT( ): It returns the number of rows that matches a
specified criteria.
Syntax:
SELECT COUNT(column_name) FROM table_name;
Ex: SELECT COUNT(*) FROM student;
Output: COUNT(*)
3

3. MAX( ): It returns largest value of the selected column.


Syntax:
SELECT MAX(column_name) FROM table_name;
Ex: SELECT MAX(total) FROM student;
Output: MAX(total)
523
4. MIN( ): It returns lowest value of the selected column.
Syntax:
SELECT MIN(column_name) FROM table_name;
Ex: SELECT MIN(total) FROM student;
Output: MIN(total)
179

5. SUM( ): It calculates total sum of a numeric column.


Syntax:
SELECT SUM(column_name) FROM table_name;
Ex: SELECT SUM(total) FROM student;
Output: SUM(total)
1065
TEXT FUNCTIONS
Consider the following STUDENT TABLE:
REG NO NAME COMB TOTAL RESULT
121 Anusha PCMC 363 Pass
122 Ashok PCMC 179 Fail

1. UPPER( ): Converts the value of a field to uppercase.


Syntax:
SELECT UPPER(column_name) FROM table_name;
Ex: SELECT UPPER(name) FROM student;
Output: UPPER(name)
ANUSHA
ASHOK
2. LOWER( ): Converts the value of a field to lowercase.
Syntax:
SELECT LOWER(column_name) FROM table_name;
Ex: SELECT LOWER(comb) FROM student;
Output: LOWER(comb)
pcmc
pcmc

3. LENGTH( ): It returns number of characters in a string.


Syntax:
SELECT LENGTH(column_name) FROM table_name;
Ex: SELECT LENGTH(comb) FROM student;
Output: LENGTH(comb)
4
1. INITCAP (string): Convert the string into mixed case
 Example: INITCAP(‘GOOD MORNING’) it returns Good Morning
DATE AND TIME FUNCTIONS
Numeric functions
ABS(x) It returns the absolute ABS(-20) = 20
value of x
CEIL(x) Returns the integer value that CEIL(2.83)=3
is greater than or equal to the CEIL(2.49)=3
number x

FLOOR(x) Returns the integer value that FLOOR(2.83)=2


is less than or equal to the FLOOR(2.49)=2
number x

TRUNC(x,y) Truncates the value of x up to TRUNC(25.234,2)=25.23


y decimal places TRUNC(5.7)=5

ROUND() Rounded off the value


ROUND(123.456,0)=123
JOINS
 The SQL Joins clause is used to combine records from two or more tables
in a database. A JOIN clause combines the common fields from two tables.
Ex: Consider two tables, CUSTOMER & ORDER table:

ID NAME AGE ADDRESS SALARY

1 Ramesh 35 Ahmedabad 2000.00


2 Kavya 25 Delhi 1500.00
3 Ashok 23 Kolkata 2000.00
4 Deeksha 26 Bangalore 1200.50

OID DATE ID AMOUNT


102 2009-10-08 3 3000
100 2009-10-08 1 1500
101 2009-11-20 2 1560
Syntax:
SELECT column_name1….column_nameN FROM
table_name1,tablename2 WHERE
table_name1.column_name=table_name2.column_name;

Ex: SELECT id, name, age, amount FROM customer, order


WHERE customer.id=order.id;
Output:
ID NAME AGE AMOUNT

3 Ashok 23 3000

1 Ramesh 35 1500

2 Kavya 25 1560
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.
This ensures the accuracy and reliability of the data in the
database.
 Following are commonly used constraints available in SQL:
NULL value
NOT NULL Constraint
DEFAULT Constraint
UNIQUE Constraint
PRIMARY Key
FOREIGN Key
CHECK Constraint
NULL Value
 A NULL value in a table is a value in a field that appears to be blank,
which means a field with a NULL value is a field with no value.
 It is important to understand that a NULL value is different than a zero
value.
 A field with a NULL is one that has been left blank during insertion of
rows.

Ex:
SQL> insert into student values('18C1302',‘aayush');
SQL> insert into student values('18C1303','');
SQL> select *from student;

RNO NAME
---------- ---------------
18C1302 aayush
NOT NULL Constraint
 It ensures that a column cannot have NULL value.
 When a column is defined as NOT NULL then the column
becomes a mandatory column.
Ex:
CREATE TABLE product
(
pid char (4) NOT NULL,
description varchar2 (25) NOT NULL,
companyid char (10),
dom date,
type char (10),
price number (10,2)
);
DEFAULT Constraint
It provides a default value for a column when no data is specified
during insertion of values.
Ex:
CREATE TABLE product
(
pid char (4),
description varchar2 (25),
companyid char (10),
dom date,
type char (10),
price number (10, 2) default 1000.00
);
UNIQUE Constraint
 This constraint ensures that no rows have the same value in the
specified column.

Ex: UNIQUE constraint applied on PID of PRODUCT table ensures


that no rows have the same PID value.
CREATE TABLE product
(
pid char (4) unique,
description varchar2 (25),
companyid char (10),
dom date,
type char (10),
price number (10,2)
);
PRIMARY Key
 A primary key is a field which uniquely identifies each row in a
database table.
 By default this column is NOT NULL. It defines the column as
a mandatory column i.e. the column cannot be left blank.
Ex:
CREATE TABLE product
(
pid char (4) PRIMARY KEY,
description varchar2 (25),
CompanyId char (10),
dom date,
type char (10),
price number (10,2)
FOREIGN Key:
 A foreign key is used to link two tables together.
 A foreign key is a column whose values are derived from the
primary key of some other table.

Ex: COMPANY TABLE


CREATE TABLE company
(
cid char (10) primary key,
cprofile varchar2 (200),
noofproducts number (20),
doe date
);
Ex: PRODUCT TABLE
CREATE TABLE product
(
pid char (4) primary key,
description varchar2 (25), not null
companyid char (10) references company (cid),
dom date,
type char (10),
price number (10,2)
);
CHECK Constraint:
 If a value does not meet the condition, it cannot be placed in
the column.
Ex:
CREATE TABLE product
(
pid char (4) ,
description varchar2 (25),
companyid char (10),
dom date,
type char (10),
price number (10, 2) check (price>0)
);
ORDER BY
 ORDER BY clause is used to sort the data in ascending or descending
order, based on one or more columns.
Syntax:
Select column-list from table_name
order by column1, column2,.. columnN asc/desc;

Example: Consider the following student table


GROUP BY
 GROUP BY clause is used to arrange identical data into groups.
Syntax:
Select columnname from table_name
group by columnname
order by columnname;

Example: Consider the following student table


What is the difference between Order by and Group by clause in SQL? Give
examples for each

ORDER BY Clause GROUP BY Clause


1. ORDER BY clause is 1. The GROUP BY clause
used to display the result can be used in a SELECT
of a query in a specific statement to collect data
order(sorted order) across multiple records and
group the results by one or
more columns.

2. Example:- 2. Example:-
SELECT ID, Name FROM Select ID, Name, Percent,
student ORDER BY result from STUDENT
Name; GROUP BY COMB
Difference between data definition language and data manipulation language.

DDL DML

1.These commands 1.These commands are


are used to used to insert, modify the
Create ,modify and data of the database table
delete the database
table

2.DDL commands are 2.INSERT,SELECT,DELET


CREATE, ALTER, E, UPDATE
DROP
THANK
YOU

You might also like