Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

SQL Commands

The document provides an overview of SQL commands categorized into DDL, DML, and DCL, detailing their syntax and examples. It covers key commands such as CREATE, INSERT, SELECT, UPDATE, and DELETE, along with SQL constraints like PRIMARY KEY and FOREIGN KEY. Additionally, it discusses aggregate and scalar functions used for data manipulation and retrieval in SQL.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQL Commands

The document provides an overview of SQL commands categorized into DDL, DML, and DCL, detailing their syntax and examples. It covers key commands such as CREATE, INSERT, SELECT, UPDATE, and DELETE, along with SQL constraints like PRIMARY KEY and FOREIGN KEY. Additionally, it discusses aggregate and scalar functions used for data manipulation and retrieval in SQL.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

SQL Commands

1.DDL : Data Definition language


2.DML : Data Manipulation Language
3.DCL : Data Control Language

DDL: 3 Main commands


1.Create commands
Use: It is used to create database objects:
table, database, query, view, structures
Syntax:
CREATE TABLE <tablename>
(
<coulmnname1> <datatype>,
.
.
<coulmnnamen><datatype>
);
Example
CREATE TABLE student
(
Sid1 number,
Sname char(25),
Marks number,
Email char(30)
);
2.DESC Command
Use: It is used to Describe, any database
object
Syntax:
DESC <database object name>;
Example:
DESC employee;

3.INSERT Command
We can add records in the object
Syntax1:
INSERT INTO <tablename> VALUES (value1,
value2….. valuen);
Example
INSERT INTO student
VALUES(1,’amit’,23,’amnit@gmail.com’);

INSERT INTO student


VALUES(1,’amit’,’’,’amnit@gmail.com’);
Syntax 2
INSERT INTO <tablename> (<columnnam1,
colunmame2…) VALUES (value1, value 2);
Example
INSERT INTO student (sid, sname) values
(1,’amit’);
Syntax 3
INSERT INTO <tablename> values (&sid,
&sname,&marks….);

4.Drop Command
Use : its used to delete the database object
Syntax: DROP
TABLE<databaseobjectname>;
Example DROP TABLE Student;

SQL Constraints
Constraints in SQL helps to ensure that
the data entered by the user is correct.
SQL supports 6 types of constraints
1.Primary key: to uniquely identify each
record in the table.
Primary key: Not NULL + unique
Example
Create table student
(
Sid number PRIMARY KEY,
Sname char(25),
Marks number
);
Create table student
(
Sid number,
Sname char(25),
Marks number,
Emailed char(25),
PRIMARY KEY (sid)
);
2.NOT NULL
It enforce that the column can not be
left blank. The field or the column will
always contain a value.
Example 1

Create table student


(
Sid number PRIMARY KEY,
Sname char(25) NOT NULL,
Marks number
);

Example 2
Create table student
(
Sid number,
Sname char(25),
Marks number,
Emailed char(25),
PRIMARY KEY (sid),
NOT NULL (sname)
);
3.Unique Constraint
Identifies each record uniquely in a
database table.
Example 1
Create table student
(
Sid number PRIMARY KEY,
Sname char(25) NOT NULL,
Marks number
Email char(30) UNIQUE
);
Example 2

Create table student


(
Sid number,
Sname char(25),
Marks number,
Emailed char(25),
PRIMARY KEY (sid),
NOT NULL (sname),
UNIQUE (emailed)
);

4.CHECK Constraint:
It is used to limit the value range that
can be placed in a column.
Example
CREATE TABLE Persons
(
P_id number PRIMARY KEY,
P_Name Char(40) NOT NULL,
Address char(40) UNIQUE,
City varchar(30),
CHECK (P_id>0)
);
5.DEFAULT constraint
Example
CREATE TABLE Persons
(
P_id number PRIMARY KEY,
P_Name Char(40) NOT NULL,
Address char(40) UNIQUE,
City varchar(30) DEFAULT ‘DELHI’,
CHECK (P_id>0)
);
6.Foreign Key Constraint
It is used to link two tables. It will be
more used in joins, subquery

Persons table
P_ID,
Lastname
Firstname
Address, City, Dept_id
( P_Id is the primary key)
Dept_id foreign key)
Persons table and department table
Example
CREATE TABLE PERSONS
(
P_ID number,
Lastname char(30),
Firstname char(30),
Address char(50),
City char(15)
Dept_id number,
PRIMARY KEY(P_ID),
FOREIGN KEY (DEPT_ID) REFERENCES
DEPARTMENT(DEPT_ID)
);

Sql CONSTRAINTS
1.PRIMARY KEY
2.FOREIGN KEY
3.CHECK
4.DEFAULT
5.UNIQUE
6.NOT NULL

SQL COMMANDS: DDL COMMANDS


