0% found this document useful (0 votes)
43 views

DCL: Stands For Data Control Language. Control The Behaviour of Those Objects. SQL Queries Like GRANT and

SQL is a language used to interact with databases by executing queries, inserting, updating, and deleting data. It includes data definition language (DDL) for defining database objects, data manipulation language (DML) for interacting with data, and data control language (DCL) for controlling access privileges. Joins combine data from multiple tables based on common columns and include inner, left, right, outer, full, and Cartesian joins. Wildcard operators help with pattern matching in queries.

Uploaded by

shivani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

DCL: Stands For Data Control Language. Control The Behaviour of Those Objects. SQL Queries Like GRANT and

SQL is a language used to interact with databases by executing queries, inserting, updating, and deleting data. It includes data definition language (DDL) for defining database objects, data manipulation language (DML) for interacting with data, and data control language (DCL) for controlling access privileges. Joins combine data from multiple tables based on common columns and include inner, left, right, outer, full, and Cartesian joins. Wildcard operators help with pattern matching in queries.

Uploaded by

shivani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

SQL

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%';

Join (Inner, Left, Right and Full Joins)


A SQL Join statement is used to combine data or rows from two or more tables based on a common field between them.
Join/Inner Join is a combination of a Cartesian product followed by a selection process. A Join operation pairs two
tuples from different relations, if and only if a given join condition is satisfied. 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.
Theta (θ) Join- R1 ⋈θ R2, the attributes don‘t have anything in common, that is, R1 ∩ R2 = Φ.
Equijoin- When Theta join uses only equality comparison operator
Natural Join -Natural join does not use any comparison operator. It does not concatenate the way a Cartesian product
does. We can perform a Natural Join only if there is at least one common attribute that exists between two relations. In
addition, the attributes must have the same name and domain.
Outer Joins- Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only those tuples with
matching attributes and the rest are discarded in the resulting relation. Therefore, we need to use outer joins to include all
the tuples from the participating relations in the resulting relation. There are three kinds of outer joins: left outer join,
right outer join, and full outer join.
Left Outer Join /Left Join (R S)- All the tuples from the Left relation, R, are included in the resulting relation. If there
are tuples in R without any matching tuple in the Right relation S, then the S-attributes of the resulting relation are made
NULL. 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.
Right Outer Join /Right Join (R S)- All the tuples from the Right relation, S, are included in the resulting relation. If
there are tuples in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL. 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.
Full Outer Join: (R S)-All the tuples from both participating relations are included in the resulting relation. If there are
no matching tuples for both relations, their respective unmatched attributes are made NULL. 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.
1. SELECT table1.column1,table1.column2,table2.column1,....
2. FROM table1 INNER/LEFT/RIGHT/FULL JOIN table2
3. ON table1.matching_column = table2.matching_column; (matching_column: Column common to both the tables.)

LEFT JOIN RIGHT JOIN FULL JOIN


Page 2 of 11
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 conditions 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
SELECT table1.column1, table1.column2, table2.column1..FROM table1 CROSS JOIN table2;
Self Join-As the name signifies, in SELF JOIN a table is joined to itself. That is, each row of the table is joined with itself
and all other rows depending on some conditions. In other words we can say that it is a join between two copies of the
same table. SELECT a.ROLL_NO , b.NAME FROM Student a, Student b WHERE a.ROLL_NO < b.ROLL_NO;

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 );

How to specify constraints?


We can specify constraints at the time of creating the table using CREATE TABLE statement. We can also specify the
constraints after creating a table using ALTER TABLE statement.
CREATE TABLE sample_table (column1 data_type(size) constraint_name, column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name, ....);

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;

WITH CHECK OPTION


The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is applicable to an updatable view. If the
view is not updatable, then there is no meaning of including this clause in the CREATE VIEW statement.
 The WITH CHECK OPTION clause is used to prevent the insertion of rows in the view where the condition in the
WHERE clause in CREATE VIEW statement is not satisfied.
 If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the UPDATE or
INSERT clause does not satisfy the conditions then they will return an error.
CREATE VIEW SampleView AS
SELECT S_ID, NAME FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the NAME column then it will give an error because the
view is created with the condition for NAME column as NOT NULL.
For example, though the View is updatable but then also the below query for this View is not valid:
INSERT INTO SampleView(S_ID) VALUES(6);
NOTE: The default value of NAME column is null.

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

Example: DATE_FORMAT (NOW (),'%d %b %y') Result: 13 Jan 17

