SQL – AppDividend https://appdividend.com Latest Code Tutorials Mon, 15 Jul 2019 04:11:59 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png SQL – AppDividend https://appdividend.com 32 32 SQL Views Example | Views In SQL Tutorial Explained In Detail https://appdividend.com/2019/07/15/sql-views-example-views-in-sql-tutorial-explained-in-detail/ https://appdividend.com/2019/07/15/sql-views-example-views-in-sql-tutorial-explained-in-detail/#respond Mon, 15 Jul 2019 04:10:01 +0000 http://localhost/wordpress/?p=9683 SQL Views Example | Views In SQL Tutorial Explained In Detail

SQL Views Example | Views In SQL Tutorial is today’s topic. SQL views is a kind of virtual tables which have rows and columns as they are in a real database. A view can be accompanied with all the rows of a particular table or selected rows based on a certain condition. In Structured Query […]

The post SQL Views Example | Views In SQL Tutorial Explained In Detail appeared first on AppDividend.

]]>
SQL Views Example | Views In SQL Tutorial Explained In Detail

SQL Views Example | Views In SQL Tutorial is today’s topic. SQL views is a kind of virtual tables which have rows and columns as they are in a real database. A view can be accompanied with all the rows of a particular table or selected rows based on a certain condition. In Structured Query Language, a view is a virtual table based on the result-set of an SQL statement.

SQL VIEWS

SQL view contains rows and columns, just like the real table. The fields in the view are fields from one or more real tables in the database. You can add the SQL functions, WHERE, and JOIN statements to the view and present a data as if that data were coming from a single table.

Let’s learn to create, deleting, and updating views.

Consider two tables:

Student:

ID NAME CITY
1 Shubh Kolkata
2 Karan Allahabad
3 Suraj Kota
4 Akash Vizag

 

Marks:

ID NAME MARKS Age
1 Shubh 90 21
2 Rohit 91 21
3 Suraj 92 22
4 Akash 93 22

 

#CREATING VIEWS

Let’s create views using single tables or multiple tables.

#SYNTAX

Create View View_name AS
Select column(s)
From table_name
Where condition;

#PARAMETERS:

  1. View_name: Name of the View.
  2. Column(s): Name of the column.
  3. Table_name: Name of the table.
  4. Where: This is used for specifying some conditions.

Let’s clear this with the help of an example.

#QUERY: (Creating View With a single table)

Create view Details AS
Select name, city
From Student
Where id>=1;

#Output

Type the following query to get the output.

Select * from Details;

See the below output.

NAME CITY
Shubh Kolkata
Karan Allahabad
Suraj Kota
Akash Vizag

 

#QUERY: (Creating Views from Multiple Tables)

Create View Marks AS
Select Student.Name, Student.City, Marks.Marks
From Student, Marks
Where Student.Name=Marks.Name;

OUTPUT

Fire the following query.

Select * from Marks;

See the output.

NAME CITY Marks
Shubh Kolkata 90
Suraj Kota 92
Akash Vizag 93

 

So, until now, we have learned how to create views.

Let’s Learn how to delete views.

#DELETING VIEWS

Views can be removed with the help of DROP Statement.

#SYNTAX

Drop VIEW view_name;

See the following parameters.

#PARAMETERS

View_name: This is the name of the View which you want to delete.

#QUERY

Drop VIEW Details;

So, the View Details will be deleted which we had created above.

So, we have learned how to delete views.

Let’s learn how to update views.

#UPDATING VIEWS

Views can be updated with the help of Create or replace statement.

#SYNTAX:

Create or Replace View View_Name AS
Select column(s)
From table_name
Where condition;

#PARAMETERS:

  1. View_name: Name of the View.
  2. Column(s): Name of the column.
  3. Table_name: Name of the table.
  4. Where: This is used for specifying some conditions.

Let’s clear this with the help of an example.

Suppose, we want to add student Age as well in Marks view then following queries has to be written.

#QUERY

Create or replace View MARKS AS
Select Student.Name, Student.City, Marks.Marks, Marks.Age
From Student, Marks
Where Student.Name=Marks.Name;

#OUTPUT

Select * from MARKS;

See the output.

NAME CITY Marks Age
Shubh Kolkata 90 21
Suraj Kota 92 22
Akash Vizag 93 22

 

#Inserting a row in a view.

We can insert values in view as that of we insert into the table.

#SYNTAX

Insert into view_name (column(s)) VALUES (values);

#PARAMETERS

View_name: This is the name of the View which you want to delete.

#QUERY

INSERT INTO DETAILS (Name, City) VALUES(‘Aman’,’Patna’);

#OUTPUT

Select * from DETAILS;
NAME CITY
Shubh Kolkata
Karan Allahabad
Suraj Kota
Akash Vizag
Aman Patna

 

We have considered here the view details which was previously created in CREATE VIEW Query.

#Deleting a row from a view

We can Delete the details from the view using the DELETE statement.

#SYNTAX

DELETE FROM view_name where Condition;

#PARAMETERS

View_name: This is the name of the View which you want to delete.

#QUERY:

Delete from details where name=”Aman”;

#OUTPUT:

Fire the following query.

Select * from Details;
NAME CITY
Shubh Kolkata
Karan Allahabad
Suraj Kota
Akash Vizag

 

# SQL Views Keynote:

One should keep in his/her mind to consider these following points before updating the views.

  1. Group by Clause and Order By clause should not be included with the create statement.
  2. DISTINCT keyword should not be present with the select statement.
  3. The view should not contain any NULL values.
  4. The views should not be created with Nested Queries or Complex Queries.
  5. Views should not be created with multiple views.

