0% found this document useful (0 votes)
24 views27 pages

SQL Notes

The document discusses SQL and database concepts like SQL commands (DDL, DML, DCL, DQL), database normalization forms (1NF, 2NF, 3NF), SQL statements (SELECT, INSERT, UPDATE, DELETE), indexes, and operators (comparison, logical).

Uploaded by

Sunil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views27 pages

SQL Notes

The document discusses SQL and database concepts like SQL commands (DDL, DML, DCL, DQL), database normalization forms (1NF, 2NF, 3NF), SQL statements (SELECT, INSERT, UPDATE, DELETE), indexes, and operators (comparison, logical).

Uploaded by

Sunil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

SQL Notes.

sql

# sql notes :

-->sql is structural query langugue its a Relational databases.


-->sql commands :

DDL: data definition Language :


--> its means its create the databases and tables
--> we can drop the databases and tables alter the columns also.
-->its usually use only for create , databases ,tables and drop
-->that tables and database...

DML: data manupulation Language:


-->to manipualte the data inside the query .
--> we use Insert , drop ,Update.
--> its only for the rows of the tables and query.

DCL: data control language:


--> its give the authority to the tables or database in the
database.
-> by using the GRANT and REVOKE Command ..

DQL: data query language:


->to retrieve the data or a query from the table.
->SELECT command is used to fetch the query.

TCL: Transacition control language:

->its contains the SAVEPOINT,ROLLBACK...

constriants :

constraints are Rules or restriction that are applied to the columns in the
tables. it give what type data that column contains.
ex: NOT NULL ' the rows can-not be null'.
primary-key ' the rows will become unique identify .its doesnt contain
the duplicate values.';
foreigh-key:' its same has unique identify .its written inside the primary
key table..
when tables are created with the foreigh key these tables are can't be
deleted' untill parent table will
be remove. and its accept the duplicate values also.'
check:'its give the condition that are applied to the specific column.
ex: in a columns its name as a Age
so we declare its has a condition like age can't 'be below the
18 . '
unique:'the name itself shows the unique of the column its doesn't ' the
column will become unique ex: the email id we can't 'enter the same email id
again and again in a column.
when the columns declare as a unique key the column can't 'accept the
repeated or same values.'

Page 1 of 27
SQL Notes.sql

index :' to retrieve the data from tables to quickly.'


default :' provide a value if the column is none of the values are
provided the default values will be present inside the rows'.

---->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:

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, you can create index on single or multiple columns using the following syntax:
CREATE INDEX index_name
ON table_name ( column1, column2.....);
To create an INDEX on AGE column, to optimize the search on customers for a particular
age, following is the SQL

syntax:
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
DROP an INDEX Constraint:
To drop an INDEX constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;

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.

First Normal Form (1NF)

Page 2 of 27
SQL Notes.sql

 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.
First Rule of 1NF:
You must define the data items. This means looking at the data to be stored, organizing
the data into columns,
defining what type of data each column contains, and finally putting related columns into
their own table.
For example, you put all the columns relating to locations of meetings in the Location
table, those relating to
members in the MemberDetails table, and so on.

Third Rule of 1NF:


The final rule of the first normal form, create a primary key for each table which we
have already created.

Second Normal Form


Second normal form states that it should meet all the rules for 1NF and there must be no
partial dependences of
any of the columns on the primary key:
Consider a customer-order relation and you want to store customer ID, customer name,
order ID and order detail,
and date of purchase.

Third Normal Form


A table is in third normal form when the following conditions are met:
 It is in second normal form.
 All nonprimary fields are dependent on the primary key.

SQL SELECT Statement:


SELECT column1, column2....columnN
FROM table_name;
SQL DISTINCT Clause:
SELECT DISTINCT column1, column2....columnN
FROM table_name;
SQL WHERE Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;
SQL AND/OR Clause:
SELECT column1, column2....columnN
FROM table_name

Page 3 of 27
SQL Notes.sql

WHERE CONDITION-1 {AND|OR} CONDITION-2;

SQL IN Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);

SQL BETWEEN Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;

