You are on page 1of 30

Structured Query Language

By: Smriti Singh


Introduction
• SQL is a standard language for accessing and
manipulating databases.
• SQL became a standard of the American National
Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO)
in 1987
• To build a web site that shows data from a database,
you will need:
1. An RDBMS database program (i.e. MS Access, SQL
Server, MySQL)
2. To use a server-side scripting language, like PHP or
ASP
3. To use SQL to get the data you want
SQL Process
• Step-1:
• Parser: During parse call, the
database performs the following
checks- Syntax check, Semantic check
and Shared pool check. Parser
performs the following checks as
(refer detailed diagram):
• Syntax check – concludes SQL
syntactic validity.
• Semantic check – determines
whether the statement is meaningful
or not.
• Shared Pool check – Every query
possess a hash code during its
execution. So, this check determines
existence of written hash code in
shared pool if code exists in shared
pool then database will not take
additional steps for optimization and
execution.
• Hard Parse and Soft Parse –
If there is a fresh query and its hash code does not exist in shared pool then
that query has to pass through from the additional steps known as hard
parsing otherwise if hash code exists then query does not passes through
additional steps. It just passes directly to execution engine (refer detailed
diagram). This is known as soft parsing.
Hard Parse includes following steps – Optimizer and Row source generation.
• Step-2:
Optimizer: During optimization stage, database must perform a hard parse at
least for one unique DML statement and perform optimization during this
parse. This database never optimizes DDL unless it includes a DML
component such as sub query that require optimization. It is a process in
which multiple query execution plan for satisfying a query are examined and
most efficient query plan is satisfied for execution.
Database catalog stores the execution plans and then optimizer passes the
lowest cost plan for execution.
• Row Source Generation –
The Row Source Generation is a software that receives a optimal execution
plan from the optimizer and produces an iterative execution plan that is
usable by the rest of the database. the iterative plan is the binary program
that when executes by the sql engine produces the result set.
• Step-3:
Execution Engine: Finally runs the query and display the required result.
SQL Data types
RDBMS
• Stands for "Relational Database Management System." An RDBMS is
a DBMS designed specifically for relational databases. Therefore,
RDBMSes are a subset of DBMSes.
• A relational database refers to a database that stores data in a structured
format, using rows and columns. This makes it easy to locate and access
specific values within the database.
• It is "relational" because the values within each table are related to each
other. Tables may also be related to other tables. The relational structure
makes it possible to run queries across multiple tables at once.
• Most well known DBMS applications fall into the RDBMS category.
Examples include Oracle Database, MySQL, Microsoft SQL Server, and
IBM DB2. Some of these programs support non-relational databases, but
they are primarily used for relational database management.
• Examples of non-relational databases include Apache HBase, IBM
Domino, and Oracle NoSQL Database. These type of databases are
managed by other DMBS programs that support NoSQL, which do not fall
into the RDBMS category.
SQL Commands
DDL (Data Definition Language)
• In SQL, DDL are the set of commands used to
define database schema. These commands are
use to change the structure of database objects.
• In simple words, DDL commands are mainly used
for creating or modifying a database/table
structure and schema.
– CREATE
– ALTER
– SP_RENAME
– TRUNCATE
– DROP
• CREATE: The CREATE command in SQL Server is used to create a new database
object. It can be used to create a new table, view, function, stored procedure, etc.
in the database.
Syntax to create a new table in the database:
CREATE TABLE Table_Name (
Column_Name1 Data_Type (Size),
Column_Name2 Data_Type (Size),
Column_NameN Data_Type (Size)
);
• ALTER: The ALTER command in SQL is used to add, modify, or delete,
columns or constraints in an existing table.
This command is used to change the structure of an existing table in the
database.
Syntax to add a new column in an existing table:
ALTER TABLE Table_Name ADD New_Column_Name Data_Type (Size);
Syntax to change the existing column datatype and size:
ALTER TABLE Table_Name ALTER COLUMN Column_Name New_Data_Type
(New_Size)
Syntax to delete an existing column from a table:
ALTER TABLE Table_Name DROP COLUMN Column_Name
• Rename: In SQL Server SP_RENAME is basically a system-defined
stored procedure, which can be used to change the column and table
name.
Syntax to change an existing column name from a table:
SP_RENAME ‘Table_Name.Old_Column_Name’,’New_Column_Name’ ;
Syntax to change an existing table name:
SP_RENAME ‘Old_Table_Name’,’New_Table_Name’ ;
• Truncate : The TRUNCATE command in SQL Server is to delete all the
records from a table, but not the table itself. It doesn’t support the
‘where’ clause, that’s why we can’t delete a specific record.
• DROP: The DROP command in SQL Server is used to remove an
object from the database.
If we use drop command on a table, the table including all the
records and constraints will be removed from the database.
Syntax to use the drop command:
DROP TABLE Table_Name
DML (Data Manipulation Language)
• The DML commands in SQL Server are used
to manipulate or modify the data stored in the
database. These commands can be used to
insert, update, or delete the records from the
database.
– INSERT
– UPDATE
– DELETE
• INSERT : The INSERT command in SQL Server is used to add a new record in the table.
Syntax to use the Insert command:
INSERT INTO Table_Name (Column_Name1, Column_Name2, ColumnN) VALUES (Value1,
Value2, ValueN);
• UPDATE : The UPDATE command in SQL server is used to change or modify the
existing records in a table.
Syntax to use the Update command:
To update all the records for the particular columns
UPDATE Table_Name SET Column_Name1 = Value1, Column_Name2 = Value2, ColumnN =
ValueN;
To update specific records based on where condition
UPDATE Table_Name SET Column_Name1 = Value1, Column_Name2 = Value2,
ColumnN = ValueN WHERE condition;
• DELETE :The DELETE command in SQL Server is used to delete one or more
existing records from a table.
Syntax to use the Delete command:
To delete specfic records
DELETE FROM Table_Name WHERE condition;
To delete all the records
DELETE FROM Table_Name ;
DCL (Data Control Language)
• The DCL commands in SQL Server is mainly deal with the
right, permissions, and other security-related issues,
Using DCL commands a user can be allowed to access the
information from a database.
• We can grant a user with various privileges on single or
multiple tables. These permissions can be applicable for a
user to use the commands
such as SELECT, INSERT, UPDATE, DELETE, REFERENCES, ALTER,
or ALL on a table.
• Following are the DCL Commands:
– GRANT: Grant command in SQL server is used for granting a user
access privileges or other privileges to the database.
– REVOKE: Withdraws or take back some or all the user’s access
privileges to the database given by using the GRANT command.
TCL (Transaction Control Language)
• The TCL commands in SQL Server is used to manage the transaction or the
changes made by DML statements like INSERT, UPDATE and DELETE in a table. The
following are the TCL commands:
• COMMIT: Commit command in SQL Server is used to save all the changes or
transactions permanently into the database.
Syntax to use the commit command.
COMMIT;
• ROLLBACK: The Rollback command in SQL Server is used to undo or restores
the database to the last committed state in case of any error.
After the rollback, it releases the transaction locks acquired on the tables.
Syntax to use the Rollback command.
ROLLBACK ;
• SAVEPOINT (SAVE TRANSACTION): Savepoint command in SQL Server is used
to save a transaction temporarily. So, that we can Rollback to a certain state
or point whenever required. Example
INSERT INTO EmployeeDetails VALUES(104,'Sameer',30000);
// Create a savepoint after the first INSERT
SAVE TRANSACTION A;
DQL (Data Query Language)
• SELECT : The select statement in SQL Server is used to fetch the
records from the database. It can be used to access the data from
the database based on the condition using the ‘where’ clause.
Syntax
SELECT expressions FROM Table_Name WHERE conditions;
• Insert: The SQL INSERT INTO Statement is used to add new rows of data to a
table in the database.
Syntax
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
• Update: It is used to modify the existing records in a table. You can use
the WHERE clause with the UPDATE query to update the selected rows,
otherwise all the rows would be affected.
Syntax
UPDATE table_name SET column1 = value1, column2 = value2...., columnN =
valueN WHERE [condition];
FILTERS
• Like: Clause is used to compare a value to similar values using wildcard
operators. There are two wildcards used in conjunction with the LIKE
operator. 1. The percent sign (%) 2. The underscore (_)
• Syntax
• SELECT FROM table_name WHERE column LIKE 'XXXX%'
• SELECT FROM table_name WHERE column LIKE 'XXXX_'
• ORDER BY: Clause is used to sort the data in ascending or descending
order, based on one or more columns. Some databases sort the query
results in an ascending order by default.
Syntax
SELECT column-list FROM table_name [WHERE condition] [ORDER BY
column1, column2, .. columnN] [ASC | DESC];
• GROUP BY: clause is used in collaboration with the SELECT
statement to arrange identical data into groups. This GROUP BY
clause follows the WHERE clause in a SELECT statement .
Syntax
SELECT column1, column2 FROM table_name WHERE [ conditions ]
GROUP BY column1, column2
• DISTINCT keyword is used in conjunction with the SELECT
statement to eliminate all the duplicate records and fetching only
unique records.
Syntax
SELECT DISTINCT column1, column2,.....columnN FROM table_name
WHERE [condition]
Joins
• A JOIN clause is used to combine rows from two or more tables,
based on a related column between them.
• Different Types of SQL JOINs
1. (INNER) JOIN: Returns records that have matching values in both
tables
2. LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
3. RIGHT (OUTER) JOIN: Returns all records from the right table, and
the matched records from the left table
4. FULL (OUTER) JOIN: Returns all records when there is a match in
either left or right table
Inner join Syntax
SELECT column_name(s)
FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;
Left Join Syntax
SELECT column_name(s)
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;
Right Join Syntax
SELECT column_name(s)
FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Full Outer Join Syntax
SELECT column_name(s)
FROM table1 FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
SQL Constraints
• Constraints are used to limit the type of data that can go into a table.
• SQL constraints are used to specify rules for the data in a table.
• Constraints can be column level or table level. Column level constraints
apply to a column, and table level constraints apply to the whole table.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
• The following constraints are commonly used in SQL:
1. NOT NULL - Ensures that a column cannot have a NULL value
2. UNIQUE - Ensures that all values in a column are different
3. PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
4. FOREIGN KEY - Prevents actions that would destroy links between tables
5. Default
6. check
Aggregate Functions
• The MIN() function returns the smallest value of the selected column.
Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;

