SQL Notes
SQL Notes
sql
# sql notes :
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:
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:
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
Page 2 of 27
SQL Notes.sql
Page 3 of 27
SQL Notes.sql
SQL IN Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
Page 4 of 27
SQL Notes.sql
<= 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.
-----> 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
----------------> 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.
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
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.
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.
--->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
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.
-------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;
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:
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
Page 12 of 27
SQL Notes.sql
---------------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;
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 |
+-----+---------------------+-------------+--------+
Page 13 of 27
SQL Notes.sql
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
-- 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
---> 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];
'
----->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
Single-Column Indexes:
A single-column index is one that is created based on only one table column. The basic
syntax is as follows:
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:
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.
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 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:
Page 17 of 27
SQL Notes.sql
The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as
follows:
----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];
Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. Following
is the example:
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:
UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name='Ramesh';
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
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
------> 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.
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;
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 |
ROLLBACK;
Following is the example, which would delete records from the table having age = 25 and
Page 23 of 27
SQL Notes.sql
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.
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