Monday, June 13, 2016

SQL BASICS

SQL stands for Structured Query Language. and it is generally referred to as SEQUEL. SQL is simple language to learn. SQL is a Nonprocedural language, as compared to the procedural or third generation languages (3GLs) such as COBOL and C. SQL was developed by IBM in the 1970s.
The American National Standards Institute (ANSI) published its first SQL standard in 1986 and a second widely adopted standard in 1989. ANSI released updates in 1992, known as SQL92 and SQL2, and again in 1999, termed both SQL99 and SQL3. Each time, ANSI added new features and incorporated new commands and capabilities into the language.
SQL is a simple, yet powerful, language used to create, access, and manipulate data and structure in the database.

SQL Statements categories: DDL - Data Definition Language.
DDL is used to define, alter, or drop database objects and their privileges. DDL statements will implicitly perform a commit.
DDL Statements:
Create
It is used to create objects(tables, views) in the database.
Alter
It is used to alter the structure of the database objects.
Drop
delete database objects (It will invalidate the dependent objects ,it also drops indexes, triggers and referential integrity constraints ).
Truncate
remove all records from a table, including all spaces allocated for the records are removed (It is fast as compared to Delete and does not generate undo information as Delete does. It performs an implicit commit as it is a DDL. It resets the high water mark.)
Grant
assigning privileges


DML - Data Manipulation Language.
DML is used to access, create, modify or delete data in the structures of the database.
DML Statements:
Select
Select data from the database
Insert
It is used to insert data into a table
Update
It is used to update existing data within a table
Delete
It removes rows from the table.


DCL - Data Control Language
Following are the examples of Data control Statements.
DCL Statements:

Commit
It will end the current transaction making the changes permanent and visible to all users..
Savepoint
It will identify a point(named SAVEPOINT) in a transaction to which you can later roll back
Rollback
It will undo all the changes made by the current transaction.
Set- Transaction
It is used to define the properties of a transaction.


On this page, you will find SQL syntax for some of the most important SQL commands. These belowSQL Syntaxes will be suitable for quick reference.

SELECT [hint][DISTINCT] select_list
FROM table_list

[WHERE conditions]
[GROUP BY group_by_list]
[HAVING search_conditions]

[ORDER BY order_list [ASC DESC] ]
[FOR UPDATE for_update_options]

SQL Select Statement

SELECT "column name" FROM "table name"

Example:
Select salary from emp;

SQL Where

SELECT "column name"
FROM "table name"
WHERE "condition"

Example:
Select salary from emp
Where salary > 2000

SQL Distinct

SELECT DISTINCT "column name"
FROM "table name"

Example:
Select DISTINCT name from emp;

SQL And/Or

SELECT "column name"
FROM "table name"
WHERE "condition"
{[ANDOR] "condition"}+

Example:
SELECT salary
FROM emp
WHERE Salary > 1000
OR (Salary <> 275)

SQL Between

SELECT "column name"
FROM "table name"
WHERE "column name" BETWEEN 'value1' AND 'value2'

Example:
SELECT *
FROM emp
WHERE Date BETWEEN 'Jan-01-1999' AND 'Jan-15-1999'

SQL In

SELECT "column name"
FROM "table name"
WHERE "column name" IN ('value1', ‘value2’ ...)

Example:
SELECT *
FROM emp
WHERE last_name IN ('sharma', 'dhall')

SQL Like

SELECT "column name"
FROM "table name"
WHERE "column name" LIKE {PATTERN}

Example:
SELECT *
FROM emp
WHERE last_name LIKE '%EN%'

SQL Order By

SELECT "column name"
FROM "table name"
[WHERE "condition"]
ORDER BY "column name" [ASC, DESC]

Example:
SELECT name, Salary
FROM emp
ORDER BY name DESC

SQL Count

SELECT COUNT ("column name")
FROM "table name"

Example:
 
SELECT COUNT (salary)
FROM emp

SELECT * FROM Table;

In the above query, SELECT and FROM are SQL keywords, * is a wildcard which means “all columns”

According to wikipedia Commonly available SQL keywords related to SELECT include:

1.            FROM is used to indicate from which tables the data is to be taken, as well as how the tables JOIN to each other.
2.            WHERE is used to identify which rows to be retrieved, or applied to GROUP BY. WHERE is evaluated before the GROUP BY.
3.            GROUP BY is used to combine rows with related values into elements of a smaller set of rows.
4.            HAVING is used to identify which of the "combined rows" (combined rows are produced when the query has a GROUP BY keyword or when the SELECT part contains aggregates), are to be retrieved. HAVING acts much like a WHERE, but it operates on the results of the GROUP BY and hence can use aggregate functions.
5.            ORDER BY is used to identify which columns are used to sort the resulting data.

Returning a Single Column from a table

The syntax is as follows:
SELECT Column FROM Table;

Oracle uses the ANSI standard concatenation operator, . Because this operator is reserved for string concatenation, the operands don't need to be cast to a string type—they'll be converted automatically:

SELECT FirstName ' ' LastName AS Name FROM EMP_Database;

Sorting with the ORDER BY Clause

The
 ORDER BY clause is always applied after all other clauses are applied, such as the WHERE andGROUP BY clauses. Without an ORDER BY clause in an SQL statement, rows will often be retrieved in the physical order in which they were added to the table. The default behavior is to sort rows in ascending order.

SELECT ColumnA, ColumnB FROM Table
ORDER BY ColumnA ASC;

Although this is the default behavior so you don't need to explicitly specify the ASC keyword, it's a better idea to include it to ensure that your queries are as easy to read as possible.

Also, you may want to sort your rows in descending order, in which case you use the
 DESC keyword:

SELECT ColumnA, ColumnB FROM Table
ORDER BY ColumnA DESC;

Filtering Data

DISTINCT
 always retrieves the first value from a repeating group. If there are multiple repeating groupsDISTINCT will retrieve the first row from each group.

Hence,
 DISTINCT will always require a sort. DISTINCT can operate on a single or multiple columns.

SELECT DISTINCT ColumnA FROM Table;

In order to filter out duplicate rows, you use the
 DISTINCT keyword.

If you want to retrieve multiple columns, you can guarantee that every row you obtain contains unique data for the specified set of columns.
For example, the following query will return only unique combinations of customer names and debit card details:

SELECT DISTINCT CustomerName, DebitCard FROM Customers;

This doesn't mean that you won't have duplicates in either column, only that each combination is unique. You could, for example, have several customers with the same name but with different debit card numbers.

Using WHERE Clause

We can use the
 WHERE clause to restrict the rows returned by a query.

SELECT ColumnA, ColumnB, ColumnC FROM Table
WHERE Condition;

Condition is very flexible, allowing you to test for equalities and inequalities in column data, ranges of values to look for etc. You achieve all this using a simple syntax that includes various operators and keywords that, when combined, allow you to search for pretty much anything.

We can use following comparison operators with the
 WHERE clause:


Operator
Meaning
=
Equal
<>, !=, ^=
Not Equal
> 
Greater Than
< 
Less Than
>=
Greater Than Or Equal
<=
Less Than Or Equal



And many more for example BETWEEN ...AND..., LIKE, IS NULL etc.

Some examples of where

1)
SELECT name FROM bedroom
WHERE bedcolor = 'BLACK'
OR ceilingcolor = 'GREEN'
OR wallcolor = 'YELLOW'

2)
SELECT z
FROM t
WHERE x = 6 AND y > 7 ;

3)
Find the average price of Bud.

Sells (bar, beer, price)

SELECT AVG (price)
FROM Sells
WHERE beer = 'Bud';


SQL Joins
You will get vast amount of data/ information on this page regarding Oracle SQL JOINS like
1.            SQL Inner Join
2.            SQL Outer Join
3.            SQL Self Join
4.            SQL Cross Join
5.            SQL Equijoin
6.            Join using MULTIPLE TABLES

SQL Inner Join

Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins.

Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables. [
Source]
SELECT Consumers.LastName, Consumers.FirstName, Orders.OrderNo
FROM Consumers
INNER JOIN Orders
ON Consumers.P_Id=Orders.P_Id
ORDER BY Consumers.LastName


SQL Group By Examples
Example 1 of SQL Group By

Let us say we have a table name Orders.