SQL LIKE Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };

SQL ORDER BY Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};

SQL GROUP BY Clause:


SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;

SQL COUNT Clause:


SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;

SQL HAVING Clause:


SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name

SQL DROP TABLE Statement:


DROP TABLE table_name;
SQL CREATE INDEX Statement:
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);

SQL DROP INDEX Statement:


ALTER TABLE table_name
DROP INDEX index_name;

Page 4 of 27
SQL Notes.sql

SQL DESC Statement:


DESC table_name;
SQL TRUNCATE TABLE Statement:
TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement:


ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};
SQL ALTER TABLE Statement (Rename):
ALTER TABLE table_name RENAME TO new_table_name;

SQL INSERT INTO Statement:


INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);
HAVING (arithematic function condition);

SQL Comparison Operators:


Assume variable a holds 10 and variable b holds 20, then:
Operator Description Example
= Checks if the values of two operands are equal or not, if yes then condition becomes
true. (a = b) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(a != b) is true.
<> Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.
(a <> b) is true.
>
Checks if the value of left operand is greater than the value of right operand, if yes
then
condition becomes true.
(a > b) is not true.
<
Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
(a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right
operand, if
yes then condition becomes true.
(a >= b) is not true.

<= Checks if the value of left operand is less than or equal to the value of right
operand, if
yes then condition becomes true.
(a <= b) is true.
!< Checks if the value of left operand is not less than the value of right operand, if
yes then
condition becomes true.
(a !< b) is false.

Page 5 of 27
SQL Notes.sql

!> Checks if the value of left operand is not greater than the value of right operand, if
yes
then condition becomes true.
(a !> b) is true.

SQL Logical Operators:


Here is a list of all the logical operators available in SQL.
Operator Description
ALL The ALL operator is used to compare a value to all values in another value set.
AND The AND operator allows the existence of multiple conditions in an SQL statements
WHERE clause.
ANY The ANY operator is used to compare a value to any applicable value in the list
according to the
condition.
BETWEEN The BETWEEN operator is used to search for values that are within a set of
values, given the
minimum value and the maximum value.
EXISTS The EXISTS operator is used to search for the presence of a row in a specified
table that meets
certain criteria.
IN The IN operator is used to compare a value to a list of literal values that have been
specified.
LIKE The LIKE operator is used to compare a value to similar values using wildcard
operators.
NOT The NOT operator reverses the meaning of the logical operator with which it is used.
Eg: NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
OR The OR operator is used to combine multiple conditions in an SQL statements WHERE
clause.
IS NULL The NULL operator is used to compare a value with a NULL value.
UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no
duplicates).

-----> WHERE
where clause can be used Select , Delete ,Update ..
ex:
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;

---> AND / OR

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.

Page 6 of 27
SQL Notes.sql

The AND Operator:


The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;

' The OR Operator:

The OR operator is used to combine multiple conditions in an SQL statement's WHERE


clause.

'SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;

----------------> LIKE

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. The symbols can be used in combinations.
----> 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:
Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200
WHERE SALARY LIKE
'%200%' Finds any values that have 200 in any position
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE
'2_%_%' Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end
with a 3
WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and
end with 3

----> TOP
TOP clause is used to fetch a TOP N number or X percent records from a table.
Note: All the databases do not support TOP clause. For example MySQL supports LIMIT
clause to fetch limited

Page 7 of 27
SQL Notes.sql

number of records and Oracle uses ROWNUM to fetch limited number of records.

SELECT TOP 3 * FROM CUSTOMERS;

we can use Limit operator..


If you are using MySQL server, then here is an equivalent example:

SQL> SELECT * FROM CUSTOMERS


LIMIT 3;

-----> order by clause

ORDER BY clause is used to sort the data in ascending or descending order, based on one
or
more columns. Some database sorts query results in ascending order by default

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.
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

----> group by

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

The GROUP BY clause must follow the conditions in the


WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

If you want to know the total amount of salary on each customer, then GROUP BY query
would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;

----->Distinct
DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the
duplicate
records and fetching only unique records.