Finally, SQL Views Example | Views In SQL Tutorial Explained In Detail is over.

The post SQL Views Example | Views In SQL Tutorial Explained In Detail appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/15/sql-views-example-views-in-sql-tutorial-explained-in-detail/feed/ 0
SQL CREATE INDEX Statement Tutorial With Example https://appdividend.com/2019/07/11/sql-create-index-statement-tutorial-with-example/ https://appdividend.com/2019/07/11/sql-create-index-statement-tutorial-with-example/#respond Thu, 11 Jul 2019 06:33:04 +0000 http://localhost/wordpress/?p=9579 SQL CREATE INDEX Statement Tutorial With Example

SQL CREATE INDEX Statement Tutorial With Example is today’s topic. SQL CREATE INDEX statement is used to create the indexes in the tables. Indexes are used to retrieve the data from the database very fast. The users cannot see the indexes, and they are just used to speed up the searches/queries. Updating the table with […]

The post SQL CREATE INDEX Statement Tutorial With Example appeared first on AppDividend.

]]>
SQL CREATE INDEX Statement Tutorial With Example

SQL CREATE INDEX Statement Tutorial With Example is today’s topic. SQL CREATE INDEX statement is used to create the indexes in the tables. Indexes are used to retrieve the data from the database very fast. The users cannot see the indexes, and they are just used to speed up the searches/queries. Updating the table with indexes takes more time than updating the table without (because the indexes also need the update). So, only create indexes on the columns that will be frequently searched against.

#What is an Index in SQL

The index is a performance-tuning method of allowing the faster retrieval of records. SQL index creates the entry for each value that appears in the indexed columns. Each index name must be unique in the database.

SQL CREATE INDEX Statement

SQL Indexes are used to improve the efficiency of searches for data, presenting the data in the specific order when joining tables (see the “JOIN” Guides) and more.

An index is a “system” object, meaning that the database manager uses it.

Part of this usage is for the DBMS to update the index when the data used by index changes in the related table. Keep this in mind because as the number of indexes increase in the database, overall system performance can be impacted.

If you find that your SQLs are running slow on the given table or tables, creating the index is the first thing to consider to correct that issue.

See the following syntax of CREATE INDEX.

CREATE INDEX index_name
ON table_name (column1, column2, ...);

See the following example.

CREATE INDEX IDX_ProductName
ON Products (ProductName);

In the above query, we have created an index called IDX_ProductName on the Products table, and the column name is ProductName.

If you want to create the index on the combination of columns, you can list all the column names within the parentheses, separated by commas. See the following query.

CREATE INDEX IDXname
ON Products (ProductName, id);

In the above query, we have changed the syntax name, and we have added two columns.

  1. ProductName
  2. id

simple index is an index on the single column, while the composite index is an index on two or more columns. In the examples above, ProductNameIx is the simple index because there is only one column, while IDX_proname_id is the composite index because there are two columns.

There is no strict or universal rule on how to name the index. The generally accepted method is to place the prefix, such as “IDX_,” before the index name to avoid the confusion with other database objects. It is also a great idea to provide an information on which table and column(s) the index is used on.

Here one thing you need to note that the exact syntax for CREATE INDEX may be different for the different DBMS. You should consult with your database manual for the related database syntax.

#Unique Index in SQL

Similar to a primary key, a unique key allows you to choose one column or combination of columns that must be unique for each record. Although you can only have one primary key on a table, you can create as many unique indexes on a table as you need.

If we want to create a unique index on the table, you need to specify a UNIQUE keyword in the CREATE INDEX statement. See the following example.

CREATE UNIQUE INDEX IDX_ProductName
  ON Apps (ProductName);

In the above query, we have created an index called IDX_ProductName on the Apps table. The column name on which we are indexing is here ProductName.

Above example would create a unique index on the ProductName field so that this field must always contain a unique value with no duplicates. This is a great way to enforce the integrity within your database if you require the unique values in the columns that are not part of your primary key.

Finally, SQL CREATE INDEX Statement Tutorial With Example is over.

The post SQL CREATE INDEX Statement Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/11/sql-create-index-statement-tutorial-with-example/feed/ 0
SQL Truncate Table Statement Tutorial With Example https://appdividend.com/2019/07/11/sql-truncate-table-statement-tutorial-with-example/ https://appdividend.com/2019/07/11/sql-truncate-table-statement-tutorial-with-example/#respond Thu, 11 Jul 2019 05:27:13 +0000 http://localhost/wordpress/?p=9568 SQL Truncate Table Statement Tutorial With Example

SQL Truncate Table Statement Tutorial With Example is today’s topic. The DROP TABLE the command deletes a table in the database. Be careful before removing a table and deleting table results in loss of all information stored in the table. The TRUNCATE TABLE command deletes the data inside a table, but not the table itself. […]

The post SQL Truncate Table Statement Tutorial With Example appeared first on AppDividend.

]]>
SQL Truncate Table Statement Tutorial With Example

SQL Truncate Table Statement Tutorial With Example is today’s topic. The DROP TABLE the command deletes a table in the database. Be careful before removing a table and deleting table results in loss of all information stored in the table. The TRUNCATE TABLE command deletes the data inside a table, but not the table itself.

SQL Truncate Table Statement

TRUNCATE statement is the Data Definition Language (DDL) operation that is used to mark the extents of the table for deallocation (empty for reuse).

The result of this operation quickly deletes all the data from the table, typically bypassing the number of integrity enforcing mechanisms. The truncate was officially introduced in SQL:2008 standard.

SQL Truncate performs the same function as a DELETE statement without a WHERE clause.

Okay, now let’s see the syntax of SQL Truncate Table.

TRUNCATE TABLE table_name

