24

Click here to load reader

Difference SQL Latest

Embed Size (px)

DESCRIPTION

SQL Difference

Citation preview

Page 1: Difference SQL Latest

what is the difference between primary key and foreign key?A primary key is a column which uniquely identifies the records in a table. In a broad sense, a primary key is the

mixture of a unique key and an index: A column with a primary key is indexed to deliver a faster query, and doesn't allow duplicate values to ensure specific data.

A foreign key is a column (the child column) in a table which has a corresponding relationship and a dependency on another column (the parent column) that is usually in a different table. Parent columns can have multiple child columns, but a child column can only have one parent column.

Primary key does't allow null value while foreign key allow null value

Foreign Key Primary Key

1. A foreign key can refer to its own relation.

2. One or more Foreign key can be treated in Parent table.

3. Foreign key constraints can be defined at the column or table constraint level.

1. The Primary key clause speci--files one or more attributes that make up primary key of a relation.

2. One Primary key can be treated for each table.

3. Primary key constraint is a column or set of columns that uniquely identifies each row in a table.

Difference between primary and unique key constraints   

Unique Key ConstraintsThe column values should retain uniqueness.It allows null values in the column.It will create non-clustered index by default.Any number of unique constraints can be added to a table.

Primary Key ConstraintsPrimary key will create column data uniqueness in the table.It will not allow Null values.By default Primary key will create clustered index.Only one Primary key can be created for a table.

Primary Key - This is an index that cannot be NULL, Primary Keys are used in building relationships between tables in a database. (an index is automatically created on the primary key). The difference between primary and ordinary keys is that there can be multiple keys, but only one primary key.

Unique Key - Unique and Index are same, the difference is, in Unique, duplicate are not allowed in any circumstances and that is enforced by database server. Primary key(s) qualify to be Unique on basis of their uniqueness.In case, your table has 2 primary keys means that the 2 fields together form one unique key. Each field by itself may have repeating values, but both primary keys combined together must be unique.

A primary key is an unique identifier for a table object. Typically, primary keys are numeric but can be strings (such as guids or other unique character sets). The important thing is that primary keys are unique - each row entry includes a distinctly different primary key entry that cannot (or should not) reoccur as a primary key for another entry. An example would be the unique customer id you would find on any invoice that clearly points to the details of 1 and only 1 customer.

A secondary key is most often found when the use of a single field will not represent unique sequencing. For instance, if one field, say last name is not enough to create the unique nature needed for a primary key, a second field will be included to make the combination unique.

A foreign key is what allows multiple tables to efficiently interact. Once a primary key is created on one table, a second

Page 2: Difference SQL Latest

table can access the information in the first table by including a column to hold just the primary key value as a foreign key. When pulling information processes can take information from an orders table and use the foreign key on the order to reference all of the information for the customer that foreign key relates.

Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be NULL.

Unique Key: Unique Keys are used to uniquely identify each row in an Oracle table. There can be one and only one row for each unique key value.

Surrogate Key: A system generated key with no business value. Usually implemented with database generated sequences. 

The Difference Between UNION and UNION ALL

UNION performs a DISTINCT on the result set, eliminating any duplicate rows.

UNION ALL does not remove duplicates, and is therefore faster than UNION.

The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.

union is used to select distinct values from two tables where as union all is used to select all values including duplicates from the tables

UNIONThe UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.

UNION ALLThe UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.

The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.

A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.

Example :-Table X contain values(a,b,c) and Table Y contain values(c,d,e)In Case Of Union we will get Result-a,b,c,d,eand other hand (Union All ) we will get-a,b,c,c,d,e.

The SQL UNION operator combines two or more SELECT statements.

The SQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.

Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

SQL UNION SyntaxSELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2

Page 3: Difference SQL Latest

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.

SQL UNION ALL SyntaxSELECT column_name(s) FROM table_name1UNION ALLSELECT column_name(s) FROM table_name2

PS: The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.

SQL UNION Example

Look at the following tables:

"Employees_Norway":

E_ID E_Name

01 Hansen, Ola

02 Svendson, Tove

03 Svendson, Stephen

04 Pettersen, Kari