ALONG WITH SQL CONSTRAINTS
DML COMMANDS: Data Manipulation
Language.

1.SELECT STATEMENT:
Use: it is used to select or retrieve the
data from the database.
Syntax:

SELECT < COLUMN NAME> <ALL *>


FROM <DATABASE OBJECT NAME>
<Optional>
WHERE <CONDITION>
ORDER BY < SORT THE
DATA<COLUMN NAME>><ASC, DESC
> by default ascending

EXAMPLE:
Q1. WSQ (Write SQL Query) TO VIEW
THE LIST OF TABLES PRESENT IN THE
DATABASE.
SYNTAX:
SELECT FROM < DATABASENAME>
ANSWER:
SELECT FROM JIMS;
( It will show all the tables present in
the jims database.)
Q2. WSQ to show the lastname and
firstname column from persons table

SELECT lastname, firstname FROM


persons;

Q3. WSQ to show all the columns


from the persons table
SELECT * FROM persons;
Q4. Wsq to show the distinct column
value from the city column in the
person table.

SELECT DISTINCT city FROM persons;

Q5. WSQ to select the firstname of


the persons living in the city “Delhi”
from the persons table.
SELECT firstname FROM persons
WHERE city= “delhi”;
SELECT firstname where city= “delhi”
from perons; ( Incorrect)
1st Clause SELECT.
2nd FROM Clause.
3rd WHERE Clause.
4th ORDER BY
5th GROUP BY
6th HAVING

Q6. WSQ to select all the records


from the persons table for the
persons who live in the city Delhi and
whose lastname is sharma.

SELECT * FROM PERSONS WHERE


city= “delhi” AND lastname =
“sharma”;

Q7. WSQ to select all the records


from the persons table for the
persons who either live in the city
Delhi or whose lastname is sharma.
SELECT * FROM PERSONS WHERE
city= “delhi” OR lastname =
“sharma”;

Logical Operator
1.AND: when both conditions are
true then it will be executed.
Truth Table
C1 C2 Output
T T T
T F F
F T F
F F F
2.OR: when any one of the condition
is true it will be executed
Truth Table
C1 C2 Output
T T T
T F T
F T T
F F F

3.NOT Operator
Opposite of the condition
Truth Table
C1 Output
T F
F T
Q8. WSQ to show all the records
from persons table sorted in the
ascending order of the firstname.

SELECT * FROM persons ORDER BY


firstname ASC;

SELECT * FROM persons ORDER BY


firstname;

Q9. WSQ to show all the records


from persons table sorted in the
descending order of the firstname.

SELECT * FROM persons ORDER BY


firstname DESC;

Wild cards in SQL


Is used to search one or more
characters from the database.
In SQL the wild cards are generally
with like operator
% : it is a substitute for zero or more
characters.
- It is a substitute of exactly one
character
[] it is substitute of characters
that is given in the brackets
[!] it is substitute of characters
with can be anything apart from
the values given in the bracket.

Q10. WSQ to select all the


persons from the person table
sorted in the descending order of
city for the person that lives in the
city that starts with “D”.

SELECT * FROM persons WHERE city


LIKE “D%” ORDER BY city DESC;

Q11.WSQ to select all the persons


from the person table sorted in
the ascending order of city for the
person that lives in the city that
contains the pattern “elh”
anywhere in the middle of the city
name.

SELECT * FROM persons WHERE city


LIKE “%elh%” ORDER BY city ASC;

Q12. WSQ to select the firstname


and the lastname from the
persons table whose lastname
starts with “b” or “s”.

SELECT firstname, lastname FROM


persons WHERE lastname LIKE
“[bs]%”;

Q13. WSQ to select the firstname


and the lastname from the
persons table whose lastname
should not starts with “b” or “s”.
SELECT firstname, lastname FROM
persons WHERE lastname LIKE “[!
bs]%”;

Q14. WSQ to show all the records


from the persons for the persons
living in city Delhi or Mumbai.

SELECT * FROM persons WHERE


city LIKE “Delhi” OR City LIKE
“Mumbai”;
Or
SELECT * FROM persons WHERE
city IN (“delhi”, “mumbai”);

Alias Name: short names ,


abbreviations for database
objects.
Select p.firstname , p.lastname
from persons p;

SELECT s.sname, c.coursename


from student s, course c;
DML Commands
1.Select command
Select clause.
From Clause
Where clause.
Order by clause
Alias name with select statement.

2.ALTER TABLE command