Okay, now let’s see the following example.

See the following table.

 

SQL Truncate Table Statement

I have already created and inserted the data into the Apps table.

Now, we will truncate the Apps table using the following query.

TRUNCATE TABLE Apps;

So, it has removed all the data

Now, again type the following query and try to fetch all the records.

Select * from Apps

You will see that there are data left inside the table.

#DROP TABLE and TRUNCATE TABLE

The significant difference between the Drop Table and Truncate Table is that DROP table deletes the table itself, whereas the Truncate Table does not eliminate the Table itself, it removes the data from the table.

You might choose to truncate the table instead of dropping the table and recreating it.

Truncating the table can be faster and does not affect any of the table’s indexes, triggers, and dependencies. It is also a quick way to clear out the records from the table if you don’t need to worry about the rolling back.

So, DROP TABLE command to delete the complete table, but it would remove the entire table structure form the database, and you will need to re-create that table once again if you wish you store some data still or in the future.

Table or Database deletion using a DROP statement cannot be rolled back, so it must be used wisely.

#DELETE TABLE Vs. TRUNCATE TABLE

Truncate table is much faster and it uses lesser resources than the DELETE TABLE statement.

If the table contains a primary key column, the counter for that column will be reset to a first value. For example, we have ID INT IDENTITY(1, 1) which contains the 100 rows/records, and we performed the TRUNCATE Statement table on ID. That truncate statement will delete all the rows from ID, and reset the IDENTITY to 1.

If you are using the DELETE TABLE query and remove one id, then next id will be removed id + 1. Means it does not restructure the whole data.

If the particular id row is gone, then it is gone. That id will not assign to another row in case of DELETE TABLE.

The SQL Truncate Table query deletes all the rows from a specified table, but the table structure, constraints, columns, indexes will remain the same.

Finally, SQL Truncate Table Statement Tutorial With Example is over.

The post SQL Truncate Table Statement Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/11/sql-truncate-table-statement-tutorial-with-example/feed/ 0
SQL Delete Query Tutorial | Delete Statement In SQL Example https://appdividend.com/2019/07/11/sql-delete-query-tutorial-delete-statement-in-sql-example/ https://appdividend.com/2019/07/11/sql-delete-query-tutorial-delete-statement-in-sql-example/#respond Thu, 11 Jul 2019 04:21:03 +0000 http://localhost/wordpress/?p=9553 SQL Delete Query Tutorial | Delete Statement In SQL Example

SQL Delete Query Tutorial | Delete Statement In SQL Example is today’s topic. The DELETE statement is used to remove existing records in a table. We have already seen the create table, insert row, update row, and now we will see how to remove or delete the row from the SQL table. You can use […]

The post SQL Delete Query Tutorial | Delete Statement In SQL Example appeared first on AppDividend.

]]>
SQL Delete Query Tutorial | Delete Statement In SQL Example

SQL Delete Query Tutorial | Delete Statement In SQL Example is today’s topic. The DELETE statement is used to remove existing records in a table. We have already seen the create table, insert row, update row, and now we will see how to remove or delete the row from the SQL table. You can use the WHERE clause with the DELETE query to delete the selected rows; otherwise, all the records would be eliminated.

SQL Delete Query

Delete query is a type of DML type of statement in which we manipulate the tables. If you are not careful while deleting the records from the table, then you will end up losing lots of data.

#Syntax

See the following syntax of SQL Delete Statement.

DELETE FROM table
WHERE [condition];

In the above query, we need to specify the table name and a condition; otherwise, the whole table will delete. You can also combine the N number of conditions using AND or OR operators.

See the following table.

 

SQL Delete Query Tutorial

Now, let’s write a query where we will remove the AFTERGAME SNEAKER row.

DELETE FROM Products
WHERE ProductName = 'AFTERGAME SNEAKER'

Okay, so if the query is executed successfully, then now select all the rows using the following query.

Select * from Products

Now, see the output. There are not four rows.

 

Delete Statement In SQL

If you want to remove all the records from the Products table, you do not have to use the WHERE clause, and the DELETE statement would be as follows.

DELETE from Products

It will remove all the data from the Products table.

#SQL Truncate Statement

If you want to remove all the rows in the big table, you should use the TRUNCATE TABLE query which is more efficient than the DELETE statement.

#SQL DELETE related rows in multiple tables

It becomes more and more complicated when you want to delete the row in the table which is associated with the other rows in another table. We can define the relationships between the two tables using Foreign Key.

For instance, let’s say we have two tables.

  1. Categories
  2. Products

Each product belongs to one category, and a category has multiple products.

That means, if we delete a particular category, then we have to remove all the products related to that category; otherwise the integrity among the tables will be violated.

So, one table has a primary key, and another table has the foreign key, and foreign key defines the relationships between those tables.

See the following query.

DELETE from categories
WHERE id = 3;

DELETE from products
WHERE category_id = 3

Most database management systems (DBMS) allows us to create the foreign key constraint so that if you delete a row in the table, the corresponding rows to the related table are also removed automatically.

It ensures the integrity of the data. In our case, you just have to run the first DELETE statement only to delete the rows in two tables.

If the database management system does not support any foreign key constraint, you have to run both DELETE statements in the single transaction to make sure that the statements run in all-or-nothing mode.

So, DELETE Statement permanently removes records from a table.

Finally, SQL Delete Query Tutorial | Delete Statement In SQL Example is over.