"Employees_USA":

E_ID E_Name

01 Turner, Sally

02 Kent, Clark

03 Svendson, Stephen

04 Scott, Stephen

Now we want to list all the different employees in Norway and USA.

We use the following SELECT statement:

SELECT E_Name FROM Employees_NorwayUNIONSELECT E_Name FROM Employees_USA

The result-set will look like this:

E_Name

Hansen, Ola

Svendson, Tove

Svendson, Stephen

Pettersen, Kari

Turner, Sally

Kent, Clark

Scott, Stephen

Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them will be listed. The UNION command selects only distinct values.

Page 4: Difference SQL Latest

SQL UNION ALL Example

Now we want to list all employees in Norway and USA:

SELECT E_Name FROM Employees_NorwayUNION ALLSELECT E_Name FROM Employees_USA

Result

E_Name

Hansen, Ola

Svendson, Tove

Svendson, Stephen

Pettersen, Kari

Turner, Sally

Kent, Clark

Svendson, Stephen

Scott, Stephen

What are the difference between DDL, DML and DCL commands?

DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT statements

DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.

Examples: GRANT, REVOKE statements

TCL

TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database.

Examples: COMMIT, ROLLBACK statements

DDL

Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:

Page 5: Difference SQL Latest

o CREATE - to create objects in the database o ALTER - alters the structure of the database o DROP - delete objects from the database o TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed o COMMENT - add comments to the data dictionary o RENAME - rename an object

DML

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples: o SELECT - retrieve data from the a database o INSERT - insert data into a table o UPDATE - updates existing data within a table o DELETE - deletes all records from a table, the space for the records remain o MERGE - UPSERT operation (insert or update) o CALL - call a PL/SQL or Java subprogram o EXPLAIN PLAN - explain access path to data o LOCK TABLE - control concurrency

DCL

Data Control Language (DCL) statements. Some examples: o GRANT - gives user's access privileges to database o REVOKE - withdraw access privileges given with the GRANT command

TCL

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

o COMMIT - save work done o SAVEPOINT - identify a point in a transaction to which you can later roll back o ROLLBACK - restore database to original since the last COMMIT o SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

DDL COMMANDS:CREATE,ALTER,DROP AND TRUNCATE ARE CALLED DDL COMMANDS. They are called Data Definition since they are used for defining the data. That is the structure of the data is known through these DDL commands.

DML COMMANDS:DML commands are used for data manipulation. Some of the DML commandsinsert,select,update,delete etc. Even though select is not exactly a DML language command oracle still recommends you to consider SELECT as an DML command.

TCL:For revoking the transactions and to make the data commit to the database we use TCL. Some of the TCL commands are:1. ROLLBACK2. COMMIT

ROLLBACK is used for revoking the transactions until last commit.COMMIT is used for commiting the transactions to the database.Once we commit we cannot rollback. Once we rollback we cannot commit.Commit and Rollback are generally used to commit or revoke the transactions that are with regard to DML commands.

DCL:Data Control Language is used for the control of data. That is a user can access any data based on the priveleges given to him. This is done through DATA CONTROL LANGUAGE. Some of the DCL Commands are:1. GRANT2. REVOKE

Page 6: Difference SQL Latest

Difference between DELETE, TRUNCATE and DROP

  DELETE TRUNCATE DROP

Purpose Deletes some or all rows of a table

Deletes all rows of a table Removes all rows and also the table definition, including indexes, triggers, grants, storage parameters

Command Type DML DDL DDL

Space Usage and Release

Uses UNDO space. Does not use UNDO space.

Does not use UNDO space.

Released blocks that go to the freelist for the table, to be used for subsequent inserts/updates. Does not deallocate space.

Deallocates all space used by the table except MINEXTENTS.

Unless the PURGE clause is specified, does not result in space being released.

Commit required? Yes No No

Undo possible? Uncommitted deletes can be rolled back

Cannot be rolled back – once truncated, gone forever

A dropped table can be reinstated from the recycle bin (more on this in a future article)

Selective deletion possible?

Yes. Filter criteria be specified via WHERE clause

No filter criteria allowed, removes all rows

