DCL: Stands For Data Control Language. Control The Behaviour of Those Objects. SQL Queries Like GRANT and
DCL: Stands For Data Control Language. Control The Behaviour of Those Objects. SQL Queries Like GRANT and
Query: (Response to user) is a statement requesting the retrieval of information. The portion of a DML that involves
information retrieval called query language.
SQL stands for Structured Query Language. It is a language used to interact with the database, i.e to create a database, to
create a table in the database, to retrieve data or update a table in the database etc. SQL is an ANSI(American National
Standards Institute) standard. Using SQL, we can do many things, for example – we can execute queries, we can insert
records in a table, we can update records, we can create a database, we can create a table, we can delete a table etc.
SQL is Structured Query Language designed for inserting and modifying in a relational database system. SQL is a
programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL
comprises both data definition and data manipulation languages. As opposed to Relational Algebra, SQL is a non-
procedural language.
DCL: stands for Data Control Language. Control the behaviour of those objects. SQL queries like GRANT and
REVOKE come under this.
DDL: (Changes in DATABASE)stands for Data Definition Language. SQL queries like CREATE, ALTER, DROP and
RENAME come under this. It helps in creation, modification and removal of definitions that define the organization of
data in database.
DML: stands for Data Manipulation Language. SQL queries like SELECT, INSERT, DELETE and UPDATE come
under this. It helps in insertion, modification and deletion of the actual data in the database. Manipulate data within the
object.DML is responsible for all forms data modification in a data.
SELECT/FROM/WHERE- Select author_name From book_author Where age > 50;
INSERT INTO/VALUES- INSERT INTO table VALUES (value1, [value2, ... ])
UPDATE/SET/WHERE- UPDATE Neeraj SET Author=‖rathore‖ WHERE Author=‖kumar‖;
DELETE FROM/WHERE- DELETE FROM table_name [WHERE condition];
Data Retrieval: It helps in retrieval of data from the database which can be used by applications for various purposes.
User Administration: It helps in registering and monitoring users, enforcing data security, monitoring performance,
maintaining data integrity, dealing with concurrency control and recovering information corrupted by unexpected failure.
Any programming environment used to create containers, to manage human data, can be conceptualized as a Data
Management System. Traditionally, the block of human data being managed is called a database. Hence in very simple
term these programming environments can be conceptualized as DBMS.
A group of `Tables` with `Related` data in them is called a `Database`.
Database is a coherent collection of data with some inherent meaning, designed, built and populated with data for a
specific purpose.
It is successfully design & maintain database.
Identify which part of the world`s data is of interact to.
Identify what specific objects in that part.
Identify a relationship between the objects.
Anomalies
There are different types of anomalies which can occur in referencing and referenced relation which can be discussed as:
Insertion anomaly: If a tuple is inserted in referencing relation and referencing attribute value is not present in
referenced attribute, it will not allow inserting in referencing relation. For Example, If we try to insert a record in
STUDENT_COURSE with STUD_NO =7, it will not allow.
Deletion and Updation anomaly: If a tuple is deleted or updated from referenced relation and referenced attribute value
is used by referencing attribute in referencing relation, it will not allow deleting the tuple from referenced relation. For
Example, If we try to delete a record from STUDENT with STUD_NO =1, it will not allow. To avoid this, following can
be used in query:
ON DELETE/UPDATE SET NULL: If a tuple is deleted or updated from referenced relation and referenced
attribute value is used by referencing attribute in referencing relation, it will delete/update the tuple from referenced
relation and set the value of referenced attribute to NULL.
ON DELETE/UPDATE CASCADE: If a tuple is deleted or updated from referenced relation and referenced
attribute value is used by referencing attribute in referencing relation, it will delete/update the tuple from referenced
relation and referencing relation as well.
Wildcard operators
Wildcard operators are used with LIKE (pattern matching) operator, there are four basic operators: ...LIKE `%A%`, =
compare a single value to another single value, IN- Compared to a list of values and one can check single value agaist
multiple values. NOT IN- do not match all of the values.
Operator Description
% It is used in substitute of zero or more characters.
_ It is used in substitute of one character.
Page 1 of 11
[range_of_characters] It is used to fetch matching set or range of characters specified inside the brackets.
[^range_of_characters] or It is used to fetch non-matching set or range of characters specified inside the brackets.
[!range of characters]
Basic syntax:
SELECT column1,column2 FROM table_name WHERE column LIKE wildcard_operator;
Queries
To fetch records from Student table with NAME ending with letter ‗T‘.
SELECT * FROM Student WHERE NAME LIKE '%T';
To fetch records from Student table with NAME ending any letter but starting from ‗RAMES‘.
SELECT * FROM Student WHERE NAME LIKE 'RAMES_';
To fetch records from Student table with address containing letters ‗a‘, ‗b‘, or ‗c‘.
SELECT * FROM Student WHERE NAME LIKE '%[A-C]%';
To fetch records from Student table with ADDRESS not containing letters ‗a‘, ‗b‘, or ‗c‘.
SELECT * FROM Student WHERE NAME LIKE '%[^A-C]%';
To fetch records from Student table with PHONE feild having a ‗9‘ in 1st position and a ‗5‘ in 4th position.
SELECT * FROM Student WHERE PHONE LIKE '9__5%';
To fetch records from Student table with ADDRESS containing total of 6 characters.
SELECT * FROM Student WHERE ADDRESS LIKE '______';
To fetch records from Student table with ADDRESS containing ‗OH‘ at any position, and the result set should not
contain duplicate data.
SELECT DISTINCT * FROM Student WHERE NAME LIKE '%OH%';
DROP vs TRUNCATE
Truncate is normally ultra-fast and it‘s ideal for deleting data from a temporary table.
Truncate preserves the structure of the table for future use, unlike drop table where the table is deleted with its full
structure.
Table or Database deletion using DROP statement cannot be rolled back, so it must be used wisely.
DATA CONSTRAINTS-
Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the type of
data that can be stored in a particular column in a table using constraints.
Type of data constraints
1. I/O Constraints –
Primary Key Constraint (Unique, not null, atomic, irreducible) &
Foreign Key Constraint (master detail table relationship i) Not data enter in detail if master not exist. ii) Master
table data can`t deleted if corresponding data exist in detail table. Foreign key represent relationships between
tables. A file is column (or group of columns) whose values are derived from the Primary key or unique key of
some other table. Table in which the FK is defined called foreign table or detail table. Table that define primary
or unique key & is referenced by the foreign key is called primary table or master table.
2. Colum level – Data constraint are defined along with the column definition where creating or altering a table
structure.
NOTE—apply only a current a column which is the column that immediately precedes the constraints they are local
to specified column. It can`t be applied if the data constraint spans across multiple column in a table.
3. Table level- If data constraint is defined after defining the entire table column when creating or altering a table
structure must be applied if the data constraint spans across multiple columns in a table.
NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is specified as
NOT NULL then we will not be able to store null in this particular column any more. Ex- CREATE TABLE
Student ( ID int(6) NOT NULL, );
NULL instead any of data type into the column.
UNIQUE: This constraint when specified with a column, tells that all the values in the column must be unique.
That is, the values in any row of a column must not be repeated. Ex-CREATE TABLE Student ( ID int(6) NOT
NULL UNIQUE, );
CHECK constraint takes onger to execute as compared t NOT NULL, PK, FK or UNIQUE. This CHECK
constraints must be avoided if the constraint can be defined using the NOT NULL, PK or FK constraints. Ex-
columnname datatype (size) CHECK (logical expression)
PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this constraint is
used to specify a field in a table as primary key. Ex-CREATE TABLE Student ( ID int(6) NOT NULL
UNIQUE,NAME varchar(10),PRIMARY KEY(ID));
FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And this
constraint is used to specify a field as Foreign key. Ex-CREATE TABLE Orders ( O_ID int NOT NULL,
ORDER_NO int NOT NULL, C_ID int, PRIMARY KEY (O_ID), FOREIGN KEY (C_ID) REFERENCES
Customers(C_ID) )
GROUPBY columnname grouped together and the total quantity ordered for each product is displayed on screen.
HAVING used in conjection with the GROUPBY,. Ex- Select..FROM...GROUPBY...HAVING...
Put condition in GROUPBY use HAVING to do that.
IN SQL priority 1 (NOT) 2 (AND) 3(OR)
CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it helps to
ensure that the value stored in a column meets a specific condition. Ex-CREATE TABLE Student ( ID int(6) NOT
NULL, NAME varchar(10) NOT NULL, AGE int NOT NULL CHECK (AGE >= 18) );
Page 3 of 11
DEFAULT: This constraint specifies a default value for the column when no value is specified by the user. Ex-
CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10) NOT NULL, AGE int DEFAULT 18 );
Comments
As is any programming languages comments matter a lot in SQL also. In this set we will learn about writing comments in
any SQL snippet. Comments can be written in the following three formats:
Single line comments: Comments starting and ending in a single line are considered as single line comments.
Line starting with ‗–‗ is a comment and will not be executed.
Syntax:
--single line comment
--another comment
SELECT * FROM Customers;
Multi line comments: Comments starting in one line and ending in different line are considered as multi line
comments. Line starting with ‗/*‘ is considered as starting point of comment and are terminated when ‗*/‘ is
encountered.
Syntax:
/* multi line comment
another comment */
SELECT * FROM Customers;
In line comments: In line comments are an extension of multi line comments, comments can be stated in between
the statements and are enclosed in between ‗/*‘ and ‗*/‘.
SELECT * FROM /* Customers; */
GROUP BY
Group By is used to group the tuples based on some attribute or set of attributes like counting the no. of students group
by department. The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some
functions. i.e if a particular column has same values in different rows then it will arrange these rows in a group.
Important Points:
GROUP BY clause is used with the SELECT statement.
In the query, GROUP BY clause is placed after the WHERE clause.
In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax:
SELECT column1, function_name(column2) FROM table_name WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;
Group By single column:
SELECT NAME, SUM (SALARY) FROM Employee GROUP BY NAME;
Group By multiple columns:
SELECT SUBJECT, YEAR, Count (*) FROM Student GROUP BY SUBJECT, YEAR;
HAVING Clause
We know that WHERE clause is used to place conditions on columns. use HAVING clause to place conditions to decide
which group will be the part of final result-set. Also we cannot use the aggregate functions like SUM(), COUNT() etc.
with WHERE clause. So we have to use HAVING clause if we want to use any of these functions in the conditions.
Syntax:
SELECT column1, function_name(column2) FROM table_name WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
Example:
SELECT NAME, SUM(SALARY) FROM Employee GROUP BY NAME HAVING SUM(SALARY)>3000;
HAVING clause here to place this condition as the condition is required to be placed on groups not columns.
Views
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in the database. We
can create a view by selecting fields from one or more tables present in the database. A View can either have all the rows
of a table or specific rows based on certain condition.
Creating Views
Page 4 of 11
We can create View using CREATE VIEW statement. A View can be created from a single table or multiple tables.
CREATE VIEW view_name AS
SELECT column1, column2..... FROM table_name WHERE condition;
Creating View from multiple tables: To create a View from multiple tables we can simply include multiple tables in the
SELECT statement.
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks WHERE StudentDetails.NAME = StudentMarks.NAME;
Deleting Views
DROP VIEW view_name;
Updating Views
There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met, then we
will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY
clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables then we will not be
allowed to update the view.
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.
CREATE OR REPLACE VIEW view_name AS
SELECT column1,coulmn2,.. FROM table_name WHERE condition;
Inserting a row in a view:
INSERT view_name(column1, column2 , column3,..) VALUES (value1, value2, value3..);
Deleting a row from a View:
DELETE FROM view_name WHERE condition;
Date functions
In various scenarios instead of date, datetime (time is also involved with date) is used.
In MySql the default date functions are:
NOW(): Returns the current date and time. Example: SELECT NOW(); Output: 2017-01-13 08:03:52
CURDATE(): Returns the current date. Example: SELECT CURDATE(); Output: 2017-01-13
CURTIME(): Returns the current time. Example: SELECT CURTIME(); Output: 08:05:15
DATE(): Extracts the date part of a date or date/time expression. Example: For the below table named ‗Test‘
Id Name BirthTime
4120 Pratik 1996-09-26 16:44:15.581
SELECT Name, DATE(BirthTime) AS BirthDate FROM Test;
Output:
Name BirthTime
Pratik 1996-09-26
EXTRACT (): Returns a single part of a date/time. Syntax: EXTRACT (unit FORM date);
There are several units that can be considered but only some are used such as: MICROSECOND, SECOND,
MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc. And ‗date‘ is a valid date expression.
Page 5 of 11
DATE_ADD (): Adds a specified time interval to a date. DATE_ADD (date, INTERVAL expr type);
Where, date – valid date expression and expr is the number of interval we want to add and type can be one of the
following: MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc.
Id Name BirthTime
4120 Pratik 1996-09-26 16:44:15.581
SELECT Name, DATE_ADD (BirthTime, INTERVAL 1 YEAR) AS BirthTimeModified FROM Test;
Name BirthTime
Pratik 1997-09-26 16:44:15.581
SELECT Name, DATE_ADD (BirthTime, INTERVAL 30 DAY) AS BirthDayModified FROM Test;
Name BirthTime
Pratik 1997-10-26 16:44:15.581
SELECT Name, DATE_ADD (BirthTime, INTERVAL 4 HOUR) AS BirthHourModified FROM Test;
Name BirthTime
Pratik 1997-10-26 20:44:15.581
DATE_SUB(): Subtracts a specified time interval from a date. Syntax for DATE_SUB is same as DATE_ADD just
the difference is that DATE_SUB is used to subtract a given interval of date.
DATEDIFF(): Returns the number of days between two dates. Syntax: DATEDIFF (date1, date2);
DATE_FORMAT(): Displays date/time data in different formats. Syntax: DATE_FORMAT (date,format);
Date is a valid date and format specifies the output format for the date/time. The formats that can be used are:
%a-Abbreviated weekday name (Sun-Sat)
%b-Abbreviated month name (Jan-Dec)
%c-Month, numeric (0-12)
%D-Day of month with English suffix (0th, 1st, 2nd, 3rd)
%d-Day of month, numeric (00-31)
%e-Day of month, numeric (0-31)
%f-Microseconds (000000-999999)
%H-Hour (00-23)
%h-Hour (01-12)
%I-Hour (01-12)
%i-Minutes, numeric (00-59)
%j-Day of year (001-366)
%k-Hour (0-23)
%l-Hour (1-12)
%M-Month name (January-December)
%m-Month, numeric (00-12)
%p-AM or PM
%r-Time, 12-hour (hh:mm:ss followed by AM or PM)
%S-Seconds (00-59)
%s-Seconds (00-59)
%T-Time, 24-hour (hh:mm:ss)
%U-Week (00-53) where Sunday is the first day of week
%u-Week (00-53) where Monday is the first day of week
%V-Week (01-53) where Sunday is the first day of week, used with %X
%v-Week (01-53) where Monday is the first day of week, used with %x
%W-Weekday name (Sunday-Saturday)
%w-Day of the week (0=Sunday, 6=Saturday)
%X-Year for the week where Sunday is the first day of week, four digits, used with %V
%x-Year for the week where Monday is the first day of week, four digits, used with %v
%Y-Year, numeric, four digits
%y-Year, numeric, two digits
Page 6 of 11
differences between SQL and PL/SQL?
SQL PL/SQL
SQL is a query execution or commanding language PL/SQL is a complete programming language
SQL is data oriented language PL/SQL is a procedural language
SQL is very declarative in nature PL/SQL has a procedural nature
It is used for manipulating data It is used for creating applications
We can execute one statement at a time in SQL We can execute block of statements in PL/SQL
SQL tells database, what to do? PL/SQL tells database how to do
We can embed SQL in PL/SQL We can not embed PL/SQL in SQL
The oracle table `DUEL`- Duel is a small oracle worktable, which consist of only one row and one column and contains
the value X in that column. Beside arithmetic calculations, it also supports data retrieval and its formatting. To facilitate
calculations via a SELECT, oracle provide a dummy table called DUEL, against which SELECT statement that are
required to manipulate numeric literals can be fires and output obtained.
Oracle Function () - manipulating data items & returning a result. It also capable of accepting user-specified variable or
constants & operating on then are called arguments.
Scalar functions (Single row functions): - Act on only one value at a time. Ex-LENGTH, returns are result for every
row of a queried table or view.
These functions are based on user input, these too returns single value.
STRING function (work for STRING data type)
NUMERIC function (work for NUMERIC type)
CONVERSION (work for CONVERSION of one type to another)
DATE function (work for DATE data type)
UCASE (): It converts the value of a field to uppercase.
LCASE ():It converts the value of a field to lowercase.
MID ():SELECT MID(NAME,1,4) FROM Students;
LEN (): returns the length of the value in a text field.
ROUND () :SELECT ROUND(column_name,decimals) FROM table_name;
NOTE: Many database systems have adopted the IEEE 754 standard for arithmetic operations, which says that when
any numeric .5 is rounded it results to the nearest even integer i.e, 5.5 and 6.5 both gets rounded off to 6.
NOW () : returns the current system date and time.
FORMAT():is used to format how a field is to be displayed.
Page 7 of 11
SELECT FORMAT(column_name,format) FROM table_name;
Aggregation Function (): Group Functions (Aggregate Functions) Act on set of values. These functions are used to do
operations from the values of the column and a single value is returned.
AVG ([Distinct/All] expression) - Return avg value of expression ignoring NULL values.
MIN ([Distinct/All] expression) - Return minimum value of expression
COUNT (expression) - Return number of rows where expression is NOT NULL
COUNT (*) - Return number of row in table + duplicates + Null values
MAX ([Distinct/All] expression) - Return maximum value of expression
SUM ([Distinct/All] expression)- Return sum of value of expression return a single result row.
FIRST(): returns the first value of the selected column.
LAST (): returns the last value of the selected column.
Page 8 of 11
ADD_MONTHS (d, n)- Select ADD_MONTHS (SYSDATE, 4) from da; Return data after adding the number of months
specified with the function.
LAST_DAY (d)—Select SYSDATE, LAST_DAY (SYSDATE) ―LAST‖ from da; Return the also date of the month
specified with the function.
MONTHS_BETWEEN (d1, d2)- SELECT MONTHS_BETWEEN (`02-FEB-92`, `02-JAN-92`) ―MONTHS‖ FROM da;
NEXT_DAY (day, char) – Return first weekday named `char` after the date. SELECT NEXT_DAY (`04-FEB-98`,
`FRIDAY`) ―Next day‖ from da;
Nested Queried: When one query is a part of other query. Solving nested queries questions can be learnt
There is a table where only one row is fully repeated. Write a Query to find the Repeated row
SELECT name, section FROM tbl GROUP BY name, section HAVING COUNT(*) > 1
Consider the following Employee table. How many rows are there in the result of following query?
ID salary DeptName
1 10000 EC
2 40000 EC
3 30000 CS
4 40000 ME
5 50000 ME
6 60000 ME
7 70000 CS
How many rows are there in the result of following query?
SELECT E.ID FROM Employee E WHERE EXISTS (SELECT E2.salary FROM Employee E2 WHERE
E2.DeptName = 'CS' AND E.salary > E2.salary)
Following 5 rows will be result of query as 3000 is the minimum salary of CS Employees and all these rows are greater
than 30000.
2
4
5
6
7
Name the student who has secured third highest marks using sub queries.
SELECT Emp1.Name FROM Employee Emp1
WHERE 2 = (SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2 WHERE Emp2.Salary > Emp1.Salary )
*LOGIC- Number of people with salary higher than this person will be 2.
Why we cannot use WHERE clause with aggregate functions like HAVING?
The difference between the having and where clause in SQL is that the where clause can NOT be used with aggregates,
but the having clause can. we use WHERE prior to GROUP BY and HAVING after GROUP BY.
The Where clause acts as a pre filter where as Having as a post filter.
The where clause works on row‘s data, not on aggregated data.
Page 11 of 11