Is used to add, delete or modify the
columns in the existing table.
1.To add a new columns in an existing
table.
SYNTAX:
ALTER TABLE <tablename> ADD
<Columnname datatype>;
Example
ALTER TABLE student ADD emailed
char(30);
2.To delete a column from the
existing table
Syntax:
ALTER TABLE < tablename> DROP
COLUMN <columnname>;
Example
ALTER TABLE employee DROP
COLUMN doj;
3. To Change the datatype of the
column in the existing table:
ALTER TABLE <tablename> ALTER
COLUMN <cloumnname datatype>;
Or
ALTER TABLE <tablename> MODIFY
<cloumnname datatype>;

Example
ALTER TABLE employee ALTER
COLUMN eid char(30);
4.To rename the columnname in the
existing table.
SYNTAX:
ALTER TABLE <tablename> RENAME
<old columnname> TO <new
columname>;
Example
ALTER TABLE employee RENAME
eid TO empid;
5.To rename a complete table
Syntax:
ALTER TABLE <tablename> RENAME
TO <newtablename>
Example
ALTER TABLE emp RENAME TO
Employee;

Questions based on ALTER


statement

Q1. WSQ to add new column i.e


dateofbirth in the persons table.
ALTER TABLE person ADD dob
char(30);

Q2. WSQ to change the datatype of


the column datofbirth from number
to character in the persons table.

ALTER TABLE persons ALTER


COLUMN Dob char(50);
Or
ALTER TABLE persons MODIFY dob
char(50);
Q3. WSQ to delete the columname
emailid from the persons table.
ALTER TABLE persons DROP
COLUMN emailid;

Q4. WSQ to rename the persons


table to the new name i.e customer.

ALTER TABLE persons RENAME TO


customers.

Q5. WSQ to rename the column i.e


mobile number to new
colunmname i.e. contactno.

ALTER TABLE persons RENAME


mobileno TO contactno;
3.DELETE Command: this command is
used to delete the records from the
table
Syntax:
DELETE FROM <tablename> WHERE
<condition>;
Example
DELETE FROM Student where sid=1;
( It will the record of the student
whose sid is 1)
DELETE FROM student WHERE
sname= “amit”;
( It will delete the record of amit from
the student table)

DELETE FROM student WHERE


marks<40;
( its will delete all the records of the
student whose marks is less than 40
from the student table)

DELETE FROM student;

( It will delete all the records from


student table)
( It will delete all the rows).

Q WSQ to delete the student records


whose firstname is “ Amit” and
lastname is “ Sharma” from the
student table.
DELETE FROM student WHERE
firstname= “amit” AND lastname=
“sharma”;

4.UPDATE Command: It is used to


update the records in the existing
table
Syntax:
UPDATE <tablename> SET
<columnname><value> WHERE
<condition>
Example:
UPDATE student SET marks=marks+2;
( It is updating the marks every
student which is increased by 2
marks)
UPDATE student SET marks=marks+2
WHERE sname= “amit”;
( It will update the marks of amit i.e.
increase by 2 marks).
Q WSQ to update the employee table
where the company want to increase
the salary very employee by RS 500.

UPDATE employee SET


salary=salary+500;

Q WSQ to update the employee table


where the company want to increase
the salary of employee by RS 500 for
those whose salary is less than 20000
UPDATE employee SET
salary=salary+500 WHERE
salary<20000;

DDL : create, insert, drop, desc


DML: select, alter, delete and update.

DCL Command:

Data Control Language.


It always work with the administrator
login.

1.SAVEPOINT statement: is used to


temporary save a transaction so that
you can rollback to that point
whenever required.
Syntax:
SAVEPOINT <save_point_name>;
2.COMMIT Statement: This command
finishes the transaction and store all
changes made inside the transaction.
It basically executes the transaction.
Syntax:
<command>
COMMIT;

Drop Table Student;


COMMIT;
3.ROLLBACK statement: It revert all
changes made in the scope of
transaction.
Syntax:
<command>
ROLLBACK;

Example DROP Table student;


ROLLBACK;

Functions in SQL: In built functions


present in SQL to manipulate date or
select data.
They are divided into 2 categories:
1.Aggregate Functions.
2.Scalar Functions.

Aggregate Functions: they are those


functions that returns a single value
which is calculated from the values
in a column.

Some of the important aggregate


functions are:
AVG(): It returns the average value
of the columns.
COUNT(): It returns the no of rows
that contains some value.
FIRST(): It will return the first value
in the given column.
LAST():It will return the last value in
the given column.
MAX(): It will return the maximum
value from the given column.
MIN():It will return the minimum
value from the given column.
SUM(): It will return the total of the
values from the given column.

Scalar functions: they also return


the single value, but generally they
perform the operations on the text
based columns and values.

1.UCASE: It converts the field value