No filter criteria allowed, removes all rows

Triggers fired? Yes, DELETE triggers fired

No triggers fired No triggers fired

What if foreign keys (FKs) based on the

table exist?

Can delete data even if FKs are enabled, provided the data violates no FK constraint

Cannot delete data if FKs are enabled; FKs need to be disabled/dropped.

Can drop the table with the CASCADE CONSTRAINTS option. This will also remove the associated FKs

Exception: Truncate is possible if the FK is self-referential.

Page 7: Difference SQL Latest

Efficiency DELETE can be slow especially if the table has many triggers, indexes,and other dependencies

TRUNCATE is most efficient for deleting all rows, even more than dropping and recreating the table using DROP

DROP may not be as efficient as TRUNCATE, as dropping and re-creating the table requires you to re-grant object privileges, re-create indexes, constraints, etc.

Privileges required to issue the command

DELETE privilege. DROP ANY TABLE system privilege.

DROP ANY TABLE system privilege.

DELETE ANY TABLE allows you to delete rows from any table of any schema.

Grants DELETE privilege on a specific table can be granted to another user or role.

TRUNCATE privilege on a specific table cannot be granted to another user or role.

DROP ANY privilege on a specific table cannot be granted to another user or role.

Can work outside the user’s schema?

Yes, as long as the user has the DELETE privilege on the object.

No. A table can be truncated in one’s own schema only.

No. A table can be dropped in one’s own schema only.

Can work on a table that is part of a

cluster?

Yes No. You will have to truncate the whole cluster, or use either DELETE or DROP.

Yes

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.

TRUNCATE removes all rows from a table. The operation cannot be rolled back. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. The operation cannot be rolled back.

DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.

The delete statement will result in the table spaces or memories would remain as the current size and table structure remain in the database. Delete is not effective when you use it to remove all data from a table because it takes up storeage spaces due to unclear memories. The truncate statement will result in clearing table spaces or memories and the table structure remain in the database. Therefore it free table storage spaces and only use it when you need to remove all data from a table. The drop statement will result in completely removing the table from the database. Note: Statements above are made with the assumption that a commit is has been executed. Once a commit statement is executed (commit is final). Therefore rollback a transaction will not work if commit statement is executed.

DELETE

Page 8: Difference SQL Latest

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.

SQL> SELECT COUNT(*) FROM emp; COUNT(*)---------- 14SQL> DELETE FROM emp WHERE job = 'CLERK';4 rows deleted.SQL> COMMIT;Commit complete.SQL> SELECT COUNT(*) FROM emp; COUNT(*)---------- 10TRUNCATETRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

SQL> TRUNCATE TABLE emp;Table truncated.SQL> SELECT COUNT(*) FROM emp;

COUNT(*)---------- 0DROPThe DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.

SQL> DROP TABLE emp;Table dropped.SQL> SELECT * FROM emp;SELECT * FROM emp *ERROR at line 1:ORA-00942: table or view does not exist

DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.

