DataBase SQL
DataBase SQL
com
Table of Contents
SQL Overview................................................................................................................................................................................................................... 3
What is SQL? .................................................................................................................................................................................................................... 3
Why SQL? ......................................................................................................................................................................................................................... 3
SQL Process: ..................................................................................................................................................................................................................... 3
SQL Commands: .............................................................................................................................................................................................................. 3
DDL - Data Definition Language: .................................................................................................................................................................................... 4
DML - Data Manipulation Language: ............................................................................................................................................................................. 4
DCL - Data Control Language: ....................................................................................................................................................................................... 4
DQL - Data Query Language: ......................................................................................................................................................................................... 4
SQL RDBMS Concepts .................................................................................................................................................................................................... 4
What is NULL value? ....................................................................................................................................................................................................... 5
SQL Constraints: .............................................................................................................................................................................................................. 5
Data Integrity: .................................................................................................................................................................................................................. 5
Integrity Constraints: ....................................................................................................................................................................................................... 5
NOT NULL (Presence Check) Constraint: ..................................................................................................................................................................... 5
DEFAULT Constraint:..................................................................................................................................................................................................... 6
Drop Default Constraint: ................................................................................................................................................................................................. 6
UNIQUE Constraint: ........................................................................................................................................................................................................ 7
DROP a UNIQUE Constraint: ......................................................................................................................................................................................... 7
PRIMARY Key:................................................................................................................................................................................................................ 7
Create Primary Key: ........................................................................................................................................................................................................ 8
Delete Primary Key: ......................................................................................................................................................................................................... 8
FOREIGN Key: ................................................................................................................................................................................................................ 8
DROP a FOREIGN KEY Constraint: ............................................................................................................................................................................. 9
CHECK Constraint: ......................................................................................................................................................................................................... 9
DROP a CHECK Constraint: ........................................................................................................................................................................................ 10
INDEX:............................................................................................................................................................................................................................ 10
DROP an INDEX Constraint:........................................................................................................................................................................................ 11
Database Normalization ................................................................................................................................................................................................. 11
First Normal Form ......................................................................................................................................................................................................... 11
Second Normal Form ..................................................................................................................................................................................................... 13
Third Normal Form ........................................................................................................................................................................................................ 14
SQL Syntax ..................................................................................................................................................................................................................... 15
SQL Data Types .............................................................................................................................................................................................................. 19
Exact Numeric Data Types: ........................................................................................................................................................................................... 19
Approximate Numeric Data Types: ............................................................................................................................................................................... 19
Date and Time Data Types:............................................................................................................................................................................................ 19
Character Strings Data Types: ...................................................................................................................................................................................... 19
Unicode Character Strings Data Types: ........................................................................................................................................................................ 20
Binary Data Types: ......................................................................................................................................................................................................... 20
SQL Operators................................................................................................................................................................................................................ 20
SQL Comparison Operators: ......................................................................................................................................................................................... 22
SQL Logical Operators: ................................................................................................................................................................................................. 24
SQL NULL Values.......................................................................................................................................................................................................... 27
SQL CREATE Database ................................................................................................................................................................................................ 28
DROP or DELETE Database ......................................................................................................................................................................................... 28
SQL SELECT Database ................................................................................................................................................................................................. 28
SQL CREATE Table ...................................................................................................................................................................................................... 29
SQL DROP or DELETE Table ...................................................................................................................................................................................... 31
SQL Overview
What is SQL?
SQL is Structured Query Language, which is a computer language for Relation Database System for
storing, manipulating and retrieving data stored in relational database. A query is a way of searching
and extracting data from a database to find the answer to a question. The query/search checks each
record and produces a list of data that satisfies the query criteria.
All relational database management systems (DBMS) like MySQL, MS Access, Oracle, Sybase,
Informix, postgres and SQL Server use SQL as standard database language.
Also, they are using different dialects, such as:
MS SQL Server using T-SQL,
Oracle using PL/SQL,
MS Access version of SQL is called JET SQL (native format) etc.
Why SQL?
Allows users to access data in relational database management systems.
Allows users to describe the data.
Allows users to define the data in database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries & pre-compilers.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a database.
Allows users to set permissions on tables, procedures and views
SQL Process:
When you are executing an SQL command for any RDBMS, the system determines the best way to
carry out your request and SQL engine figures out how to interpret the task.
There are various components included in the process. These components are Query Dispatcher,
Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine handles
all non-SQL queries, but SQL query engine won't handle logical files.
Following is a simple diagram showing SQL Architecture:
SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be classified into groups based on their nature:
A file or table such as the one above consists of a number of records. A record is represented as a row
in a table. A record consists of data items related to an object or person. A field is part of a record that
stores a single data item. In a table, each field is represented by a column and is referenced by its field
name (the column title). The key field (or primary key) is the field used to uniquely identify one
record. In the table above the key field is CustomerID; each customer has a unique ID.
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL
and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd.
SQL Constraints:
Constraints are the rules enforced on data columns on table that to limits 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 column level or table level. Column level constraints are applied only to one
column, whereas table level constraints are applied to the whole table.
Following are 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 identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.
INDEX: Use to create and retrieve data from the database very quickly.
Data Integrity:
The following categories of the data integrity exist with each RDBMS:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the type, the format,
or the range of values.
Referential Integrity: Rows cannot be deleted which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall into entity,
domain, or referential integrity.
Integrity Constraints:
Integrity constraints are used to ensure accuracy and consistency of 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 mentioned above.
Here, NOT NULL signifies that column should always accept an explicit value of the given data type.
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to SALARY
column in Oracle and MySQL, you would write a statement similar to the following:
DEFAULT Constraint:
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement
does not provide a specific value.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
SALARY column is set to 5000.00 by default, so in case INSERT INTO statement does not provide a
value for this column. Then by default this column would be set to 5000.00.
If CUSTOMERS table has already been created without Default constraint, then to add it to SALARY
column, you would write a statement similar to the following:
UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a particular column. In
the CUSTOMERS table, for example, you might want to prevent two or more people from having
identical age.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
AGE column is set to UNIQUE, so that you cannot have two records with same age:
If CUSTOMERS table has already been created without UNIQUE constraint, then to add it to AGE
column, you would write a statement similar to the following:
You can also use following syntax, which supports naming the constraint in multiple columns as well:
If you are using MySQL, then you can use the following syntax:
PRIMARY Key:
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When multiple
fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the same
value of that field(s).
Note: You would use these concepts while creating database tables.
To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already exists
without it, use the following SQL syntax:
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table
already exists without it, use the following SQL syntax:
FOREIGN Key:
A foreign key is a key used to link two tables together. This is sometimes called a referencing key.
Foreign Key is a column or a combination of columns whose values match a Primary Key in a different
table.
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in
the second table.
If a table has a primary key defined on any field(s), then you cannot have two records having the same
value of that field(s). Example:
Consider the structure of the two tables as follows:
CUSTOMERS table:
ORDERS table:
If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for
specifying a foreign key by altering a table
CHECK Constraint:
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn’t entered into the table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
we add a CHECK with AGE column, so that you cannot have any CUSTOMER below 18 years:
If CUSTOMERS table has already been created without a CHECK constraint, then to add it to AGE
column, you would write a statement similar to the following
You can also use following syntax, which supports naming the constraint in multiple columns as well:
INDEX:
The INDEX is used to create and retrieve data from the database very quickly. Index can be created by
using single or group of columns in a table. When index is created, it is assigned a ROWID for each
row before it sorts out the data. Proper indexes are good for performance in large databases, but
you need to be careful while creating index. Selection of fields depends on what you are using in your
SQL queries. Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns:
Now, you can create index on single or multiple columns using the following syntax
To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL syntax
Database Normalization
Database normalization is the process of efficiently organizing data in a database. There are two
reasons of the normalization process:
Eliminating redundant data, for example, storing the same data in more than one table.
Ensuring data dependencies make sense.
Both of these are worthy goals as they reduce the amount of space a database consumes and ensure
that data is logically stored. Normalization consists of a series of guidelines that help guide you in
creating a good database structure.
Normalization guidelines are divided into normal forms; think of form as the format or the way a
database structure is laid out. The aim of normal forms is to organize the database structure so that it
complies with the rules of first normal form, then second normal form, and finally third normal form.
The Normal Forms are:
First Normal Form (1NF)
Second Normal Form (2NF)
Third Normal Form (3NF)
First Normal Form
First normal form (1NF) sets the very basic rules for an organized database:
Define the data items required, because they become the columns in a table. Place related data
items in a table.
Ensure that there are no repeating groups of data.
Ensure that there is a primary key.
Consider we have the following table:
So if we populate this table for a single customer having multiple orders, then it would be something as
follows
But as per 1NF, we need to ensure that there are no repeating groups of data. So let us break above table
into two parts and join them using a key as follows:
CUSTOMERS table:
ORDERS table:
The final rule of the first normal form, create a primary key for each table which we have already
created.
This table is in first normal form, in that it obeys all the rules of first normal form. In this table, the
primary key consists of CUST_ID and ORDER_ID. Combined, they are unique assuming same
customer would hardly order same thing.
However, the table is not in second normal form because there are partial dependencies of primary
keys and columns. CUST_NAME is dependent on CUST_ID, and there's no real link between a
customer's name and what he purchased. Order detail and purchase date are also dependent on
ORDER_ID, but they are not dependent on CUST_ID, because there's no link between a CUST_ID and
an ORDER_DETAIL or their SALE_DATE.
To make this table comply with second normal form, you need to separate the columns into three
tables. First, create a table to store the customer details as follows:
Finally, create a third table storing just CUST_ID and ORDER_ID to keep track of all the orders for a
customer:
The dependency between zip code and address is called a transitive dependency. To comply with
third normal form, all you need to do is move the Street, City, and State fields into their own table,
which you can call the Zip. Code table:
The advantages of removing transitive dependencies are mainly twofold. First, the amount of data
duplication is reduced and therefore your database becomes smaller.
The second advantage is data integrity. When duplicated data changes, there's a big risk of updating
only some of the data (Data Inconsistency), especially if it's spread out in a number of different places
in the database. For example, if address and zip code data were stored in three or four different tables,
then any changes in zip codes would need to ripple out to every record in those three or four tables
SQL Syntax
SQL is followed by unique set of rules and guidelines called Syntax. This tutorial gives you a quick
start with SQL by listing all the basic SQL Syntax:
All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE,
ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;).
Important point to be noted is that SQL is case insensitive, which means SELECT and select have same
meaning in SQL statements, but MySQL makes difference in table names. So if you are working with
MySQL, then you need to give table names as they exist in the database.
Note: Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy.
Character Strings Data Types:
SQL Operators
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to
perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple
conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions
SQL Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20, then:
Make sure you have admin privilege before creating any database. Once a database is created, you can
check it in the list of databases as follows
NOTE: Be careful before using this operation because by deleting an existing database would result in
loss of complete information stored in the database.
Make sure you have admin privilege before dropping any database. Once a database is dropped, you
can check it.
Now, if you want to work with AMROOD database, then you can execute the following SQL command
and start working with AMROOD database:
CREATE TABLE is the keyword telling the database system what you want to do. In this case, you
want to create a new table. The unique name or identifier for the table follows the CREATE TABLE
statement.
Then in brackets comes the list defining each column in the table and what sort of data type it is. The
syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE statement and
the SELECT statement. You can check complete details at Create Table Using another Table.
Create Table Using another Table
A copy of an existing table can be created using a combination of the CREATE TABLE statement and
the SELECT statement.
The new table has the same column definitions. All columns or specific columns can be selected.
When you create a new table using existing table, new table would be populated using existing values
in the old table.
Syntax:
The basic syntax for creating a table from another table is as follows:
Here, column1, column2...are the fields of existing table and same would be used to create fields of
new table.
Example:
Following is an example, which would create a table SALARY using CUSTOMERS table and having
fields customer ID and customer SALARY:
This would create new table SALARY, which would have the following records:
Example:
Following is an example, which creates a CUSTOMERS table with ID as primary key and NOT NULL
are the constraints showing that these fields cannot be NULL while creating records in this table:
You can verify if your table has been created successfully by looking at the message displayed by the
SQL server, otherwise you can use DESC command as follows:
Now, you have CUSTOMERS table available in your database which you can use to store required
information related to customers.
Example:
Let us first verify CUSTOMERS table and then we would delete it from the database:
This means CUSTOMERS table is available in the database, so let us drop it as follows:
Now, if you would try DESC command, then you would get error as follows
Here, column1, column2,...columnN are the names of the columns in the table into which you want to
insert data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all the
columns of the table. But make sure the order of the values is in the same order as the columns in the
table. The SQL INSERT
INTO syntax would be as follows:
Example:
Following statements would create six records in CUSTOMERS table:
You can create a record in CUSTOMERS table using second syntax as follows:
All the above statements would produce the following records in CUSTOMERS table:
Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch
all the fields available in the field, then you can use the following syntax:
Example:
Consider the CUSTOMERS table having the following records:
Following is an example, which would fetch ID, Name and Salary fields of the customers available in
CUSTOMERS table:
If you want to fetch all the fields of CUSTOMERS table, then use the following query:
The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE
statement, etc., which we would examine in subsequent chapters.
Syntax:
The basic syntax of SELECT statement with WHERE clause is as follows:
You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT etc. Below
examples would make this concept clear
Example:
Consider the CUSTOMERS table having the following records:
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table
where salary is greater than 2000:
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table
for a customer with name Hardik. Here, it is important to note that all the strings should be given inside
single quotes ('') whereas numeric values should be given without any quote as in above example:
The SQL AND and OR operators are used to combine multiple conditions to narrow data in an SQL
statement. These two operators are called 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.
Syntax:
The basic syntax of AND operator with WHERE clause is as follows:
You can combine N number of conditions using AND operator. For an action to be taken by the SQL
statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE.
Example:
Consider the CUSTOMERS table having the following records:
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table
where salary is greater than 2000 AND age is less than 25 years:
The OR Operator:
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
Syntax:
The basic syntax of OR operator with WHERE clause is as follows
You can combine N number of conditions using OR operator. For an action to be taken by the SQL
statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR
must be TRUE.
Example:
Consider the CUSTOMERS table having the following records:
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table
where salary is greater than 2000 OR age is less than 25 years:
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not
need to use WHERE clause and UPDATE query would be as follows:
Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:
If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE
clause and DELETE query would be as follows
You can combine N number of conditions using AND or OR operators. Here, XXXX could be any
numeric or string value
Example:
Here are number of examples showing WHERE part having different LIKE clause with '%' and '_'
operators:
Let us take a real example, consider the CUSTOMERS table having the following records:
Following is an example, which would display all the records from CUSTOMERS table where
SALARY starts with 200:
You can use more than one column in the ORDER BY clause. Make sure whatever column you are
using to sort, that column should be in column-list.
Example:
Consider the CUSTOMERS table having the following records:
Following is an example, which would sort the result in ascending order by NAME and SALARY:
Following is an example, which would sort the result in descending order by NAME:
SQL Group By
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical
data into groups. The GROUP BY clause follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
Example:
Consider the CUSTOMERS table having the following records:
If you want to know the total amount of salary on each customer, then GROUP BY query would be as
follows:
Now, let us have following table where CUSTOMERS table has the following records with duplicate
names:
Now again, if you want to know the total amount of salary on each customer, then GROUP BY query
would be as follows:
Example:
Consider the CUSTOMERS table having the following records:
First, let us see how the following SELECT query returns duplicate salary records:
This would produce the following result where salary 2000 is coming twice which is a duplicate record
from the original table.
Now, let us use DISTINCT keyword with the above SELECT query and see the result:
This would produce the following result where we do not have any duplicate entry
You can use more than one column in the ORDER BY clause. Make sure whatever column you are
using to sort, that column should be in column-list.
Example:
Consider the CUSTOMERS table having the following records:
Following is an example, which would sort the result in ascending order by NAME and SALARY:
Following is an example, which would sort the result in descending order by NAME:
To fetch the rows with own preferred order, the SELECT query would be as follows:
This will sort customers by ADDRESS in your own Order of preference first and in a natural order for
the remaining addresses. Also remaining Addresses will be sorted in the reverse alpha order.
SQL Joins
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each.
Consider the following two tables, (a) CUSTOMERS table is as follows:
Now, let us join these two tables in our SELECT statement as follows:
Here, 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 symbol.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more
joined tables.
INNER JOIN
The most frequently used and important of the joins is the INNER JOIN. They are also referred to as
an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of table1 with each row of table2
to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column
values for each matched pair of rows of A and B are combined into a result row.
Syntax:
The basic syntax of INNER JOIN is as follows:
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Now, let us join these two tables using INNER JOIN as follows
LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table.
This means that if the ON clause matches 0 (zero) records in right table, the join will still return a row
in the result, but with NULL in each column from right table.
This means that a left join returns all the values from the left table, plus matched values from the right
table or NULL in case of no matching join predicate.
Syntax:
The basic syntax of LEFT JOIN is as follows:
Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Now, let us join these two tables using LEFT JOIN as follows:
RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the left
table. This means that if the ON clause matches 0 (zero) records in left table, the join will still return a
row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from the left
table or NULL in case of no matching join predicate.
Syntax:
The basic syntax of RIGHT JOIN is as follows:
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Now, let us join these two tables using RIGHT JOIN as follows:
FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches on
either side.
Syntax:
The basic syntax of FULL JOIN is as follows:
Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Now, let us join these two tables using FULL JOIN as follows:
If your Database does not support FULL JOIN like MySQL does not support FULL JOIN, then you
can use UNION ALL clause to combine two JOINS as follows:
SELF JOIN
The SQL 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.
Syntax:
The basic syntax of SELF JOIN is as follows:
Here, WHERE clause could be any given expression based on your requirement
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the cartesian product of the sets of records from the
two or more joined tables. Thus, it equates to an inner join where the join-condition always evaluates
to True or where the join-condition is absent from the statement.
Syntax:
The basic syntax of INNER JOIN is as follows:
Example:
Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Now, let us join these two tables in our SELECT statement as follows:
Here given condition could be any given expression based on your requirement.
Now, let us join these two tables in our SELECT statement as follows:
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Example:
Now, CUSTOMERS table is changed and following would be output from SELECT statement:
Now, CUSTOMERS table is changed and following would be output from SELECT statement:
Example:
Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 58
Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]
Now, CUSTOMERS table is truncated and following would be the output from SELECT statement:
The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER
BY clause if used. The following is the syntax of the SELECT statement, including the HAVING
clause:
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
Following is the example, which would display record for which similar age count would be more than
or equal to 2:
Example:
Consider the CUSTOMERS table having the following records:
Example:
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy
complete
CUSTOMERS table into CUSTOMERS_BKP, following is the syntax:
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows:
Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose
AGE is greater than or equal to 27:
This would impact two rows and finally CUSTOMERS table would have the following records:
Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
Following example deletes records from CUSTOMERS table for all the customers whose AGE is
greater than or equal to 27:
This would impact two rows and finally CUSTOMERS table would have the following records:
Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE
Now suppose based on the above table you want to count total number of rows in this table, then you
can do it as follows:
Similarly, if you want to count the number of records for Zara, then it can be done as follows:
NOTE: All the SQL queries are case insensitive, so it does not make any difference if you give ZARA
or Zara in WHERE CONDITION.
Now suppose based on the above table you want to fetch maximum value of daily_typing_pages, then
you can do so simply using the following command:
You can find all the records with maximum value for each name using GROUP BY clause as follows:
You can use MIN Function along with MAX function to find out minimum value as well. Try out the
following example:
Now suppose based on the above table you want to fetch minimum value of daily_typing_pages, then
you can do so simply using the following command:
You can find all the records with minimum value for each name using GROUP BY clause as follows:
You can use MIN Function along with MAX function to find out minimum value as well. Try out the
following example:
Now suppose based on the above table you want to calculate average of all the dialy_typing_pages,
then you can do so by using the following command:
Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 67
Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]
You can take average of various records set using GROUP BY clause. Following example will take
average all the records related to a single person and you will have average typed pages by every person.
Now suppose based on the above table you want to calculate total of all the dialy_typing_pages, then
you can do so by using the following command:
You can take sum of various records set using GROUP BY clause. Following example will sum up all
the records related to a single person and you will have total typed pages by every person
You are seeing float value here because internally SQL will manipulate square root in float data type.
You can use SQRT function to find out square root of various records as well. To understand SQRT
function in more detail, consider an employee_tbl table, which is having the following records:
Now suppose based on the above table you want to calculate square root of all the dialy_typing_pages,
then you can do so by using the following command:
When invoked with an integer argument, RAND( ) uses that value to seed the random number generator.
Each time you seed the generator with a given value, RAND( ) will produce a repeatable series of
numbers:
You can use ORDER BY RAND() to randomize a set of rows or values as follows:
To understand ORDER BY RAND() function, consider an employee_tbl table, which is having the
following records:
To understand CONCAT function in more detail, consider an employee_tbl table, which is having the
following records
Now suppose based on the above table you want to concatenate all the names employee ID and
work_date, then you can do it using the following command:
You can include multiple tables in your SELECT statement in very similar way as you use them in
normal SQL SELECT query.
Example:
Consider the CUSTOMERS table having the following records:
Now, following is the example to create a view from CUSTOMERS table. This view would be used to
have customer name and age from CUSTOMERS table:
Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. Following is
the 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:
A view can be updated under certain conditions:
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY clause.
The FROM clause may not contain multiple tables.
The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or HAVING.
Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
So if a view satisfies all the above mentioned rules then you can update a view. Following is an example
to update the age of Ramesh:
This would ultimately update the base table CUSTOMERS and same would reflect in the view itself.
Now, try to query base table, and SELECT statement would produce the following result:
This would ultimately delete a row from the base table CUSTOMERS and same would reflect in the
view itself. Now, try to query base table, and SELECT statement would produce the following result:
Dropping Views:
Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The
syntax is very simple as given below:
SQL Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or sequences
of work accomplished in a logical order, whether in a manual fashion by a user or automatically by
some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you are creating
a record or updating a record or deleting a record from the table, then you are performing transaction
on the table. It is important to control transactions to ensure data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them together as
a part of a transaction.
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:
Atomicity: ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure, and previous operations are rolled
back to their former state.
Consistency: ensures that the database properly changes states upon a successfully committed
transaction.
Isolation: enables transactions to operate independently of and transparent to each other.
Durability: ensures that the result or effect of a committed transaction persists in case of a
system failure.
Transaction Control:
There are following commands used to control transactions:
COMMIT: to save the changes.
ROLLBACK: to rollback the changes.
SAVEPOINT: creates points within groups of transactions in which to ROLLBACK
SET TRANSACTION: Places a name on a transaction.
Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only.
They cannot be used while creating tables or dropping them because these operations are automatically
committed in the database.
The COMMIT Command:
The COMMIT command is the transactional command used to save changes invoked by a transaction
to the database.