The post SQL Delete Query Tutorial | Delete Statement In SQL Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/11/sql-delete-query-tutorial-delete-statement-in-sql-example/feed/ 0
SQL Merge Statement Tutorial With Example | Merge In SQL https://appdividend.com/2019/07/11/sql-merge-statement-tutorial-with-example-merge-in-sql/ https://appdividend.com/2019/07/11/sql-merge-statement-tutorial-with-example-merge-in-sql/#respond Thu, 11 Jul 2019 03:09:02 +0000 http://localhost/wordpress/?p=9515 SQL Merge Statement Tutorial With Example | Merge In SQL

SQL Merge Statement Tutorial With Example is today’s topic. SQL MERGE STATEMENT is the combination of INSERT, UPDATE, and DELETE statement. Merge Statement can perform all these operations in our main target table when the source table is provided. MERGE is very useful when it comes to loading the data warehouse tables, which can be […]

The post SQL Merge Statement Tutorial With Example | Merge In SQL appeared first on AppDividend.

]]>
SQL Merge Statement Tutorial With Example | Merge In SQL

SQL Merge Statement Tutorial With Example is today’s topic. SQL MERGE STATEMENT is the combination of INSERT, UPDATE, and DELETE statement. Merge Statement can perform all these operations in our main target table when the source table is provided. MERGE is very useful when it comes to loading the data warehouse tables, which can be very large and require the specific actions to be taken when the rows are or are not present.

SQL Merge Statement

The syntax is following.

MERGE <target_table> [AS TARGET]
USING <table_source> [AS SOURCE]
ON <search_condition>
[WHEN MATCHED 
THEN <merge_matched> ]
[WHEN NOT MATCHED [BY TARGET]
THEN <merge_not_matched> ]
[WHEN NOT MATCHED BY SOURCE
THEN <merge_matched> ];

#How to use SQL MERGE STATEMENT

  1. Identify the target table which is going to be used in that logic.
  2. Next step is to identify the source table which we can use in the logic.
  3. Next step is to determine the appropriate search conditions in the ON clause to match the rows.
  4. Implement logic when records are matched or not matched between the target and source.
  5. For each of this comparison, conditions write the logic, and When matched, generally an update condition is used and When not matched, then insert or delete statement is used.

Let’s Clear this by seeing an example:

Consider Table Products: (This will be considered as Target Table).

ID NAME PRICE
101 Tea 5.00
201 Chips 10.00
301 Coffee 15.00

Updated_Products: (This will be Considered as SOURCE Table).

ID NAME PRICE
101 Tea 5.00
201 Biscuits 20.00
301 Coffee 25.00

 

#QUERY

MERGE PRODUCTS AS TARGET
USING UPDATED_PRODUCTS AS SOURCE
ON (TARGET.ID=SOURCE.ID)
THEN MATCHED AND TARGET.NAME SOUCE.NAME
OR TARGET.PRICE SOURCE.PRICE THEN
UPDATE SET TARGET.NAME=SOURCE.NAME,
TARGET.PRICE=SOURCE.PRICE
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, NAME, PRICE)
VALUES (SOURCE.ID, SOURCE.NAME, SOURCE.PRICE)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;

#Output

So, after running the above query Products table will be replaced by the Updated_products table.

You can see the table below.

ID NAME PRICE
101 Tea 5.00
201 Biscuits 20.00
301 Coffee 25.00

 

So, in this way, we can perform all three operations together using MERGE clause.

NOTE:

We can use any name other than source and target we have used these names to give you a better explanation.

#Some basic Key Points

  1. The MERGE SQL statement requires the semicolon (;) as a statement terminator Otherwise Error 10713 will be raised.
  2. At least one of three MATCHED clauses must be specified when we are using the MERGE statement.
  3. The user using the MERGE statement should have SELECT permission on the SOURCE table and INSERT, UPDATE and DELETE permissions on a TARGET table.
  4. While inserting, deleting or updating using merge statement in SQL Server fires any corresponding AFTER triggers defined on that target table, but it does not guarantee which action to fire triggers first or last.

Finally, SQL Merge Tutorial With Example is over.

The post SQL Merge Statement Tutorial With Example | Merge In SQL appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/11/sql-merge-statement-tutorial-with-example-merge-in-sql/feed/ 0
How To Add Comments in SQL Query Tutorial With Example https://appdividend.com/2019/07/10/how-to-add-comments-in-sql-query-tutorial-with-example/ https://appdividend.com/2019/07/10/how-to-add-comments-in-sql-query-tutorial-with-example/#respond Wed, 10 Jul 2019 09:11:46 +0000 http://localhost/wordpress/?p=9536 How To Add Comments in SQL Query Tutorial With Example

How To Add Comments in SQL Query Tutorial With Example is today’s topic. Comments are used to explain the sections of SQL statements, or to prevent the execution of SQL statements. Comments are not supported in the Microsoft Access databases. Mozilla Firefox and Microsoft Edge are using Microsoft Access database in our examples. How To […]

The post How To Add Comments in SQL Query Tutorial With Example appeared first on AppDividend.

]]>
How To Add Comments in SQL Query Tutorial With Example

How To Add Comments in SQL Query Tutorial With Example is today’s topic. Comments are used to explain the sections of SQL statements, or to prevent the execution of SQL statements. Comments are not supported in the Microsoft Access databases. Mozilla Firefox and Microsoft Edge are using Microsoft Access database in our examples.

How To Add Comments in SQL

In SQL, you can comment the code just like any other language. Comments can appear on the single line or span across the multiple lines. Let’s explore how to comment on your SQL statements.

Comments can be written in the following formats:

  1. Single line comments.
  2. Multi-line comments
  3. Inline comments

#Syntax

#Syntax Using — Symbol

The syntax for creating the comment in SQL using — symbol is the following.

-- comment goes here

Any text between — and the end of the line will be ignored (will not be executed).