• The MAX() function returns the largest value of the selected column.
Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;

• The COUNT() function returns the number of rows that matches a


specified criterion.
Syntax
SELECT COUNT(column_name)
FROM table_name;
• The AVG() function returns the average value of a numeric column.
Syntax
SELECT AVG(column_name)
FROM table_name;

• The SUM() function returns the total sum of a numeric column.


Syntax
SELECT SUM(column_name)
FROM table_name;
• SQL Aliases
• SQL aliases are used to give a table, or a column in a table, a temporary
name.
• Aliases are often used to make column names more readable.
• An alias only exists for the duration of that query.
• An alias is created with the AS keyword.
Syntax
SELECT column_name AS alias_name
FROM table_name;
Logical Operators
• AND: The AND operator displays a record if all the conditions separated
by AND are TRUE.
• SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
• OR: The OR operator displays a record if any of the conditions separated
by OR is TRUE.
• SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
• NOT: The NOT operator displays a record if the condition(s) is NOT TRUE.
• SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Conti….
• Between: The BETWEEN operator selects values within a given range.
The values can be numbers, text, or dates.
• The BETWEEN operator is inclusive: begin and end values are included.
• SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
• Exists: The EXISTS operator is used to test for the existence of any
record in a subquery.
• The EXISTS operator returns TRUE if the subquery returns one or more
records.
• SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Normalization
• Normalization is a database design technique
that reduces data redundancy and eliminates
undesirable characteristics like Insertion,
Update and Deletion Anomalies.
Normalization rules divides larger tables into
smaller tables and links them using
relationships.
1NF (First Normal Form) Rules
Each table cell should contain a single value.
Each record needs to be unique.
2NF (Second Normal Form) Rules
• Rule 1- Be in 1NF
• Rule 2- Single Column Primary Key
3NF (Third Normal Form) Rules
• Rule 1- Be in 2NF
• Rule 2- Has no transitive functional dependencies
• A transitive functional dependency is when changing a non-key co
lumn, might cause any of the other non-key columns to change

• 3NF
Boyce Codd normal form (BCNF)
• BCNF is the advance version of 3NF. It is stricter
than 3NF.
• A table is in BCNF if every functional dependency
X → Y, X is the super key of the table.

In the above table Functional dependencies


are as follows:
THANK
YOU

You might also like