Does SQL support programming language features?


It is true that SQL is a language but it does not support programming as it is not a programming language, it is a
command language. We do not have conditional statements in SQL like for loops or if..else, we only have
commands which we can use to query, update , delete etc. data in the database. SQL allows us to manipulate data in
a database.

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

Difference between BETWEEN and IN operators in SQL


BETWEEN
The BETWEEN operator is used to fetch rows based on a range of values.
SELECT * FROM Students WHERE ROLL_NO BETWEEN 20 AND 30;
This query will select all those rows from the table Students where the value of the field ROLL_NO lies between 20
and 30.
IN
The IN operator is used to check for values contained in specific sets.
SELECT * FROM Students WHERE ROLL_NO IN (20, 21, 23);
This query will select all those rows from the table Students where the value of the field ROLL_NO is either 20 or
21 or 23.

Different types of case manipulation functions available in SQL


There are three types of case manipulation functions available in SQL. They are,
LOWER: The purpose of this function is to return the string in lowercase. It takes a string as argument and returns
the string by converting it into lower case. LOWER('string')
UPPER:The purpose of this function is to return the string in uppercase. It takes a string as argument and returns the
string by converting it into uppercase. UPPER('string')
INITCAP:The purpose of this function is to return the string with first letter in uppercase and rest of the letters in
lowercase. INITCAP('string')
View in SQL
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.
The CREATE VIEW statement of SQL is used for creating Views.
CREATE VIEW view_name AS....SELECT column1, column2.....FROM table_name WHERE condition;

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.

Numeric Functions ():


 ABS (n) – Return the absolute value of `n`. Ex- select ABS (-15) ―Absolute‖ o/p=15
 POWER (m, n)- Return `m` raised `nth` power `n` must be an integer else an error is returned. Ex- select POWER
(3,2) ―Raised‖ from....
 ROUND (n [m])- Return `n` rounded to `m` places right of the decimal point `m` must be an integer. If `m` is
omitted `n` is rounded to 0 places. `m` can be negative to round off digits left of the decimal point. Ex- select
ROUND (15.19, 1) ―ROUND‖ from..
 SQRT (n) – Return square root of `n` if `n` <0, NULL, return a real result. Ex- select SQRT (25) ―SQUARE
ROOT‖ from TN.

String Function ():


 LOWER (char) – return char with all letters in lowercase. Ex- select LOWER (―NEERAJ‖) ―LOWER‖ from TN.
 INITCAP (char) – Return string with the first letter in upper case. Select INITCAP (―NEERAJ‖) ―Title case‖ from
TN.
 UPPER (char)- Return char, with all letters forced to uppercase. Ex- select UPPER (―neeraj‖) from TN. o/p-
NEERAJ.
 Substr (CHAR, M[N])- Return a portion of char, beginning at character `m` exceeding upto `n` characters. If `n` is
omitted, result is returned upto the end char. The first position of char is 1. Ex- select SUBSTR (`neeraj`,3,4)
―substring‖, o/p- eraj
 LENGTH (char)- select LENGTH (`neeraj`) ―length‖...., o/p- 6
 LTRIM (char [, set])- Rename characters from the left of char with initial character removed upto the first character
not in set. Select LTRIM (`neeraj`,n) ―left trim‖ from ...; o/p-eeraj.
 RTRIM (char [, set])- Rename characters with final character removed after the last character not in the set. `set` is
optional. It defaults to spaces. Select RTRIM (`neeraj`,j) ―right trim‖ from ...; o/p-neera.
 LPAD [cha1, n [ ,char2])- return `char1`, left padded to length `n` with the sequence of characters in `char2`, `char2`
defaults to blanks. Ex- select LPAD (`page1`, 10, `*`) ―LPAD‖ from... o/p- *****page1
 RPAD [cha1, n [ ,char2])- return `char1`, right padded to length `n` with the sequence of characters in `char2`,
replicated as many times as necessary – if `char2` is omitted, right-pad is with blanks. Ex- select RPAD (`page1`,
10, `*`) ―RPAD‖ from... o/p- page1*****

Conversion Function ():


 To_Number (Char) - Convert `char` a character values containing a number, to a value of `NUMBER` data type.
UPDATE product SET p=q+ TO_NUMBER (SUBSTR (`$100`, 2, 3));
 To-Char (n, [,fmt])- convert `NUM` to `CHAR` datatype. It accepts (n) number and a numeric format (fmt) in which