DELETEDelete is the command that only remove the data from the table. It is DML statement. Deleted data can be rollback. By using this we can delete whole data from the table(if use without where clause).If ew want to remove only selected data then we should specify condition in the where clauseSQL>delete from employee;(this command will remove all the data from table)SQL>delete from employee where employee_name='JOHN';(This command will remove only that row from employee table where employee_name is JOHN');

DROP:Drop command remove the table from data dictionary. This is the DDL statement. We can not recover the table before Oracle 10g. But Oracle 10g provide the command to recover it by using the command (FLASHBACK)

TRUNCATE:This is the DML command. This command delete the data from table. But there is one difference from ordinary delete command. Truncate command drop the storage held by this table. Drop storage can be use by this table again or some other table. This is the faster command because it directly drop the storage

Page 9: Difference SQL Latest

SQL Delete Statement

The DELETE Statement is used to delete rows from a table.

The Syntax of a SQL DELETE statement is:

DELETE FROM table_name [WHERE condition];

table_name -- the table name which has to be updated.

NOTE:The WHERE clause in the sql delete command is optional and it identifies the rows in the column that gets deleted. If you do not include the WHERE clause all the rows in the table is deleted, so be careful while writing a DELETE query without WHERE clause.

For Example: To delete an employee with id 100 from the employee table, the sql delete query would be like,

DELETE FROM employee WHERE id = 100; To delete all the rows from the employee table, the query would be like, DELETE FROM employee;

SQL TRUNCATE Statement

The SQL TRUNCATE command is used to delete all the rows from the table and free the space containing the table.

Syntax to TRUNCATE a table:

TRUNCATE TABLE table_name;

For Example: To delete all the rows from employee table, the query would be like,

TRUNCATE TABLE employee;

Difference between DELETE and TRUNCATE Statements:

DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.

TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.

SQL DROP Statement:

The SQL DROP command is used to remove an object from the database. If you drop a table, all the rows in the table is

deleted and the table structure is removed from the database. Once a table is dropped we cannot get it back, so be careful

while using RENAME command. When a table is dropped all the references to the table will not be valid.

Syntax to drop a sql table structure:

Page 10: Difference SQL Latest

DROP TABLE table_name;

For Example: To drop the table employee, the query would be like

DROP TABLE employee;

Difference between DROP and TRUNCATE Statement:

If a table is dropped, all the relationships with other tables will no longer be valid, the integrity constraints will be dropped, grant or access privileges on the table will also be dropped, if want use the table again it has to be recreated with the integrity constraints, access privileges and the relationships with other tables should be established again. But, if a table is truncated, the table structure remains the same, therefore any of the above problems will not exist.

difference between inner and outer join

An inner join of A and B gives the result of A intersect B, i.e. the inner part of a venn diagram intersection.

An outer join of A and B gives the results of A union B, i.e. the outer parts of a venn diagram union.

Examples

Suppose you have two Tables, with a single column each, and data as follows:

A    B-    -1    32    43    54    6

Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.

inner join

An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in

common.

select * from a INNER JOIN b on a.a = b.b;select a.*,b.*  from a,b where a.a = b.b;

a | b--+--3 | 34 | 4

left outer join

A left outer join will give all rows in A, plus any common rows in B.

select * from a LEFT OUTER JOIN b on a.a = b.b;select a.*,b.*  from a,b where a.a = b.b(+);

a |  b  --+-----1 | null2 | null

Page 11: Difference SQL Latest

3 |    34 |    4

full outer join

A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't

have a corresponding datum in B, then the B portion is null, and vice versa.

select * from a FULL OUTER JOIN b on a.a = b.b;

 a   |  b  -----+-----   1 | null   2 | null   3 |    3   4 |    4null |    6null |    5

Joins

A join is a query that combines rows from two or more tables, views, or materialized views. Oracle Database performs a join whenever multiple tables appear in the FROM clause of the query. The select list of the query can select any columns from any of these tables. If any two of these tables have a column name in common, then you must qualify all references to these columns throughout the query with table names to avoid ambiguity.

Join Conditions

Most join queries contain at least one join condition, either in the FROM clause or in the WHERE clause. The join condition compares two columns, each from a different table. To execute a join, Oracle Database combines pairs of rows, each containing one row from each table, for which the join condition evaluates to TRUE. The columns in the join conditions need not also appear in the select list.

To execute a join of three or more tables, Oracle first joins two of the tables based on the join conditions comparing their columns and then joins the result to another table based on join conditions containing columns of the joined tables and the new table. Oracle continues this process until all tables are joined into the result. The optimizer determines the order in which Oracle joins tables based on the join conditions, indexes on the tables, and, any available statistics for the tables.

IA WHERE clause that contains a join condition can also contain other conditions that refer to columns of only one table. These conditions can further restrict the rows returned by the join query.

Note:You cannot specify LOB columns in the WHERE clause if the WHERE clause contains the join condition. The use of LOBs in WHERE clauses is also subject to other restrictions. See Oracle Database SecureFiles and Large Objects Developer's Guide for more information.

Equijoins

An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that have equivalent values for the specified columns. Depending on the internal algorithm the optimizer chooses to execute the join, the total size of the columns in the equijoin condition in a single table may be limited to the size of a data block minus some overhead. The size of a data block is specified by the initialization parameter DB_BLOCK_SIZE.

See Also:"Using Join Queries: Examples"

Page 12: Difference SQL Latest

Self Joins

A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. To perform a self join, Oracle Database combines and returns rows of the table that satisfy the join condition.

See Also:"Using Self Joins: Example"

Cartesian Products

If two tables in a join query have no join condition, then Oracle Database returns their Cartesian product. Oracle combines each row of one table with each row of the other. A Cartesian product always generates many rows and is rarely useful. For example, the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include a join condition unless you specifically need a Cartesian product. If a query joins three or more tables and you do not specify a join condition for a specific pair, then the optimizer may choose a join order that avoids producing an intermediate Cartesian product.

Inner Joins

An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy the join condition.

Outer Joins

An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and also returns some or all of those rows from one table for which no rows from the other satisfy the join condition.

To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer join), use the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of B in the join condition in the WHERE clause. For all rows in A that have no matching rows in B, Oracle Database returns null for any select list expressions containing columns of B.