The comment started with  symbol must be at the end of the line in your SQL statement with the line break after it. The above method of commenting can only span the single line within your SQL and must be at the end of the line.

See the following example. If you do not know how to create a table, then check out the article on how to create a table in MySQL.

-- fetch the records staring from LV
SELECT * FROM Products
WHERE ProductName LIKE 'LV%'

See the following output.

 

How To Add Comments in SQL Query Tutorial

#Multi-line Comments OR Syntax Using /* and */ symbols

See the following query.

/*Select all the columns
of all the records
in the Products table:*/

SELECT * FROM Products

See the output.

 

Multi-line Comments

If we want to ignore just the part of the statement, also use a /* */ comment.

See the following example which uses a comment to ignore part of the line.

SELECT ProductName, /*ProductCategory,*/ ProductPrice
FROM Products

See the following output.

Add Comments in SQL
Finally,  How To Add Comments in SQL Query Tutorial With Example is over.

The post How To Add Comments in SQL Query Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/10/how-to-add-comments-in-sql-query-tutorial-with-example/feed/ 0
SQL Constraints Tutorial With Example | Understand SQL Constraints https://appdividend.com/2019/07/09/sql-constraints-tutorial-with-example-understand-sql-constraints/ https://appdividend.com/2019/07/09/sql-constraints-tutorial-with-example-understand-sql-constraints/#respond Tue, 09 Jul 2019 07:01:06 +0000 http://localhost/wordpress/?p=9459 SQL Constraints Tutorial With Example | Understand SQL Constraints

SQL Constraints Tutorial With Example | Understand SQL Constraints is today’s topic. SQL Constraints are rules used to limit a type of data that can go into the table, to maintain the accuracy and the integrity of a data inside the table. Constraints can be divided into the following two types, Column level constraints: Limits only […]

The post SQL Constraints Tutorial With Example | Understand SQL Constraints appeared first on AppDividend.

]]>
SQL Constraints Tutorial With Example | Understand SQL Constraints

SQL Constraints Tutorial With Example | Understand SQL Constraints is today’s topic. SQL Constraints are rules used to limit a type of data that can go into the table, to maintain the accuracy and the integrity of a data inside the table. Constraints can be divided into the following two types,

  1. Column level constraints: Limits only the column data.
  2. Table-level constraints: Limits whole table data.

SQL Constraints

Constraints are the set of rules enforced on the data columns of the table. These are used to limit the type of data that can go into the table. It ensures the accuracy, integrity, and reliability of the data in the SQL database.

Constraints in SQL are used to make sure that an integrity of the data is maintained in the database.

See the following most used constraints that can be applied to the table.

  1. NOT NULL
  2. UNIQUE
  3. PRIMARY KEY
  4. FOREIGN KEY
  5. CHECK
  6. DEFAULT

#NOT NULL Constraint in SQL

NOT NULL constraint restricts the column from having the NULL value. Once a NOT NULL constraint is applied to the column, you cannot pass the null value to that column. It enforces the column to contain a proper value. Empty will should not be there in that column for every table.

Generally, the ID column in the SQL Table contains the NOT NULL constraint.

See the following query of NOT NULL constraint.

CREATE TABLE Singer (
 id int NOT NULL, 
 Name varchar(60) NOT NULL, 
 Song varchar(60)
);

The above query will declare that an id and Name field of the Singer table will not take NULL value.

#PRIMARY KEY Constraint

We have covered Primary Key in this blog. The primary key is a field in the table which is used for uniquely identifying the row in the table. If the column has a primary key constraint, then it will contain the unique values and will not able to hold any NULL values.

The following SQL statement creates the table named investors and specifies an id column as a primary key. That means id field does not allow the NULL or duplicate values.

CREATE TABLE investors (
    id INT NOT NULL PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    portfolio amount INT,
    fund_name VARCHAR(50)
);

In the above query, we will create the investors’ table in which id column is the primary key. You can not add NULL value in the Primary Key column. So, id column has now two SQL Constraints. One point to remember that a primary key length cannot exceed more than 900 bytes.

#UNIQUE Constraint

UNIQUE constraint ensures that a field or the column will only have unique values. The UNIQUE constraint field will not have any duplicate data. The unique constraint can be applied at the column level or the table level.

The UNIQUE Constraint prevents two records from having identical values in a column.

#UNIQUE constraint in Table-level

Here we have the simple CREATE query to create the table, which will have the column app_id with unique values. See the following query.

CREATE TABLE Apps(
  app_id int NOT NULL UNIQUE, 
  Name varchar(60), 
  Price int
);

#UNIQUE constraint in Column-level

Here, we have to use the Alter table query to assign the Unique constraint to a particular field.

See the following query.

ALTER TABLE Apps ADD UNIQUE(app_id);

The above query specifies that the app_id field of Apps table will only have a unique value.

#Foreign Key Constraint

We have also covered the Foreign Key constraint here in this blog. SQL foreign key is used to form a link between two tables, which makes it a referencing key. FOREIGN KEY is used to relate the two tables. The FOREIGN KEY constraint is also used to restrict the actions that would destroy the links between tables. Let’s see its use, with the help of the two tables.

Investors

i_id investor_Name address
101 KRUNAL Noida
102 ANKIT Delhi
103 RUSHABH Rohtak

Employees

e_id employee_age i_id
10 26 101
11 24 103
12 26 102

In the above, there are two tables.

  1. Investors
  2. Employees

Now, the above two tables are connected through the Foreign key called i_id.

Investors table has a primary key called i_id and Employees table has a foreign key called i_id.

If you try to insert incorrect data, the DBMS will return the error and will not allow you to insert any data.