the number has to appear. If `fmt` is omitted `n` is converted to a char value exactly long enough to hold significant
digits.
 SELECT TO_CHAR (17145, `$099, 999`) ―char‖ FROM duel; o/p=$017,145
 TO_CHAR (data, [, fmt]) – (date conversion)
 SELECT TO_CHAR (order_date, `Month DD, YYYY`) ―New date format‖ FROM sales_order WHERE
order_no=`78`

Data conversion Function ():


Its default format `DD-MON-YY HH: MI: SS` TO_DATE (char [, frm])
INSERT INTO sales_order (oreder_no, order_date) VALUES (`087650`, TO_DATE (`30-SEP-85 10 :55 AM`, DD-
MON-YY HH:MI:SS‖);

Data Functions ():

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

Query to find 2nd highest salary of an employee?


SELECT max(salary) FROM EMPLOYEES WHERE salary IN (SELECT salary FROM EMPLOYEEs MINUS
SELECT max(salary) FROM EMPLOYEES);
OR
SELECT max(salary) FROM EMPLOYEES WHERE salary <> (SELECT max(salary) FROM EMPLOYEES);

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.

Static (embedded) SQL Dynamic (interactive) SQL


In static SQL how database will be accessed is In dynamic SQL, how database will be accessed is
predetermined in the embedded SQL statement. determined at run time. for example, the application may
allow users to enter their own queries.
More swift and efficient. less swift and efficient.
SQL statements are compiled at compile time. SQL statements are compiled at run time.
Parsing, validation, optimization, and generation of Parsing, validation, optimization, and generation of
application plan are done at compile time. application plan are done at run time.
Data is distributed uniformly. data is distributed non-uniformly
EXECUTE IMMEDIATE, EXECUTE and EXECUTE IMMEDIATE, EXECUTE and PREPARE
PREPARE statements are not used. statements are used.
Page 9 of 11
It is less flexible. It is more flexible.
SQL statements in an application that do not change Dynamic SQL is a programming technique that enables
at runtime and, therefore, can be hard-coded into the you to build. SQL statements dynamically at runtime. You
application. can create more general purpose, flexible applications by
using dynamic SQL because the full text of a SQL
statement may be unknown at compilation.

Difference between CHAR and VARCHAR?


 CHAR and VARCHAR are differing in storage and retrieval.
 CHAR column length is fixed while VARCHAR length is variable.
 The maximum no. of character CHAR data type can hold is 255 character while VARCHAR can hold up to 4000
character.
 CHAR is 50% faster than VARCHAR.
 CHAR uses static memory allocation while VARCHAR uses dynamic memory allocation.
You may also like:

Sno ATTRIBUTE DESCRIPTION


1 ARITHMATIC (+, /, *, -, <, >, ** (Exponentiation, () enclosed operation, /(division))
OPERATORS
2 AGGREGATE Select SUM/ADD/COUNT (data) FROM table name...
FUNCTIONS
3 ALIAS
Renaming column used with expression lists, rename the default output column name with an ALIAS, when
required
 Aliases are created to make table or column names more readable.
 The renaming is just a temporary change and table name does not change in the original database.
 Aliases are useful when table or column names are big or not very readable.
 These are preferred when there are more than one table involved in a query.
SELECT column as alias_name FROM table_name;
For table alias: SELECT column FROM table_name as alias_name;
4 ALTER TABLE ALTER TABLE ADD/DROP/MODIFY (NAME VARCHAR (15)) (change the name of
table/column; decrease the size of column if table data exist.)
5 AND/OR ..where data >100 OR ( data < 300 AND data > 500)
6 BETWEEN (Range) ..where data BETWEEN `100` AND 200
7 CONCATENATE Select CONCATENATE (Neeraj, Rathore)...
8 CONSTRAINT Create table student (sid varchar (5) NOT NULL,.......)
9 CREATE INDEX Create INDEX cus_loc on customer (city, country)
10 CREATE TABLE Create table tablename (column1 data_type(size),...)
CREATE DATABASE A Database is defined as a structured set of data. So, in SQL the very first step to store the
data in a well structured manner is to create a database.
CREATE DATABASE database_name;
11 CREATE VIEW Create VIEW cust_id as select f_name, L_name from customer;
12 DESCRIBE Finding out the colum details of a table created; DESCRIBE tablename;
13 DELETE DELETE from biodata WHERE name= `NEERAJ`; ( Removal of a specified row or all
rows)
14 DISTINCT Select DISTINCT column name from...where...
15 DROP DROP is used to delete a whole database or just a table. The DROP statement destroys the
objects like an existing database, table, index, or view. It removes a component from a
RDBMS.
DROP TABLE table_name; DROP DATABASE database_name;
17 From From is used to give input as relation or set of relations from which data needs to be
selected.
18 EXISTS Select....where... EXIST (select ........from...where)
19 FOREIGN KEY FOREIGN KEY (CUST_ID (dependent table)) REFERENCES (CUST_ID(of main table))
20 FULL OUTER JOIN ..wheretablename1.attribute1(+rows).= tablename2=attribute1(+rows).
21 GROUP BY ...FROM....GROUPBY data.
22 HAVING Use with GROUPBY always, ...GROUPBY...HAVING sum(data) >100;
23 IN ..where data in (`100, `200`)
24 INSERSECTION Select data from Tablename1 INSERSECTION select data from tablename2;
Page 10 of 11
25 INSERT Only values: First method is to specify only the value of data to be inserted without the
column names.
INSERT INTO table_name VALUES (value1, value2, value3,...);
Column names and values both: In the second method we will specify both the columns
which we want to fill and their corresponding values as shown below: INSERT INTO
table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..);
26 JOIN ..where tablename1.attribute1= tablename2=attribute1.
28 LEFT OUTER JOIN ..where tablename1.attribute1(+rows).= tablename2=attribute1.
29 LOGICAL process all rows & display result when all of the condition specified using AND/ any of the
OPERATORS conditions specified using OR/ none of the condition specified using NOT.
(AND/OR/NOT)
30 MINUS Select data from Tablename1 MINUS select data from tablename2;
31 ORDER BY SELECT * FROM table_name ORDER BY column_name ASC|DESC
Sort according to multiple columns:
SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2 ASC|DESC
(by default it is ascending [asen])
32 OUTER JOIN ..where tablename1.attribute1-tablename2.attribute1
33 PRIMARY KEY Create table student (sid varchar (5) PRIMARY KEY,.......) OR {at last, after all attribute
has been formed}PRIMARY KEY (sid );
34 RENAME TABLE RENAME oldtable to newtable
35 RIGHT OUTER JOIN ..where tablename1.attribute1= tablename2=attribute1(+rows).
36 SELECT Selects columns from a relation or set of relations.Note: As opposed to Relational Algebra,
it may give duplicate tuples for repeated value of an attribute.
SELECT name from tablename
37 SUBSTRING Select SUBSTR (name 2,4) from std where name= `Neeraj Kumar`. O/P - ....
38 TABLE VIEW Examine objects created by a user. Select * from tab;
39 TRIM Select TRIM/LTRIM/RTRIM(`Sample`)o/p-`Sam`/ `Sam `/ ` Sam`;
41 TRUNCATE TRUNCATE statement is a DDL operation that is used to mark the extents of a table for
deallocation (empty for reuse). The result of this operation quickly removes all data from a
table, typically bypassing a number of integrity enforcing mechanisms. The TRUNCATE
TABLE mytable statement is logically (though not physically) equivalent to the DELETE
FROM mytable statement (without a WHERE clause). TRUNCATE TABLE table_name;
42 UNION & UNION ALL
The Union Clause is used to combine two separate select statements and produce the result set as a union of both
the select statements.
NOTE:
1. The fields to be used in both the select statements must be in same order, same number and same data type.
2. The Union clause produces distinct values in the result set; to fetch the duplicate values too UNION ALL
must be used instead of just UNION.
Basic Syntax:
SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;
Resultant set consists of distinct values.
SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2;
Resultant set consists of duplicate values too.
SELECT ROLL_NO,NAME FROM Student WHERE ROLL_NO>3
UNION ALL
SELECT ROLL_NO,Branch FROM Student_Details WHERE ROLL_NO<3
ORDER BY 1;
Note:The column names in both the select statements can be different but the data type must be same. And in the
result set the name of column used in the first select statement will appear.
43 UPDATE UPDATE tablename SET age=30 WHERE name=`NEERAJ`;
44 WHERE Where is used to give condition to be used to filter tuples .Where...conditions
45 PAGESIZE To increase the horizontal space of the page.Ex-PAGESIZE tablename;
46 LINESIZE To increase the Vertical space of the page. Ex- LINESIZE tablename
47 TOP Fetch limited number of rows from a database.
SELECT TOP value column1,column2 FROM table_name;
Using Percent
SELECT TOP value PERCENT column1,column2 FROM table_name;

Page 11 of 11

You might also like