Friday, 26 September 2014

SQL Unions Clause

The  SQL UNION clause/operator  is  used  to  combine  the  results  of  two  or  more  SELECT  statements without returning any duplicate rows.
To use 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]

Here given condition could be any given expression based on your requirement.
Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables in our SELECT statement as follows :-

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

The UNION ALL Clause :-
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.
Syntax :-
The basic syntax of UNION ALL is as follows :-

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

Here given condition could be any given expression based on your requirement. 
Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables in our SELECT statement as follows :-

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;

This would produce the following result :-
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.
Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables in our SELECT statement as follows :-

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;

This would produce the following result :-

EXCEPT Clause

The  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.
Syntax :- 
The basic syntax of EXCEPT is as follows :-

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

Here given condition could be any given expression based on your requirement.
Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables in our SELECT statement as follows :-

SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
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;

This would produce the following result :-











Thursday, 25 September 2014

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 :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables in our SELECT statement as follows :-

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

This would produce the following result :-
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.
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
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 :-

SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;

Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables using INNER JOIN as follows :-

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

This would produce the following result :-

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

SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_filed = table2.common_field;

Here given condition could be any given expression based on your requirement.
Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables using LEFT JOIN as follows :-

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

This would produce the following result :-

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

SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_filed = table2.common_field;

Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables using RIGHT JOIN as follows :-

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

This would produce the following result :-

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

SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;

Here given condition could be any given expression based on your requirement. 
Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables using FULL JOIN as follows :-

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

This would produce the following result :-
 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 :-

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

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

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 requirement.
Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
Now, let us join this table using SELF JOIN as follows :-

SELECT a.ID, b.NAME, a.SALARY
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;

This would produce the following result :-

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.
Syntax :-
The basic syntax of INNER JOIN is as follows :-

SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]

Example :-
Consider the following two tables, (a) CUSTOMERS table is as follows :-
(b) Another table is ORDERS as follows :-
Now, let us join these two tables using INNER JOIN as follows :-

SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS; 

This would produce the following result :-




















Wednesday, 24 September 2014

SQL Constraints

Constraints  are the rules enforced on data columns on table. These are used to limit the type of data that
can go into a table. This ensures the accuracy and reliability of the data in the database.
Contraints could be column level or table level. Column level constraints are applied only to one column where as table level constraints are applied to the whole table.
Following  are  commonly  used  constraints  available  in  SQL.  These  constraints  have  already  been  discussed in SQL - RDBMS Concepts chapter but its worth to revise them at this point.

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 row/record in any other 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

NOT NULL Constraint :-
By default, a column can hold NULL values. If you do not want a column to have a NULL value,  then you need to define such constraint on this column specifying that NULL is now not allowed for that column.
A NULL is not the same as no data, rather, it represents unknown data.
Example :-
For example, the following SQL creates a new table called CUSTOMERS and adds five columns, three of which, ID and NAME and AGE, specify not to accept NULLs :-

CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
CHAPTER
25 
TUTORIALS POINT
Simply Easy Learning
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), 
PRIMARY KEY (ID)
);

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

ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL;

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.

CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00, 
PRIMARY KEY (ID)
);

If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY column, you would write a statement similar to the following :-

ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;

Drop Default Constraint :-
To drop a DEFAULT constraint, use the following SQL :-

ALTER TABLE CUSTOMERS
ALTER COLUMN SALARY DROP DEFAULT; 

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 can not have two records with same age :-

CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), 
PRIMARY KEY (ID)
);

If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE column, you would write a statement similar to the following :-

ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;

You can also use the following syntax, which supports naming the constraint in multiple columns as well :-

ALTER TABLE CUSTOMERS
ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);

DROP a UNIQUE Constraint :-

To drop a UNIQUE constraint, use the following SQL :-

ALTER TABLE CUSTOMERS
DROP CONSTRAINT myUniqueConstraint;

If you are using MySQL, then you can use the following syntax :-

ALTER TABLE CUSTOMERS
DROP INDEX myUniqueConstraint; 

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 can not have two records having the same value of that field(s).
Note :- You would use these concepts while creating database tables.

Create Primary Key :-
Here is the syntax to define ID attribute as a primary key in a 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)
);

To  create  a  PRIMARY  KEY  constraint  on  the  "ID"  column  when  CUSTOMERS  table  already  exists,  use  the following SQL syntax :-

ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

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

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, NAME)
); 

To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table already exists, use the following SQL syntax :-

ALTER TABLE CUSTOMERS 
ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);

Delete Primary Key :-
You can clear the primary key constraints from the table, Use Syntax :-

ALTER TABLE CUSTOMERS DROP PRIMARY KEY ;

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), 
TUTORIALS POINT
Simply Easy Learning
AMOUNT double,
PRIMARY KEY (ID)
);

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;

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 can not have any CUSTOMER below 18 years :-

CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT    NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2), 
PRIMARY KEY (ID)
);

If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you would write a statement similar to the following :-

ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL CHECK (AGE >= 18 );

You can also use following syntax, which supports naming the constraint and multiple columns as well:
ALTER TABLE CUSTOMERS

ADD CONSTRAINT myCheckConstraint CHECK(AGE >= 18);

DROP a CHECK Constraint :-
To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL :-

ALTER TABLE CUSTOMERS
DROP CONSTRAINT myCheckConstraint;

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

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;

Constraints can be specified when a table is created with the CREATE  TABLE statement or you can use ALTER TABLE statment to create constraints even after the table is created.

Dropping Constraints :-
Any  constraint  that  you  have  defined  can  be  dropped  using  the  ALTER  TABLE  command  with  the  DROP CONSTRAINT option.
For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following command :-

ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;

Some implementations may provide shortcuts for dropping certain constraints. For example, to drop the primary key constraint for a table in Oracle, you can use the following command :-

ALTER TABLE EMPLOYEES DROP PRIMARY KEY;

Some  implementations  allow  you  to  disable  constraints.  Instead  of  permanently  dropping  a  constraint  from  the database, you may want to temporarily disable the constraint, and then enable it later.
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. 

SQL SORTING Results

The  SQL 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];

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

SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

This would produce the following result :-
Following is an example, which would sort the result in descending order by NAME :-

SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

This would produce the following result :-
To fetch the rows with own preferred order, the SELECT query would be as follows :-

SELECT * FROM CUSTOMERS

SELECT * FROM CUSTOMERS
ORDER BY (CASE ADDRESS
WHEN 'DELHI'    THEN 1
WHEN 'BHOPAL'    THEN 2
WHEN 'KOTA'   THEN 3
WHEN 'AHMADABAD' THEN 4
WHEN 'MP'   THEN 5
ELSE 100 END) ASC, ADDRESS DESC;

This would produce the following result :-
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 Distinct Keyword

The  SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate
records and fetching only unique records.
There  may  be  a  situation  when  you  have  multiple  duplicate  records  in  a  table. While  fetching  such  records,  it makes more sense to fetch only unique records instead of fetching duplicate records.
Syntax :-
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows :-

SELECT DISTINCT column1, column2,.....columnN 
FROM table_name
WHERE [condition]

Example :-
Consider the CUSTOMERS table having the following records :-
First, let us see how the following SELECT query returns duplicate salary records :-

SELECT SALARY FROM CUSTOMERS
ORDER BY SALARY;

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

SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY;

This would produce the following result where we do not have any duplicate entry :-



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.

SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

Example :-
Consider the CUSTOMERS table having the following records.
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.

SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

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

SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;

This would produce the following result :-
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 :-

SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;

This would produce the following result :-





SQL ORDER BY Clause

The  SQL 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.
Syntax :-
The basic syntax of ORDER BY clause is as follows :-

SELECT column-list 
FROM table_name 
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

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

SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

This would produce the following result :-
Following is an example, which would sort the result in descending order by NAME :-

SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

This would produce the following result :-