Page 8 of 27
SQL Notes.sql

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 unique records instead of fetching duplicate records.

----------> order by

ORDER BY clause is used to sort the data in ascending or descending order, based on one
or
more columns. Some databases sort query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause which would be used to sort result in ascending or
descending order is as
follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

FOREIGN Key:
A foreign key is a key used to link two tables together. This is sometimes called a
referencing key.
Primary key field from one table and insert it into the other table where it becomes a
foreign key i.e., 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 can not have two records
having the same value of
that field(s).
Example:
Consider the structure of the two tables as follows:
CUSTOMERS table:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
ORDERS table:
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);

Page 9 of 27
SQL Notes.sql

If ORDERS table has already been created, and the foreign key has not yet been, use the
syntax for specifying a
foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
DROP a FOREIGN KEY Constraint:
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS
DROP FOREIGN KEY;

----> joins
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.

let us join these two tables in our SELECT statement as follows:


SQL> SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

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.

SQL Join Types:


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.

--->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.

Page 10 of 27
SQL Notes.sql

SELECT table1.column1, table2.column2...


FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;

CUSTOMERS table is as follows:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00
ORDERS as follows:
+-----+---------------------+-------------+--------+

| OID | DATE | ID | AMOUNT |


+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables using INNER JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

---> Left join

L 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.
--> where right side present or not its print left side..
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

---->RIGHT JOIN

Page 11 of 27
SQL Notes.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.

SQL> SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

-------FULL JOINS
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:
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;

SQL> SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
FULL JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

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 JOINS


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:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Here, WHERE clause could be any given expression based on your requiremen

Now, let us join this table using SELF JOIN as follows:


SQL> SELECT a.ID, b.NAME, a.SALARY

Page 12 of 27
SQL Notes.sql

FROM CUSTOMERS a, CUSTOMERS b


WHERE a.SALARY < b.SALARY;

---------------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 joincondition is absent from the statement.
Now, let us join these two tables using INNER JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS;

-----------UNION CLAUSE ----------------

union : it can't' accept duplicates values;


SQL UNION clause/operator is used to combine the results of two or more SELECT statements
without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number
of column
expressions, the same data type, and have them in the same order, but they do not have to
be the same length.

Syntax:
The basic syntax of UNION is as follows:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

Another table is ORDERS as follows:

+-----+---------------------+-------------+--------+

Page 13 of 27
SQL Notes.sql

|OID | DATE | CUSTOMER_ID | AMOUNT |


+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:
+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+------+----------+--------+------------------

-----> union all

The UNION ALL operator is used to combine the results of two SELECT statements including
duplicate rows.

The same rules that apply to UNION apply to the UNION ALL operator.
Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Page 14 of 27
SQL Notes.sql

There are two other clauses (i.e., operators), which are very similar to UNION clause:
 SQL INTERSECT Clause: is used to combine two SELECT statements, but returns rows only
from the first
SELECT statement that are identical to a row in the second SELECT statement.
 SQL EXCEPT Clause : combines two SELECT statements and returns rows from the first
SELECT statement
that are not returned by the second SELECT statement.
INTERSECT Clause
The SQL INTERSECT clause/operator is used to combine two SELECT statements, but returns
rows only from the
first SELECT statement that are identical to a row in the second SELECT statement. This
means INTERSECT
returns only common rows returned by the two SELECT statements.
Just as with the UNION operator, the same rules apply when using the INTERSECT operator.
MySQL does not
support INTERSECT operator
Syntax:
The basic syntax of INTERSECT is as follows:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here given condition could be any given expression based on your requirement

SQL> SELECT ID, NAME, AMOUNT, DATE


FROM CUSTOMERS
LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
INTERSECT
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

-- Except clause
SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows
from the first
SELECT statement that are not returned by the second SELECT statement. This means EXCEPT
returns only
rows, which are not available in second SELECT statement.
Just as with the UNION operator, the same rules apply when using the EXCEPT operator.
MySQL does not
support EXCEPT operator.

Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS

Page 15 of 27
SQL Notes.sql

LEFT JOIN ORDERS


ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
EXCEPT
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

---> Alias
---> we can use alias key is: as key .
---> we declare as or not we create a temporaryname of the class
rename a table or a column temporarily by giving another name known as alias.
The use of table aliases means to rename a table in a particular SQL statement. The
renaming is a temporary
change and the actual table name does not change in the database.
The column aliases are used to rename a table's columns for the purpose of a particular
SQL query.

Syntax:
The basic syntax of table alias is as follows:
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
The basic syntax of column alias is as follows:
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];

following is the usage of table alias:


SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT
FROM CUSTOMERS AS C, ORDERS AS O
WHERE C.ID = O.CUSTOMER_ID;

'

----->INDEXES

Indexes are special lookup tables that the database search engine can use to speed up
data retrieval. Simply
put, an index is a pointer to data in a table. An index in a database is very similar to
an index in the back of a book.

An index helps speed up SELECT queries and WHERE clauses, but it slows down data input,
with UPDATE and
INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the
index, to specify the
table and which column or columns to index, and to indicate whether the index is in
ascending or descending
order.

Page 16 of 27
SQL Notes.sql

The CREATE INDEX Command:


The basic syntax of CREATE INDEX is as follows:
CREATE INDEX index_name ON table_name;

Single-Column Indexes:
A single-column index is one that is created based on only one table column. The basic
syntax is as follows:

CREATE INDEX index_name


ON table_name (column_name);

Unique Indexes:
Unique indexes are used not only for performance, but also for data integrity. A unique
index does not allow any
duplicate values to be inserted into the table. The basic syntax is as follows:

CREATE INDEX index_name


on table_name (column_name);

Composite Indexes:
A composite index is an index on two or more columns of a table. The basic syntax is as
follows:
CREATE INDEX index_name
on table_name (column1, column2);

Implicit Indexes:
Implicit indexes are indexes that are automatically created by the database server when
an object is created.
Indexes are automatically created for primary key constraints and unique constraints.

The DROP INDEX Command:

An index can be dropped using SQL DROP command. Care should be taken when dropping an
index because
performance may be slowed or improved.
The basic syntax is as follows:
DROP INDEX index_name;

-----------------------------------ALTER TABLE COMMAND -------------

ALTER TABLE command is used to add, delete or modify columns in an existing table.
You would also use ALTER TABLE command to add and drop various constraints on an existing
table.
Syntax:

The basic syntax of ALTER TABLE to add a new column in an existing table is as follows:

ALTER TABLE table_name ADD column_name datatype;


The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows:

Page 17 of 27
SQL Notes.sql

ALTER TABLE table_name DROP COLUMN column_name;


The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as
follows:

ALTER TABLE table_name MODIFY COLUMN column_name datatype;


The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as
follows:

ALTER TABLE table_name MODIFY column_name datatype NOT NULL;


The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows:

ALTER TABLE table_name


ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows:

ALTER TABLE table_name


ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as follows:

ALTER TABLE table_name


ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);

ALTER TABLE table_name


DROP CONSTRAINT MyUniqueConstraint;
If youre using MySQL, the code is as follows:

ALTER TABLE table_name


DROP INDEX MyUniqueConstraint;

The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as
follows:

ALTER TABLE table_name


DROP CONSTRAINT MyPrimaryKey;

If youre using MySQL, the code is as follows:

ALTER TABLE table_name


DROP PRIMARY KEY;

ADD a new column in an existing table:

ALTER TABLE CUSTOMERS ADD SEX char(1);

ALTER TABLE CUSTOMERS DROP SEX;

----TRUNCATE TABLE

Page 18 of 27
SQL Notes.sql

TRUNCATE TABLE command is used to delete complete data from an existing table.
You can also use DROP TABLE command to delete complete table but it would remove complete
table structure
form the database and you would need to re-create this table once again if you wish you
store some data.

Syntax:
The basic syntax of TRUNCATE TABLE is as follows:
TRUNCATE TABLE table_name;