To write a query that performs an outer join of tables A and B and returns all rows from B (a right outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of A in the join condition in the WHERE clause. For all rows in B that have no matching rows in A, Oracle returns null for any select list expressions containing columns of A.

To write a query that performs an outer join and returns all rows from A and B, extended with nulls if they do not satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the FROM clause.

You cannot compare a column with a subquery in the WHERE clause of any outer join, regardless which form you specify.

You can use outer joins to fill gaps in sparse data. Such a join is called a partitioned outer join and is formed using the query_partition_clause of the join_clause syntax. Sparse data is data that does not have rows for all possible values of a dimension such as time or department. For example, tables of sales data typically do not have rows for products that had no sales on a given date. Filling data gaps is useful in situations where data sparsity complicates analytic computation or where some data might be missed if the sparse data is queried directly.

See Also:

join_clause for more information about using outer joins to fill gaps in sparse data Oracle Database Data Warehousing Guide for a complete discussion of group outer joins and filling gaps in

sparse data

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to the FROM clause OUTER JOIN syntax:

Page 13: Difference SQL Latest

You cannot specify the (+) operator in a query block that also contains FROM clause join syntax. The (+) operator can appear only in the WHERE clause or, in the context of left-correlation (when specifying the

TABLE clause) in the FROM clause, and can be applied only to a column of a table or view.

If A and B are joined by multiple join conditions, then you must use the (+) operator in all of these conditions. If you do not, then Oracle Database will return only the rows resulting from a simple join, but without a warning or error to advise you that you do not have the results of an outer join.

The (+) operator does not produce an outer join if you specify one table in the outer query and the other table in an inner query.

You cannot use the (+) operator to outer-join a table to itself, although self joins are valid. For example, the following statement is not valid:

-- The following statement is not valid: SELECT employee_id, manager_id FROM employees WHERE employees.manager_id(+) = employees.employee_id;

However, the following self join is valid:

SELECT e1.employee_id, e1.manager_id, e2.employee_id FROM employees e1, employees e2 WHERE e1.manager_id(+) = e2.employee_id ORDER BY e1.employee_id, e1.manager_id, e2.employee_id;

The (+) operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary expression can contain one or more columns marked with the (+) operator.

A WHERE condition containing the (+) operator cannot be combined with another condition using the OR logical operator.

A WHERE condition cannot use the IN comparison condition to compare a column marked with the (+) operator with an expression.

If the WHERE clause contains a condition that compares a column from table B with a constant, then the (+) operator must be applied to the column so that Oracle returns the rows from table A for which it has generated nulls for this column. Otherwise Oracle returns only the results of a simple join.

In a query that performs outer joins of more than two pairs of tables, a single table can be the null-generated table for only one other table. For this reason, you cannot apply the (+) operator to columns of B in the join condition for A and B and the join condition for B and C. Refer to SELECT for the syntax for an outer join.

Antijoins

An antijoin returns rows from the left side of the predicate for which there are no corresponding rows on the right side of the predicate. It returns rows that fail to match (NOT IN) the subquery on the right side.

See Also:"Using Antijoins: Example"

Semijoins

A semijoin returns rows that match an EXISTS subquery without duplicating rows from the left side of the predicate when multiple rows on the right side satisfy the criteria of the subquery.

Semijoin and antijoin transformation cannot be done if the subquery is on an OR branch of the WHERE clause.

What is the difference between Modify, Insert, Update commands

Page 14: Difference SQL Latest

Modiy is used to edit and change the existing record. In case of database table if the record exist then it will try to modiy otherwise it will inser new record.

Insert is used to insert a record in the tabel in a speicified place.

Update is used to change the existing record.

INSERT - inserts a new record. INSERT expects that a record with the required key does NOT exist in the table. Therefore, if a record with the same key already exists, a runtime error occurs. For more details on INSERT, visit here.

UPDATE - update an existing record. UPDATE expects that a record with required key exists in the table. If a record with the required key does not exist, it issue an error (sy-subrc is 4). For more details on UPDATE, visit here.

MODIFY - acts like a combination of INSERT and UPDATE. If a record with the specified key does not exist, it adds it to the table. If a record with the specified key does exist, it modifies it. So MODIFY actually acts like "Insert or change record". To read more about MODIFY, visit here.

To summarize:INSERT - adds a new record to the table. If the row (key) exists, issues an error.UPDATE - updates an existing record to the table. If the row (key) does not exist, issues an error.MODIFY - If the key exists, modifies the record. If the key does not exist, adds the record to the table.

SQL Integrity Constraints

Integrity Constraints are used to apply business rules for the database tables.

The constraints available in SQL are Foreign Key, Not Null, Unique, Check.

Constraints can be defined in two ways

1) The constraints can be specified immediately after the column definition. This is called column-level definition.

2) The constraints can be specified after all the columns are defined. This is called table-level definition.

1) SQL Primary key:

This constraint defines a column or combination of columns which uniquely identifies each row in the table.

Syntax to define a Primary key at column level:

column name datatype [CONSTRAINT constraint_name] PRIMARY KEY

Syntax to define a Primary key at table level:

[CONSTRAINT constraint_name] PRIMARY KEY (column_name1,column_name2,..)

column_name1, column_name2 are the names of the columns which define the primary Key.

The syntax within the bracket i.e. [CONSTRAINT constraint_name] is optional.

For Example: To create an employee table with Primary Key constraint, the query would be like.

Primary Key at table level:

Page 15: Difference SQL Latest

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), salary number(10), location char(10) );

or

CREATE TABLE employee( id number(5) CONSTRAINT emp_id_pk PRIMARY KEY, name char(20),dept char(10),age number(2),salary number(10),location char(10));

Primary Key at table level:

CREATE TABLE employee ( id number(5), name char(20),dept char(10),age number(2),salary number(10),location char(10),CONSTRAINT emp_id_pk PRIMARY KEY (id));

2) SQL Foreign key or Referential Integrity :

This constraint identifies any column referencing the PRIMARY KEY in another table. It establishes a relationship between two columns in the same table or between different tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One or more columns can be defined as Foreign key.

Syntax to define a Foreign key at column level:

[CONSTRAINT constraint_name] REFERENCES Referenced_Table_name(column_name)

Syntax to define a Foreign key at table level:

[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES referenced_table_name(column_name);

For Example:

1) Lets use the "product" table and "order_items".

Foreign Key at column level:

Page 16: Difference SQL Latest

CREATE TABLE product ( product_id number(5) CONSTRAINT pd_id_pk PRIMARY KEY, product_name char(20),supplier_name char(20),unit_price number(10));CREATE TABLE order_items( order_id number(5) CONSTRAINT od_id_pk PRIMARY KEY,product_id number(5) CONSTRAINT pd_id_fk REFERENCES, product(product_id),product_name char(20),supplier_name char(20),unit_price number(10));

Foreign Key at table level:

CREATE TABLE order_items( order_id number(5) ,product_id number(5),product_name char(20),supplier_name char(20),unit_price number(10)CONSTRAINT od_id_pk PRIMARY KEY(order_id),CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES product(product_id));

2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references primary key 'id' within the same table, the query would be like,

CREATE TABLE employee( id number(5) PRIMARY KEY,name char(20),dept char(10),age number(2),mgr_id number(5) REFERENCES employee(id),salary number(10),location char(10) );

3) SQL Not Null Constraint :

This constraint ensures all rows in the table contain a definite value for the column which is specified as not null. Which means a null value is not allowed.

Syntax to define a Not Null constraint:

[CONSTRAINT constraint name] NOT NULL

For Example: To create a employee table with Null value, the query would be like

CREATE TABLE employee( id number(5),name char(20) CONSTRAINT nm_nn NOT NULL,dept char(10),age number(2),salary number(10),location char(10) );

Page 17: Difference SQL Latest

4) SQL Unique Key:

This constraint ensures that a column or a group of columns in each row have a distinct value. A column(s) can have a null value but the values cannot be duplicated.

Syntax to define a Unique key at column level:

[CONSTRAINT constraint_name] UNIQUE

Syntax to define a Unique key at table level:

[CONSTRAINT constraint_name] UNIQUE(column_name)

For Example: To create an employee table with Unique key, the query would be like,

Unique Key at column level:

CREATE TABLE employee( id number(5) PRIMARY KEY,name char(20),dept char(10),age number(2),salary number(10),location char(10) UNIQUE ); or CREATE TABLE employee( id number(5) PRIMARY KEY,name char(20),dept char(10),age number(2),salary number(10),location char(10) CONSTRAINT loc_un UNIQUE );

Unique Key at table level:

CREATE TABLE employee( id number(5) PRIMARY KEY,name char(20),dept char(10),age number(2),salary number(10),location char(10),CONSTRAINT loc_un UNIQUE(location) );

5) SQL Check Constraint :

This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint can be applied for a single column or a group of columns.

Syntax to define a Check constraint:

[CONSTRAINT constraint_name] CHECK (condition)

For Example: In the employee table to select the gender of a person, the query would be like

Check Constraint at column level:

Page 18: Difference SQL Latest

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), gender char(1) CHECK (gender in ('M','F')), salary number(10), location char(10) );

Check Constraint at table level:

CREATE TABLE employee ( id number(5) PRIMARY KEY, name char(20), dept char(10), age number(2), gender char(1), salary number(10), location char(10), CONSTRAINT gender_ck CHECK (gender in ('M','F')) ); Referential integrity

Referential integrity is a database concept that ensures that relationships between tables remain consistent. When one table has a foreign key to another table, the concept of referential integrity states that you may not add a record to the table that contains the foreign key unless there is a corresponding record in the linked table. It also includes the techniques known as cascading update and cascading delete, which ensure that changes made to the linked table are reflected in the primary table.

Consider the situation where we have two tables: Employees and Managers. The Employees table has a foreign key attribute entitled ManagedBy which points to the record for that employee’s manager in the Managers table. Referential integrity enforces the following three rules:

We may not add a record to the Employees table unless the ManagedBy attribute points to a valid record in the Managers table.

If the primary key for a record in the Managers table changes, all corresponding records in the Employees table must be modified using a cascading update.

If a record in the Managers table is deleted, all corresponding records in the Employees table must be deleted using a cascading delete.

A REFERENTIAL INTEGRITY is a database concept that is used to build and maintain logical relationships between tables to avoid logical corruption of data. It is a very useful and important part in RDBMS.

Usually referential integrity is made up by the combination of a primary key and a foreign key.

The main concept of REFERENTIAL INTEGRITY is that, it does not allow to add any record in a table that contains the foreign key unless the reference table containing a corresponding primary key.

If any record in referenced table (i.e. the table who contain primary key) is deleted, all the corresponding records in the referencing table will be deleted for the referential integrity.

How to find out duplicate records in sql server?

we have to use the group by with having command to get the duplicate values. this query shall show the result of only the users have duplicate values in the employee table.

Page 19: Difference SQL Latest

Syntex:Select columnName From Table_nameGroup By columnNameHaving count (*) > 1

Example:SELECT  UserID FROM employeeGROUP BY useridHAVING count( * ) > 1

select *from tablegroup by key1, key2, ..., keyNhaving count (*) > 1;