So, it will prevent to add any malicious values are manipulative values. You need to be really very careful when editing, updating, or deleting the data between those tables.

If it goes wrong, then the entire system will behave unnaturally and buggy.

#Using FOREIGN KEY constraint at Table Level

See the following query.

CREATE table Employees(
    e_id int PRIMARY KEY, 
    employee_age varchar(60) NOT NULL,
    i_id int FOREIGN KEY REFERENCES Investors(i_id)
);

So, in the above query, we have defined the relationship between the tables using i_id.

The i_id column in the Employees table reference from Investors tables.

#Using FOREIGN KEY constraint at Column Level

See the following query.

ALTER table Employees 
ADD FOREIGN KEY (i_id) REFERENCES Investors(i_id);

Here, we have used Alter query to add the Foreign Key constraint to the Employees table.

#Behaviour of Foreign Key Column on Delete

There are two ways to maintain the integrity of data in the Child table when the particular record is removed from the main table. When the two tables are connected through Foreign key, and certain data in the main table is removed, for which the record exists in a child table, then we must have some kind of mechanism to save that integrity of the data in the child table.

    1. On Delete Cascade: It will remove a record from a child table if that value of a foreign key is deleted from a main table.
    2. On Delete Null: It will set all the values in that record of the child, the table as NULL, for which a value of a foreign key is deleted from a main table.
    3. If we don’t use any of the above, then we cannot delete the data from a main table for which the data in child table exists. We will get an error if we try to do so.
ERROR : Record in child table exist

#Check Constraint

CHECK constraint is used to restrict a value of the column between the range.

It performs check on the values, before storing them into the database. Its like condition was checking before saving data into the column.

#Using CHECK constraint at Table Level

CREATE table Student(
    id int NOT NULL CHECK(id > 0),
    Name varchar(60) NOT NULL,
    Age int
);

The above query will restrict the id value to be higher than zero.

#Using CHECK constraint at Column Level

See the following query.

ALTER table Student ADD CHECK(id > 0);

#DEFAULT Constraint

The DEFAULT constraint provides the default value to a column when the INSERT INTO statement does not provide the specific value.

#Using DEFAULT constraint at Table Level

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

#Using DEFAULT constraint at Column Level

If the table has been created already, then, we can use the Alter table statement to assign the default constraint. See the following query.

ALTER TABLE CUSTOMERS
ALTER SALARY SET DEFAULT 100000;

Finally, SQL Constraints Tutorial With Example | Understand SQL Constraints is over.

The post SQL Constraints Tutorial With Example | Understand SQL Constraints appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/09/sql-constraints-tutorial-with-example-understand-sql-constraints/feed/ 0
SQL Operators Tutorial With Example From Scratch https://appdividend.com/2019/07/09/sql-operators-tutorial-with-example-from-scratch/ https://appdividend.com/2019/07/09/sql-operators-tutorial-with-example-from-scratch/#respond Tue, 09 Jul 2019 04:49:19 +0000 http://localhost/wordpress/?p=9451 SQL Operators Tutorial With Example From Scratch

SQL Operators Tutorial With Example From Scratch is today’s topic. SQL operator is the reserved word or a character used primarily in the SQL statement’s WHERE clause to operate (s), such as comparisons and arithmetic operations. These reserved characters or words are known as the operators in SQL. These Operators are used to specify the […]

The post SQL Operators Tutorial With Example From Scratch appeared first on AppDividend.

]]>
SQL Operators Tutorial With Example From Scratch

SQL Operators Tutorial With Example From Scratch is today’s topic. SQL operator is the reserved word or a character used primarily in the SQL statement’s WHERE clause to operate (s), such as comparisons and arithmetic operations. These reserved characters or words are known as the operators in SQL. These Operators are used to specify the conditions in the SQL statement and to serve as the conjunctions for multiple conditions in the statement. We have covered SQL Datatypes in our blog. Please check out that as well.

SQL Operators

There are three types of Operators in SQL.

  1. Arithmetic operators
  2. Comparison operators
  3. Logical operators

#SQL Arithmetic Operators

SQL Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division, and modulus in SQL statements.

See the following arithmetic operators.

Operators Descriptions Example
+ (Addition) The + operator is used to add containing values of both operands x + y will give 11
– (Subtraction) The – operator subtracts right-hand operand from the left-hand operand x – y- will give -11
* (Multiplication) The * operator multiplies both operand’s values x * y will give 1100
/ (Division) The / operator divides left-hand operand by right-hand operand x / y will give 11
% (Modulo) The modulo operator divides left-hand operand by right-hand operand and returns reminder x % y will give 0

 

#SQL Comparison Operators

Comparison operators in SQL are used to find a relation between the two columns. For example, if we want to compare the values of two columns in SQL statements.

See the following table of Comparison Operators in SQL.

Operator Description Example
= The = operator checks if the values of the two operands are equal or not, if yes then a condition becomes true. (a = b) is not true.
!= The != operator checks if the values of a two operands are equal or not if the values are not equal, then that condition becomes true. (a != b) is true.
<> The <> operator checks if the values of two operands are equal or not, if the values are not equal, then condition becomes true. (a <> b) is true.
> The > operator checks if the value of the left operand is greater than a value of the right operand, if yes then that condition becomes true. (a > b) is not true.
< The < operator checks if the value of a left operand is less than a value of the right operand, if yes then that condition becomes true. (a < b) is true.
>= The >= operator checks if a value of the left operand is greater than or equal to a value of the right operand, if yes then the condition becomes true. (a >= b) is not true.
<= The <= operator checks if a value of the left operand is less than or equal to a value of the right operand, if yes then the condition becomes true. (a <= b) is true.
!< The !< operator checks if a value of the left operand is not less than a value of the right operand, if yes then condition becomes true. (a !< b) is false.
!> The !> operator checks if a value of the left operand is not greater than a value of the right operand, if yes then condition becomes true. (a !> b) is true.

#SQL Logical Operators

Logical operators in the SQL are used to perform the logical operations on the given expressions in SQL. There are many operators in the SQL which are used in the SQL statements in the WHERE clause.

See the following Logical Operator in SQL.

Operators Descriptions
ALL The + operator is used to add the containing values of both the operands.
AND The – operator subtracts a right-hand operand from the left-hand operand.
ANY The * operator multiplies both of the operand’s values.
BETWEEN The / operator divides the left-hand operand by right-hand operand.
IN The modulo operator divides a left-hand operand by right-hand operand and returns reminder.
NOT The NOT operator reverses a meaning of the logical operator with which it is used. E.g., NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is the negate an operator.
OR The OR operator is used to combine the multiple conditions in an SQL statement’s WHERE clause.
EXISTS The EXISTS operator is used to search for a presence of the row in the specified table that meets specific criteria.
LIKE The LIKE operator is used to compare the value to similar values using wildcard operators.

 

Finally, SQL Operators Tutorial With Example From Scratch is over.

The post SQL Operators Tutorial With Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/09/sql-operators-tutorial-with-example-from-scratch/feed/ 0
SQL Except Clause Example | Except Statement In SQL https://appdividend.com/2019/07/05/sql-except-clause-example-except-statement-in-sql/ https://appdividend.com/2019/07/05/sql-except-clause-example-except-statement-in-sql/#respond Fri, 05 Jul 2019 11:42:37 +0000 http://localhost/wordpress/?p=9374 SQL Except Clause Example

SQL Except Clause Example | Except Statement In SQL is today’s topic. The SQL EXCEPT operator is used to combine two select statements, which in turn returns the row that is present in the first select statement and not in the second select statement. This Clause acts like a subtract operation that we perform in […]

The post SQL Except Clause Example | Except Statement In SQL appeared first on AppDividend.

]]>
SQL Except Clause Example

SQL Except Clause Example | Except Statement In SQL is today’s topic. The SQL EXCEPT operator is used to combine two select statements, which in turn returns the row that is present in the first select statement and not in the second select statement. This Clause acts like a subtract operation that we perform in sets and Venn diagrams.

SQL Except Clause Example

In SQL, EXCEPT returns those tuples that are returned by the first SELECT operation, and not returned by the second SELECT operation.

#Pictorial Representation

 

SQL Except Clause

From above you can see that no common records will be displayed between two queries i.e., only Query1 will return all its rows.

 Each Select statement within an EXCEPT query must have the same number of fields in the result sets having similar data types.

#Syntax

Select column(s) from table_name1 where(condition)
EXCEPT
Select column(s) from table_name2 where(condition).

#PARAMETERS

  1. Column(s) represents the name of the columns.
  2. Table_name1 and Table_name2 are the names of the tables.
  3. Where(condition) is the condition to be imposed on select statements.
  4. EXCEPT is the operator who acts like a minus operator on select statements.

Let’s clear the above operations with examples.

Consider Tables: (Students) and (Course)

STUDENTS:

Roll Name City
1 Rohit Patna
2 Shouvik Jalandhar
3 Shubh Kolkata
4 Karan Allahabad
5 Shivam Palampur
6 Karan Dhulian

 

Course:

Name Course
Shubh Data Science
Rohit Data Science
Shivam Android Development

 

#QUERY

Select name from Students
Except
Select name from Course;

#OUTPUT

NAME
Shouvik
Karan

 

#EXPLANATION

In the above query name of students were declared who have not registered for any of the courses. So, Shouvik and Karan were displayed in the resulting set because they had not logged in any of the courses.

NOTE:

You can see that in the above query Karan was displayed only one time. So, to retain duplicates, we have to use EXCEPTALL clause.

The corresponding columns in the each of the SELECT statements must have similar data types.

The EXCEPT operator returns all records from the first SELECT statement that are not in the second SELECT statement.

See the following query.

Select name from Students
EXCEPTALL
Select name from Course

#OUTPUT

NAME
Shouvik
Karan
Karan

 

So, you can see that Karan has been displayed twice.

#DIFFERENCE BETWEEN EXCEPT AND NOT IN CLAUSE

Except clause removes duplicates from the resulting set whereas NOT IN clause does not remove duplicates from the resulting set.

NOTE:

MySQL does not support EXCEPT CLAUSE. So, it is better to use in SQL SERVER.

Finally, SQL Except Clause Example | Except Statement In SQL is over.

The post SQL Except Clause Example | Except Statement In SQL appeared first on AppDividend.

]]>
https://appdividend.com/2019/07/05/sql-except-clause-example-except-statement-in-sql/feed/ 0
SQL PRIMARY KEY Tutorial With Example | Primary Key in SQL https://appdividend.com/2019/06/27/sql-primary-key-tutorial-with-example-primary-key-in-sql/ https://appdividend.com/2019/06/27/sql-primary-key-tutorial-with-example-primary-key-in-sql/#respond Thu, 27 Jun 2019 11:24:43 +0000 http://localhost/wordpress/?p=9027 SQL PRIMARY KEY Tutorial With Example | Primary Key in SQL

SQL PRIMARY KEY Tutorial With Example | Primary Key in SQL is today’s topic. A primary key is a field in a table which is used for uniquely identifying a row in a table. If a column has a primary key constraint, then it will contain unique values and will not able to contain any […]

The post SQL PRIMARY KEY Tutorial With Example | Primary Key in SQL appeared first on AppDividend.

]]>
SQL PRIMARY KEY Tutorial With Example | Primary Key in SQL