Orders (O_Id, OrderDate, OrderPrice, Customer)

we want to find the total sum (total order) of each customer.

SELECT Customer,SUM(OrderPrice)
FROM Orders
GROUP BY Customer


SQL Views
SQL View

An
 SQL View is a specific representation of data from one or more tables. The tables referred in the views are known as Base tables. Creating a view does not take any storage space as only the query is stored in the data dictionary and the actual data is not stored anywhere.

The maximum number of columns that can be defined in a
 SQL View are 1000 as in tables.

Benefits / Advantages of
 SQL Views

The reasons for using views (benefits / advantages of views) in applications can be many like;
·                     Reducing complexity.
·                     Improving security.
·                     Renaming the table columns.

Creating
 SQL View

Use
 Create View statement to create a view:

SQL> create view emp_info as
2 select first_name ' ' last_name Name, employee_id
3 from employees where department_id = 20;
View created.



Referential Integrity
In order for the database to work properly, it is essential to guarantee that a foreign key always refers to a record which exists in the other table. This is known as referential integrity.

Example: If "New Delhi Branch" is a branch name appearing in one of the tuples in the
 account relation, then there exists a tuple in the branch relation for branch "New Delhi Branch".

Referential integrity
 is usually enforced by the combination of a primary key and a foreign key. For referential integrity to hold, any field in a table that is declared a foreign key can contain only values from a parent table's primary key field.

Referential integrity
 is a feature provided by relational database management systems (RDBMS’s) that prevents users or applications from entering inconsistent data.

Referential integrity
 is a database constraint that ensures that references between data are indeed valid and intact.

The main objective of Referential integrity is to maintain data of the two base relations in consistent state during tuple insertion, deletion and modification.

Example of
 Referential Integrity

The SQL statement defining the parent table, DEPARTMENT, is:
CREATE TABLE DEPARTMENT
      (DEPTNO    CHAR(3)     NOT NULL,
       DEPTNAME  VARCHAR(29) NOT NULL,
       MGRNO     CHAR(6),
       ADMRDEPT  CHAR(3)     NOT NULL,
       LOCATION  CHAR(16),
          PRIMARY KEY (DEPTNO))
   IN RESOURCE

The SQL statement defining the dependent table, EMPLOYEE, is:
CREATE TABLE EMPLOYEE
      (EMPNO     CHAR(6)     NOT NULL PRIMARY KEY,
       FIRSTNME  VARCHAR(12) NOT NULL,
       LASTNAME  VARCHAR(15) NOT NULL,
       WORKDEPT  CHAR(3),
       PHONENO   CHAR(4),
       PHOTO     BLOB(10m)   NOT NULL,
          FOREIGN KEY DEPT (WORKDEPT)
          REFERENCES DEPARTMENT ON DELETE NO ACTION)
   IN RESOURCE

By specifying the DEPTNO column as the primary key of the DEPARTMENT table and WORKDEPT as the foreign key of the EMPLOYEE table, you are defining a referential constraint on the WORKDEPT values. This constraint enforces referential integrity between the values of the two tables. In this case, any employees that are added to the EMPLOYEE table must have a department number that can be found in the DEPARTMENT table.
 



References:
 
Referential Integrity Is Important For Databases
Infocenter


UNIQUE Constraint
SQL UNIQUE Constraint

SQL UNIQUE Constraint
 indicates that a column or set of columns should contain unique values, meaning that no two values of "Ename" column (if Ename has a UNIQUE constraint) should be same.

Example 1 of
 SQL UNIQUE Constraint
CREATE TABLE Sells (
  bar   CHAR(20),
  beer VARCHAR(20),
  price REAL,
  UNIQUE(bar,beer)
 );

PRIMARY KEY Constraint
SQL PRIMARY KEY Constraint

SQL PRIMARY KEY Constraint
 - same as UNIQUE Constraint except that Primary Key constraints does not allow null values (whether or not the column definition specifies NOT NULL) and only one primary key constraint can be defined for each table.

Example of
 SQL PRIMARY KEY Constraint
CREATE TABLE Sells (
  bar   CHAR(20),
  beer  VARCHAR(20) DEFAULT 'Kingfisher',
  price REAL  NOT NULL,
  PRIMARY KEY (bar,beer)
 );


Difference Between Unique & Primary Key
Difference Between Unique & Primary Key

You can have more than one
 UNIQUE constraint per table, but only one Primary key.

Some DBMS might automatically create an index (data structure to speed search) in response toPRIMARY KEY, but not
 UNIQUE.

SQL does not allow nulls in
 Primary key, but allows them in Unique columns (which may have two or more nulls, but not repeated non-null values).


SQL Subqueries


Subquery is a query inside a main query.

SQL subquery
 can be embedded:
·                     As a column expression in the main SQL statement
·                     As a filter inside the WHERE (or HAVING) clause in the main SQL statement
·                     As a datasource inside the FROM clause in the main SQL statement

While working with SQL Subqueries you must:
·                     Enclose the subquery in parentheses
·                     Do not use a semicolon at the end of the subquery statement

Example 1 of subquery

Find the names of all of the managers in the Employees table.

Employees (emp_id, Emp_name, ManagerID)

SELECT Emp_name AS Employee
FROM Employees
WHERE emp_id IN (SELECT DISTINCT ManagerID FROM Employees)

Example 2 of SQL Subquery

Store_Info (store_name, sales, date)
Location (region_names, store_name)

Find the sales of all stores in the East region.
SELECT SUM(Sales) FROM Store_Info
WHERE Store_name IN
(SELECT store_name FROM Location
WHERE region_name = 'East')


You can nest any number of such queries; Oracle does not have a limit.
 

There is also another term used NESTED SUBQUERIES. when you use subqueries in the WHERE clause of the SELECT statement it is called nested subquery. There are only 255 levels of subqueries.

Difference between Views & Materialized views
Difference between Views & Materialized views

Materialized views
 are disk based and update periodically base upon the query definition.

Views
 are virtual only and run the query definition each time they are accessed.

Views
 evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else. The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.

Materialized views
 are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query resultset has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed. In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.

Materialized views
 can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.

Materialized views
 are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application. [Source]


Difference between SQL TRUNCATE & SQL DROP
SQL - Difference between TRUNCATE & DROP

DROP TABLE
 - deletes the table from the database. TRUNCATE TABLE - empties it, but leaves the structure for future data.


Difference between SQL HAVING & SQL WHERE
SQL - Difference between HAVING CLAUSE & WHERE CLAUSE

1.
 HAVING specifies a search condition for a group or an aggregate function used in SELECT statement. The WHERE clause specifies the criteria which individual records must meet to be selected by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.

2. The
 WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.

3. The
 WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions. [Via]


Alter Table
Alter Table changes (alters) a table definition by altering, adding, or dropping columns and constraints, or by disabling or enabling constraints and triggers.

Example 1 of
 Alter Table

Adding a new column to an Emp table:

ALTER TABLE Emp ADD phone CHAR(16)
DEFAULT 'unlisted';

Example 2 of
 Alter Table

Dropping a column from an Emp table:

ALTER TABLE Emp DROP phone;

Example 3 of
 Alter Table

Changing the datatype of a column in a table:

ALTER TABLE Emp
ALTER COLUMN phone varchar;

Example 4 of
 Alter Table

Modifying a column:
[if earlier the column "name" is like varchar(20) and we want to change it to varchar(100) then do as follows:]

ALTER TABLE Emp ALTER COLUMN name varchar(100);

Example 5 of
 Alter Table

Adding a constraint

ALTER TABLE Emp ADD CONSTRAINT con_one UNIQUE (name);

con_one is the name of the constraint.

Example 6 of
 Alter Table

Constraints can also be dropped

ALTER TABLE Emp DROP CONSTRAINT con_one;

Renaming a column or table is not possible with Alter statement in SQL Server. For that you have to use sp_rename.


SQL Merge
SQL MERGE allows you to perform multiple INSERT, UPDATE, and DELETE operations in a single statement. It is new in SQL server 2008. Based on selection criteria specified in the MERGE statement, you can conditionally apply INSERT, UPDATE, and DELETE statements to the table.

For example, you may want to UPDATE a row if it already existed and INSERT the row if it is not already in the table. You might also want to synchronize the contents of two tables.

The general syntax for
 MERGE is: