STRUCTURED QUERY LANGUAGE
It is a database computer language designed for managing the data
in relational database management systems.
USES OF SQL IN DATABASES
1. executing queries against a database.
2. retrieving data from a database.
3. inserting records into a database.
4. updating records in a database.
5. deleting records from a database.
6. SQL can create new database.
7. creating new tables in a database
8. create stored procedures in a database.
9. creating views in a database.
10. setting permissionson tables, procedures,and
views.
Examples of database management system include Microsoft
SQL server, Oracle, MySQL, Microsoft Access, IBM BD2,
Sybase etc.
DATA DEFINITION LANGUAGE (DDL)
The Data Definition Language (DDL) manages table and
index structure.
The most basic items of DDL are the CREATE, ALTER,
RENAME and DROP statements:
• CREATE creates an object (a table, for example) in
the database.
• DROP deletes an object in the database, usually
irretrievably.
• ALTER modifies the structure an existing object in various
ways—for example, adding a column to an existing table.
DATA MANIPULATION LANGUAGE (DML)
The Data Manipulation Language (DML) is the subset of
SQL used to add, update and delete data.
The acronym CRUD refers to all of the major functions that need
to be implemented in a relational database application to
consider it complete. Each letter in the acronym can
be mapped to a standard SQL statement:
SQL SYNTAX
SQL follows a unique set of rules and guidelines called
syntax.
1. All the SQL statements start with any of the keywords like
SELECT,INSERT, DELETE, UPDATE, DROP.
2. All the statements end with a semi colon (;).
3. SQL is case insensitive which means that SELECT and select
have exactly the same meaning. However, it is good
practice to always write SQL statements in block capitals.
SQL DATA TYPES
SQL supports a number of data types and these are
char (character, Yes or No)
Var char
Text
Numeric
Integer (int)
Float ( values with decimal places)
Decimal
Money etc.
SQL COMPARISON OPERATORS
operato description
r
= Checks if two operands are equal or not, if yes, the condition becomes
true.
!= or Checks if values of two operands are equal or not. If the values are not
<> equal, the condition becomes true.
> Checks if the value of the left operand is greater than the value of the
right operand.
< Checks if the value of the left operand is smaller than the value of the
right operand. if yes, the condition is true.
>= Checks if the value of the left operand is greater than or equal to the
value of the right operand.
operator description
<= Checks if the value of the left operand is
smaller than or equal to the value of the
right operand.
!< Checks if the value of the left operand is
not less than the value of the right
operand. If yes, the condition becomes
true.
!> Checks if the value of the left operand is
not greater than the value of the right
operand, if yes, the condition becomes
true.
THE CREATE TABLE COMMAND
The Create table command is used to create a table in a
database.
The syntax for the command is:
CREATE TABLE table name (
Column 1 datatype,
Column 2 datatype,
Column n datatype,
Primary key (one or more attributes)
);
WRITE SQL COMMANDS TO CREATE THE
FOLLOWING TABLE CALLED STUDENTS:
Student ID First name surname sex
001 adam Sandler M
002 Erina Moyo F
003 Mary Mutema F
CREATING TABLE FROM ANOTHER TABLE
The basic syntax for creating a table from another
table is as follows:
CREATE TABLE new table name AS
SELECT [column 1, column 2… column n]
FROM existing table name
[WHERE];
Write SQL code to create the a table called leaners from table
students with the following columns; first name, surname.
THE INSERT INTO COMMAND
The SQL insert into statement is used to add new rows of data into
a table in the database.
The general syntax of the INSERT INTO command is as follows:
INSERT INTO table name (column 1, column 2, …column n)
VALUES(value 1, value 2, … value n).
column 1, column 2, column n are the names of the columns in
the table into which you want to insert data.
One does not need to specify the column names in the SQL
statement if you are adding values into all the columns, but make
sure the order of values is the same order as the columns in the
table.
NB: string values should be placed inside single quotation marks,
as well as numbers that are declared as string.
Write SQL code to insert data into the students table.
THE CREATE DATABASE COMMAND
Is used to create a new database.
The syntax is as follows:
CREATE DATABASE database name;
THE DROP DATABASE COMMAND
Is used to delete an existing database.
The basic syntax is as follows:
DROP DATABASE database name;
THE USE STATEMENT.
Is used when there are multiple databases in the SQL
schema.
For any operations to be done on a specific database, one
has to select it first.
The syntax is :
USE database name;
To view the list of available databases, use the SHOW
DATABASES COMMAND.
SHOW DATABASES; - It lists all the databases available.
DROP TABLE COMMAND
The SQL DROP TABLE statement is used to remove a table
definition and all the data, indexes, triggers, constraints and
permission specifications for that table.
NOTE − You should be very careful while using this command
because once a table is deleted then all the information
available in that table will also be lost forever. Syntax
The basic syntax of this DROP TABLE statement is as follows
−
DROP TABLE table_name;
SQL SELECT COMMAND
The SQL SELECT statement is used to fetch the data from a
database table which returns this data in the form of a result
table.
These result tables are called result-sets.
The basic syntax for the SELECT statement is as follows:
SELECT column 1, column 2,…column N
FROM table name;
column1, column2... are the fields of a table whose values
one wants to fetch. If one wants to fetch all the fields
available in the field, then one can use the following syntax.
SELECT * FROM table name;
EXAMPLE
DETERMINE THE OUTPUT OF THE FOLLOWING SQL
STATEMENT;
SELECT ID,NAME,SALRY FROM customers;
ANSWER
QUESTION
Write SQL code to retrieve all the records in the table
Answer: SELECT * FROM customers;
SQL- WHERE CLAUSE
The SQL WHERE clause is used to specify a condition while
fetching the data from a single table or by joining with
multiple tables.
If the given condition is satisfied, then only it returns a
specific value from the table.
You should use the WHERE clause to filter the records and
fetching only the necessary records.
The WHERE clause is not only used in the SELECT statement,
but it is also used in the UPDATE, DELETE statement,
SYNTAX
Syntax
The basic syntax of the SELECT statement with the WHERE
clause is as shown below.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
You can specify a condition using the
comparison or logical operators like >, <, =, LIKE, NOT
EXAMPLE:
QUESTION
Write SQL code to retrieve the ID, Name and salary of
workers who earn more than $2000.
SQL – AND AND OR CONJUCTIVE OPERATORS
The SQL AND & OR operators are used to combine multiple
conditions to narrow data in an SQL statement.
These two operators are called as the conjunctive operators.
These operators provide a means to make multiple
comparisons with different operators in the same SQL
statement.
THE AND OPERATOR
The AND operator allows the existence of multiple conditions
in an SQL statement's WHERE clause.
The basic syntax of the AND operator with a WHERE clause is
as follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using the AND
operator.
For an action to be taken by the SQL statement, whether it be
a transaction or a query, all conditions separated by the AND
must be TRUE.
WRITE AN SQL STATEMENT TO FETCH THE ID, NAME,
SALARY AND AGE OF ALL WORKERS YOUNGER THAN 25
THE OR OPERATOR
The OR operator is used to combine multiple conditions in an
SQL statement's WHERE clause.
Syntax
The basic syntax of the OR operator with a WHERE clause is as
follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
You can combine N number of conditions using the OR operator.
For an action to be taken by the SQL statement, whether it be
a transaction or query, the only any ONE of the conditions
separated by the OR must be TRUE
DETERMINE THE RESULTS OF THE FOLLOWING
STATEMENT
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;
SQL UPDATE STATEMENT
The SQL UPDATE Query is used to modify the existing
records in a table.
One can use the WHERE clause with the UPDATE query to
update the selected rows, otherwise all the rows would be
affected.
The basic syntax of the UPDATE statement with a WHERE
CLAUSE is as follows:
UPDATE table name
SET column 1= value 1, column 2= value 2,… column N =
value N
WHERE [condition]
One can combine N number of conditions using the AND or the
OR operators.
EXAMPLE
DETERMINE THE RESULTS OF THE FOLLOWING ;
UPDATE customers
SET address = ‘Pune’
WHERE customer ID = 6;
ANSWER
DETERMINE THE OUTPUT OF THE FOLLOWING;
UPDATE customers
SET address = ‘Pune’, salary = 1000.00
SQL DELETE STATEMENT
The SQL DELETE Query is used to delete the existing records
from a table.
One can use the WHERE clause with a DELETE query to
delete the selected rows, otherwise all the records would be
deleted.
Syntax
The basic syntax of the DELETE query with the WHERE clause
is as follows −
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
EXAMPLE
The following code has a query, which will DELETE a
customer, whose ID is 6.
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;
Now, the CUSTOMERS table would have the following records.
If you want to DELETE all the records from the CUSTOMERS
table, you do not need to use the WHERE clause and the
DELETE query would be as follows.
DELETE FROM CUSTOMERS;
SQL – LIKE CLAUSE
The SQL 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.
The percent sign (%)
The underscore (_)
The percent sign represents zero, one or multiple characters.
The underscore represents a single number or character.
These symbols can be used in combinations.
EXAMPLE
The following table has a few examples showing the WHERE
part having different LIKE clause with '%' and '_' operators −
[Link]. Statement & Description
WHERE SALARY LIKE '200%'
1
Finds any values that start with 200.
WHERE SALARY LIKE '%200%'
2
Finds any values that have 200 in any position.
WHERE SALARY LIKE '_00%'
3
Finds any values that have 00 in the second and third positions.
WHERE SALARY LIKE '2_%_%'
4
Finds any values that start with 2 and are at least 3 characters in length.
WHERE SALARY LIKE '%2'
5
Finds any values that end with 2.
WHERE SALARY LIKE '_2%3'
6
Finds any values that have a 2 in the second position and end with a 3.
WHERE SALARY LIKE '2___3'
7
Finds any values in a five-digit number that start with 2 and end with 3.
CONSIDER THE CUSTOMERS TABLE HAVING THE RECORDS AS SHOWN BELOW.
consider the CUSTOMERS table having the records as shown
below.
GIVE THE OUTPUT
SQL> SELECT * FROM CUSTOMERS
WHERE SALARY LIKE '200%';
ANSWER
SQL TOP CLAUSE
The SQL TOP clause is used to fetch a TOP N number or X
percent records from a table.
The basic syntax of the TOP clause with a SELECT statement
would be as follows.
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE [condition]
SQL> SELECT TOP 3 * FROM CUSTOMERS;
(RETURNS THE FIRST 3 RECORDS IN THE CUSTOMERS TABLE).
SQL- ORDER BY CLAUSE
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.
EXAMPLE
Determine the output of the following SQL
statement:
RESULTS
EXAMPLE 2
Write SQL code to sort the names in descending
order:
Ans-
SQL – GROUP BY CLAUSE
The SQL 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 and precedes the ORDER BY clause.
SQL- DISTINCT KEY WORD
The SQL DISTINCT keyword is used in conjunction with the
SELECT statement to eliminate all the duplicate records and
fetching only unique records.
There may be a situation when you have multiple duplicate
records in a table.
While fetching such records, it makes more sense to fetch
only those unique records instead of fetching duplicate
records.
EXAMPLE
SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY;
(determine the output)
RESULTS
EXAMPLE 2: USING DISTINCT KEYWORD
SQL CONSTRAINTS
Constraints are the rules enforced on the data columns of a
table.
These are used to limit the type of data that can go into a
table.
This ensures the accuracy and reliability of the data in the
database.
Constraints could be either on a column level or a table level.
The column level constraints are applied only to one column,
whereas the table level constraints are applied to the whole
table.
Following are some of the most commonly used constraints
available in SQL.
NOT NULL Constraint − Ensures that a column cannot have
NULL value.
DEFAULT Constraint − Provides a default value for a column
when none is specified.
UNIQUE Constraint − Ensures that all values in a column are
different.
PRIMARY Key − Uniquely identifies each row/record in a
database table.
FOREIGN Key − Uniquely identifies a row/record in any of the
given database table.
CHECK Constraint − The CHECK constraint ensures that all the
values in a column satisfies certain conditions.
INDEX − Used to create and retrieve data from the database
very quickly.
Constraints can be specified when a table is created
with the CREATE TABLE statement or you can use
the ALTER TABLE statement to create constraints
even after the table is created.
Dropping Constraints
Any constraint that you have defined can be
dropped using the ALTER TABLE command with the
DROP CONSTRAINT option.
For example, to drop the primary key constraint in
the EMPLOYEES table, you can use the following
command.
INTEGRITY CONSTRAINTS
Integrity constraints are used to ensure accuracy and
consistency of the data in a relational database.
Data integrity is handled in a relational database through the
concept of referential integrity.
There are many types of integrity constraints that play a role
in Referential Integrity (RI).
These constraints include Primary Key, Foreign Key, Unique
Constraints and other constraints which are mentioned
above.
THE ALTER TABLE COMMAND
The SQL ALTER TABLE command is used to add, delete or
modify columns in an existing table.
You should also use the ALTER TABLE command to add and
drop various constraints on an existing table.
The basic syntax of an ALTER TABLE command to add a New
Column in an existing table is as follows.
The basic syntax of an ALTER TABLE command to DROP
COLUMN in an existing table is as follows.
The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column in a
table is as follows.
The basic syntax of an ALTER TABLE command to
add a NOT NULL constraint to a column in a table is
as follows.
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows.
NULL VALUES
The SQL NULL is the term used to represent a missing value.
A NULL value in a table is a value in a field that appears to
be blank.
A field with a NULL value is a field with no value.
It is very important to understand that a NULL value is
different than a zero value or a field that contains spaces.
SYNTAX
The basic syntax of NULL while creating a table.
NOT NULL signifies that column should always accept an
explicit value of the given data type.
There are two columns where we did not use NOT NULL,
which means these columns could be NULL.
A field with a NULL value is the one that has been left blank
during the record creation.
one must use the IS NULL or IS NOT NULL operators to
check for a NULL value.
SELECT* FROM CUSTOMERS
WHERE salary IS NOT NULL;
( USE IS NULL OPERATOR as well)
SQL TRUNCATE TABLE COMMAND
The SQL TRUNCATE TABLE command is used to delete
complete data from an existing table.
One can also use DROP TABLE command to delete a
complete table but it would remove complete table structure
from the database and one would need to re-create this table
once again if one wishes to store some data.
SYNTAX
The basic syntax of a TRUNCATE TABLE command is as
follows.
TRUNCATE TABLE table_name;
SQL - USING VIEWS
A view is an SQL statement that is stored in the database
with an associated name.
A view is actually a composition of a table in the form of a
predefined SQL query.
A view can contain all rows of a table or select rows from a
table.
A view can be created from one or many tables which
depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do
the following −
1. Structure data in a way that users or classes of users find natural
or intuitive.
2. Restrict access to the data in such a way that a user can see and
(sometimes) modify exactly what they need and no more.
3. Summarize data from various tables which can be used to
generate reports.
CREATING VIEWS
Database views are created using the CREATE VIEW
statement.
Views can be created from a single table, multiple tables or
another view.
To create a view, a user must have the appropriate system
privilege according to the specific implementation.
The basic CREATE VIEW syntax is as follows
One can include multiple tables in their SELECT statement in
a similar way as one uses them in a normal SQL SELECT
query.
Example to create a view from the customers table
THE WITH CHECK OPTION
The WITH CHECK OPTION is a CREATE VIEW statement option.
The purpose of the WITH CHECK OPTION is to ensure that all
UPDATE and INSERTs satisfy the condition(s) in the view
definition.
If they do not satisfy the condition(s), the UPDATE or INSERT
returns an error.
EXAMPLE
The WITH CHECK OPTION in this case should deny
the entry of any NULL values in the view's AGE
column, because the view is defined by data that
does not have a NULL value in the AGE column.
UPDATING A VIEW
INSERTING ROWS INTO A VIEW
one can insert rows in a view in a similar way as you
insert them in a table.
Deleting Rows from a View
Is done the same way we delete rows
from a table, e.g.
This would ultimately delete a row from the base table CUSTOMERS and the
same would reflect in the view itself.
DROPPING VIEWS
SQL – HAVING CLAUSE
The HAVING Clause enables one to specify conditions that
filter which group results appear in the results.
The WHERE clause places conditions on the selected
columns, whereas the HAVING clause places conditions on
groups created by the GROUP BY clause.
SYNTAX
The HAVING clause must follow the GROUP BY clause in a query and must also precede
the ORDER BY clause if used.
EXAMPLE
Following is an example, which would display a record for a
similar age count that would be more than or equal to 2.
SQL –TRANSACTIONS
Transaction Control
The following commands are used to control transactions.
COMMIT − to save the changes.
ROLLBACK − to roll back the changes.
SAVEPOINT − creates points within the groups of
transactions in which to ROLLBACK.
SET TRANSACTION − Places a name on a transaction.
THE COMMIT COMMAND
The COMMIT command is the transactional
command used to save changes invoked by a
transaction to the database.
The COMMIT command saves all the transactions to
the database since the last COMMIT or ROLLBACK
command.
The syntax for the COMMIT command is as follows.
EXAMPLE
The following SQL statement would delete all records which
have age = 25 and save the changes.
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
THE ROLLBACK COMMAND
It reverses changes made to a database.
E.g. DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
THE SAVEPOINT COMMAND
A SAVEPOINT is a point in a transaction when one can roll the
transaction back to a certain point without rolling back the
entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;
EXAMPLE
Following is an example where one plans to delete the three
different records from the CUSTOMERS table.
They want to create a SAVEPOINT before each delete, so that
they can ROLLBACK to any SAVEPOINT at any time to return
the appropriate data to its original state.
To roll back to save point 2,
THE RELEASE SAVEPOINT COMMAND
The RELEASE SAVEPOINT command is used to
remove a SAVEPOINT that you have created.
The syntax for a RELEASE SAVEPOINT command is
as follows.
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK
command to undo transactions performed since the last SAVEPOINT
THE SET TRANSACTION COMMAND
The SET TRANSACTION command can be used to initiate a
database transaction.
This command is used to specify characteristics for the
transaction that follows.
For example, you can specify a transaction to be read only or
read write.
The syntax for a SET TRANSACTION command is as follows.
SQL USEFUL FUNCTIONS
SQL has many built-in functions for performing processing on string or numeric
data. Following is the list of all useful SQL built-in functions −
SQL COUNT Function - The SQL COUNT aggregate function is used to count the
number of rows in a database table.
SQL MAX Function - The SQL MAX aggregate function allows us to select the
highest (maximum) value for a certain column.
SQL MIN Function - The SQL MIN aggregate function allows us to select the
lowest (minimum) value for a certain column.
SQL AVG Function - The SQL AVG aggregate function selects the average value
for certain table column.
SQL SUM Function - The SQL SUM aggregate function allows selecting the total
for a numeric column.
SQL SQRT Functions - This is used to generate a square root of a given number.
SQL RAND Function - This is used to generate a random number using SQL
command.
SQL MIN() AND MAX() FUNCTIONS
SQL COUNT(), AVG() AND SUM() FUNCTIONS
The COUNT() function returns the number of rows that
matches a specified criteria.
The AVG() function returns the average value of a numeric
column.
The SUM() function returns the total sum of a numeric
column.
Note: NULL values are not counted.
SQL JOINS
The SQL Joins clause is used to combine records from two or
more tables in a database. SQL JOIN
A JOIN clause is used to combine rows from two or more
tables, based on a related column between them.
A JOIN is a means for combining fields from two tables by
using values common to each.
There are different types of joins available in SQL −
INNER JOIN − returns rows when there is a match in both
tables.
LEFT JOIN − returns all rows from the left table, even if
there are no matches in the right table.
RIGHT JOIN − returns all rows from the right table, even if
there are no matches in the left table.
FULL JOIN − returns rows when there is a match in one of
the tables.
SELF JOIN − is used to join a table to itself as if the table
were two tables, temporarily renaming at least one table
in the SQL statement.
CARTESIAN JOIN − returns the Cartesian product of the
sets of records from the two or more joined tables.
SQL INNER JOIN KEYWORD
The INNER JOIN keyword selects records that have matching
values in both tables.
Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two
tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER
JOIN), that selects records that have matching values in both tables:
it is noticeable that the join is performed in the WHERE
clause.
Several operators can be used to join tables, such as =, <, >,
<>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be
used to join tables.
However, the most common operator is the equal to symbol.
SQL LEFT JOIN KEYWORD
The LEFT JOIN keyword returns all records from the left table
(table1), and the matched records from the right table
(table2).
The result is NULL from the right side, if there is no match.
Note: The LEFT JOIN keyword returns all records from the left table (Customers),
even if there are no matches in the right table (Orders).
SQL RIGHT JOIN KEYWORD
The RIGHT JOIN keyword returns all records from the right
table (table2), and the matched records from the left table
(table1).
The result is NULL from the left side, when there is no match.
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even
if there are no matches in the left table (Orders).
SQL FULL OUTER JOIN KEYWORD
The FULL OUTER JOIN keyword returns all records
when there is a match in left (table1) or right
(table2) table records.
Note: FULL OUTER JOIN can potentially return very
large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.
Note: The FULL OUTER JOIN keyword returns all matching records from both tables whether the
other table matches or not. So, if there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will
SQL SELF JOIN
A self JOIN is a regular join, but the table is joined with itself.
SQL UNIONS CLAUSE
The SQL UNION clause/operator is used to combine the
results of two or more SELECT statements without returning
any duplicate rows.
To use this UNION clause, each SELECT statement must have
1. The same number of columns selected
2. The same number of column expressions
3. The same data type and
4. Have them in the same order
But they need not have to be in the same length.