SQL PRIMARY KEY Tutorial With Example | Primary Key in SQL is today’s topic. A primary key is a field in a table which is used for uniquely identifying a row in a table. If a column has a primary key constraint, then it will contain unique values and will not able to contain any NULL values. A primary key length cannot exceed more than 900 bytes.

SQL PRIMARY KEY

A PRIMARY KEY constraint uniquely identifies each row in the table. Primary keys must contain UNIQUE values, and cannot contain the NULL values. The table can have only ONE primary key; and in the table, that primary key can consist of the single or multiple columns (fields).

A table will contain only one primary key, which may consist of single or multiple fields, and when multiple fields are used as a primary key, then it is known as composite keys.

If the table has a primary key defined in any of the fields, then it cannot have two or more records having the same values.

#SQL Composite Key

When the multiple fields are used as the Primary Key, they are called a composite key.

#Key Points for Primary Key

  1. Primary key enforces an entity integrity of the table.
  2. The primary key always has a unique data.
  3. The primary key length cannot be exceeded than 900 bytes.
  4. The primary key cannot have a null value.
  5. There must be no duplicate value for a primary key.
  6. The table can contain only one primary key constraint.

If a table has the primary key defined on any field(s), then you cannot have the two records having the same value of that field(s). There are the following ways to create a primary key:

  1. Using create statement.
  2. Using an alter statement.

#Create Primary Key Using CREATE TABLE

See the following syntax.

#Adding primary key after the name of the column.

Create table table_name
( 
column1 datatype [NULL|NOT NULL], [PRIMARY KEY],
column2 datatype [NULL|NOT NULL], [PRIMARY KEY],
…………………….
Column(n) datatype [NULL|NOT NULL]);

#Using Constraint names

CREATE TABLE table_name
(
Column1 datatype [NULL|NOT NULL],
Column2 datatype [NULL|NOT NULL],
………….
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, …., column(n));

#NOTE

[NULL|NOT NULL] is optional. If you don’t mention any of these then by default, a column can take NULL values.

LET’S CLEAR THE SYNTAXES USING AN EXAMPLE

Create table employees
(emp_id integer, name varchar(40), salary integer);

Now, after executing this command, a table will be created named employees having emp_id as a primary key. After the creation of the table writes.

Desc employees;

You can see that the emp_id key field will have a text known as PRI, which is known as the PRIMARY KEY. See the following output.

 

SQL PRIMARY KEY Tutorial

Now, see the following query.

create table employees
(emp_id integer, name varchar(40), salary integer, 
CONSTRAINT employees_id 
PRIMARY KEY(emp_id));

Now, after executing this command, a table will be created named employees having emp_id as the primary key.

After the creation of the table, write the following query.

Desc employees;

You can see that the emp_id key field will have a text known as PRI, which is known as the PRIMARY KEY. See the following output.

 

Using Constraint names

Let’s create a composite key, i.e. a primary key having more than one column. See the following query.

create table employees
(emp_id integer, name varchar(40), salary integer, 
CONSTRAINT employees_id PRIMARY KEY(name, salary));

Now, after executing this command, a table will be created named employees having name and salary as the primary key.

After the creation of the table write the following query.

Desc employees;

You can see that name and salary key field will have a text known as PRI, which is known as the PRIMARY KEY. See the following output.

 

SQL PRIMARY KEY Example

#Create PRIMARY KEY Using Alter Statement

See the following syntax.

Alter table table_name ADD primary key(column name);

See the following query.

Alter table employees add primary key(emp_id);

See the following output.

 

Create PRIMARY KEY Using Alter Statement

#Explanation

You can see that at the time of the creation of the table, we had not mentioned any column as the primary key. So, to make a column unique, we had used alter statement.

#Create COMPOSITE KEY Using Alter Statement

See the following syntax.

Alter table table_name 
ADD constraint 
constraint_name primary key(column(s));

See the following query.

alter table employees 
add constraint employees_pri Primary key(Name, salary);

See the output.

 

Create COMPOSITE KEY Using Alter Statement

#Explanation

You can see that at the time of the creation of the table, we had not mentioned any column as a primary key. So, to make column(s) unique, we had used alter statement.

#DELETE A PRIMARY KEY

See the following syntax.

Alter table table_name 
DROP primary key;

Let’s create the table employees with primary key as mentioned above. Then we will delete it.

See the query.

Alter table employees drop primary key;

See the following output.

 

DELETE A PRIMARY KEY

#Disable Primary Key

You can disable the primary key using the ALTER TABLE statement in SQL Server (Transact-SQL).

The syntax to disable the Primary Key using the ALTER INDEX statement in SQL Server (Transact-SQL) is following.

ALTER INDEX constraint_name ON table_name
DISABLE;

Let’s look at the example of how to disable a primary using the ALTER INDEX statement in SQL Server (Transact-SQL).

For example:

ALTER INDEX employees_pk ON employees
DISABLE;

#Enable Primary Key

You can enable the Primary Key using the ALTER INDEX statement in SQL Server (Transact-SQL). See the following syntax.

ALTER INDEX constraint_name ON table_name
REBUILD;

Let’s look at the example of how to enable a primary key using the ALTER INDEX statement in SQL Server.

ALTER INDEX employees_pk ON employees
REBUILD;

Finally, SQL PRIMARY KEY Tutorial With Example is over.

The post SQL PRIMARY KEY Tutorial With Example | Primary Key in SQL appeared first on AppDividend.

]]>
https://appdividend.com/2019/06/27/sql-primary-key-tutorial-with-example-primary-key-in-sql/feed/ 0