into the upper case value.
2.LCASE: It converts the field value
into the lower case value.
3. LEN: It returns the length of the
text field. The length includes the
spaces, special characters etc.
4.NOW: It returns the current data
and time value ( system data and
time). MM/DD/YYYY hh:mm:ss.ss
5.Date : It returns the current date
only in the format mm/DD/YYYY
( System date).
6.Format: It formats the field value
in the given format.
Format date dd/mm/yy.
7.MID : Its returns the character
from the given point.
MID( “Priyanka”, 2):
Output: riyanka
MID ( “ Priyanka, 2,4)
Output: riy

Q WSQ to find the average value of


the “orderprice” field from orders
table.
SELECT AVG(orderprice) FROM
orders;

SELECT AVG(orderprice) AS
averageorderprice FROM orders;
Q WSQ to find the customername
from order table whose orderprice
is greater than the average
orderprice value.

SELECT customername FROM


orders WHERE orderprice>(SELECT
AVG(orderprice) FROM Orders);

Q WSQ to count the number of


order from customer table where
the customername is “neel”.

SELECT COUNT(order) FROM


customer WHERE customername=
‘Neel’;

Q WSQ to count the total number


of orders entered in the customer
table.
SELECT COUNT(order) FROM
customer;
SELECT COUNT(*) FROM customer;

SELECT COUNT(*) AS
noofcustomers FROM customer;

Q WSQ to count the distinct


customername from the orders
table.
SELECT DISTINCT
COUNT(customername) AS
noofcustomersnames FROM order;

Q WSQ to find the largest value in


the orderprice column of the order
table.

SELECT MAX(orderprice) AS
laregestprice FROM orders;

Q WSQ to find the smallest value in


the orderprice column of the order
table.
SELECT MIN(orderprice) AS
smallestprice FROM orders;
Q WSQ to compute the total of orderprice column
from the orders table.
Q WSQ to compute the total of orderprice column
from the orders table group by the category.

Q. WSQ to show the firstname and lastname from


the customer table , alll names must be displayed
in the capital letters in the output.
Q WSQ to show the firstname and lastname from
the customer table where the lastname must be
displayed in the lowercase.
Q WSQ to select the length of values in the
address column of the Student table.
Q WSQ to show productname, price and
currentdateand time from orders table.
Q WSQ to show all the records from the Customer
table and orders table.
Q WSQ to create the view of the student table to
show studentname and marks from student table.
View: can be altered, updated and drop also
ALTER View ADD <column> <datatype> FROM
<tablename>
UPDATE VIEW SET < column><value>
DROP VIEW <viewname>

VIEW: A database view is nothing more than SQL


Statement that is stored in the database with an
associated name. A view is actually a composition
of a table of a predefined SQL Query. A View can
contain all rows of a table or select rows from a
table. View is like virtual table/
View helps in ensuring the data security.
A SQL Join statement is used to combine data or rows from two or more
tables based on a common field between them. Different types of Joins are:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN

Student
StudentCourse

The simplest Join is INNER JOIN.


1. 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.

This query will show the names and age of students enrolled in different
courses.
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE
FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
2 types of inner join
LEFT JOIN: This join returns all the rows of the table on the left side of the
join and matching rows for the table on the right side of join. The rows for
which there is no matching row on right side, the result-set will contain null.
LEFT JOIN is also known as LEFT OUTER JOIN.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the
rows of the table on the right side of the join and matching rows for the table
on the left side of join. The rows for which there is no matching row on left
side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the table

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
FULL JOIN: FULL JOIN creates the result-set by combining result of both
LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from
both the tables. The rows for which there is no matching, the result-set will
contain NULL values.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

CARTESIAN JOIN: The CARTESIAN JOIN is also known as CROSS


JOIN. In a CARTESIAN JOIN there is a join for each row of one table to
every row of another table. This usually happens when the matching
column or WHERE condition is not specified.
 In the absence of a WHERE condition the CARTESIAN JOIN will
behave like a CARTESIAN PRODUCT . i.e., the number of rows in the
result-set is the product of the number of rows of the two tables.
 In the presence of WHERE condition this JOIN will function like a
INNER JOIN.
 Generally speaking, Cross join is similar to an inner join where the
join-condition will always evaluate to True
Syntax:
SELECT table1.column1 , table1.column2, table2.column1...
FROM table1
CROSS JOIN table2;

table1: First table.


table2: Second table
Example Queries(CARTESIAN JOIN):
 In the below query we will select NAME and Age from Student table and
COURSE_ID from StudentCourse table. In the output you can see that
each row of the table Student is joined with every row of the table
StudentCourse. The total rows in the result-set = 4 * 4 = 16.

 SELECT Student.NAME, Student.AGE, StudentCourse.COURSE_ID


 FROM Student
 CROSS JOIN StudentCourse;
Output:

https://www.geeksforgeeks.org/sql-join-set-1-
inner-left-right-and-full-joins/

You might also like