----------VIEW
Aview is nothing more than a 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 kind of virtual tables, allow users to do the following:
 Structure data in a way that users or classes of users find natural or intuitive.
 Restrict access to the data such that a user can see and (sometimes) modify exactly
what they need and no
more.
 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:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];

SQL > CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age
FROM CUSTOMERS;

Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. Following
is the example:

SQL > SELECT * FROM CUSTOMERS_VIEW;

The WITH CHECK OPTION:


--->deny the entry of any NULL values.
The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH CHECK
OPTION is

Page 19 of 27
SQL Notes.sql

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.
The following is an example of creating same view CUSTOMERS_VIEW with the WITH CHECK
OPTION:
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;

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.

UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name='Ramesh';

Inserting Rows into a View:


Rows of data can be inserted into a view. The same rules that apply to the UPDATE command
also apply to the
INSERT command.
Here, we can not insert rows in CUSTOMERS_VIEW because we have not included all the NOT
NULL columns in
this view, otherwise you can insert rows in a view in similar way as you insert them in a
table.

Deleting Rows into a View:


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and
INSERT commands
apply to the DELETE command.
Following is an example to delete a record having AGE= 22.
SQL > DELETE FROM CUSTOMERS_VIEW
WHERE age = 22;

Dropping Views:
Obviously, where you have a view, you need a way to drop the view if it is no longer

Page 20 of 27
SQL Notes.sql

needed. The syntax is very


simple as given below:
DROP VIEW view_name;
Following is an example to drop CUSTOMERS_VIEW from CUSTOMERS table:
DROP VIEW CUSTOMERS_VIEW;

-------HAVING CLAUSE -------

HAVING clause enables you to specify conditions that filter which group results appear in
the final
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 following is the position of the HAVING clause in a query:
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

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:
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2.

Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example, which would display record for which similar age count would be
more than or equal to 2:

Page 21 of 27
SQL Notes.sql

SQL > SELECT *


FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;

This would produce the following result:


+----+--------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
+----+--------+-----+---------+---------+

------> TRANSCATIONS----
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.

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.

Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only.
They can not 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.

Page 22 of 27
SQL Notes.sql

The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.
The syntax for COMMIT command is as follows:
COMMIT;

Consider the CUSTOMERS table having the following records:


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

Following is the example, which would delete records from the table having age = 25 and
then COMMIT the
changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> COMMIT;

As a result, two rows from the table would be deleted and SELECT statement would produce
the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

The ROLLBACK Command:


The ROLLBACK command is the transactional command used to undo transactions that have not
already been
saved to the database.
The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK
command was issued.
The syntax for ROLLBACK command is as follows:

ROLLBACK;

-- rollback is used to get back the data .. which are commit.

Following is the example, which would delete records from the table having age = 25 and

Page 23 of 27
SQL Notes.sql

then ROLLBACK the


changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;

The SAVEPOINT Command:


A SAVEPOINT is a point in a transaction when you can roll the transaction back to a
certain point without rolling
back the entire transaction.
The syntax for SAVEPOINT command is as follows:
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among transactional statements.
The ROLLBACK
command is used to undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as follows:
ROLLBACK TO SAVEPOINT_NAME;

example where you plan to delete the three different records from the CUSTOMERS table.
You
want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT
at any time to
return the appropriate data to its original state:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, here is the series of operations:
SQL> SAVEPOINT SP1;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.

Page 24 of 27
SQL Notes.sql

Now that the three deletions have taken place, say you have changed your mind and decided
to ROLLBACK to the
SAVEPOINT that you identified as SP2. Because SP2 was created after the first deletion,
the last two deletions
are undone:
SQL> ROLLBACK TO SP2;
Rollback complete.

The RELEASE SAVEPOINT Command:


The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created.
The syntax for RELEASE SAVEPOINT is as follows:
RELEASE SAVEPOINT SAVEPOINT_NAME;

Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo
transactions
performed since the 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 SET TRANSACTION is as follows:
SET TRANSACTION [ READ WRITE | READ ONLY ];

Page 25 of 27
SQL Notes.sql

Page 26 of 27
SQL Notes.sql

Page 27 of 27

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy