It allows us to perform the below-listed functions: Insert data or rows in a database Delete data from the database Retrieve or fetch data Update data in a database.
Basic Syntax: CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE condition; view_name: Name for the View table_name: Name of the table condition: Condition to select rows For more details on how to create and use view, please refer to this article.
Orders O_ID ORDER_NO C_ID 1 2253 3 2 3325 3 3 4521 2 4 8532 1 Customers C_ID NAME ADDRESS 1 RAMESH DELHI 2 SURESH NOIDA 3 DHARMESH GURGAON As we can see clearly, that the field C_ID in the Orders table is the primary key in the Customers’ table, i.e. it uniquely identifies each row in the Customers table. Therefore, it is a Foreign Key in the Orders table. Syntax: CREATE TABLE Orders ( O_ID int NOT NULL, ORDER_NO int NOT NULL, C_ID int, PRIMARY KEY (O_ID), FOREIGN KEY (C_ID) REFERENCES Customers(C_ID) )
Table: A table has a combination of rows and columns. Rows are called records and columns are called fields. In MS SQL Server, the tables are being designated within the database and schema names. Field: In DBMS, a database field can be defined as – a single piece of information from a record.
Minimizing Redundancy Minimizing the Insertion, Deletion, And Update Anomalies Relation schemas that do not meet the properties are decomposed into smaller relation schemas that could meet desirable properties.
Denormalization is a database optimization technique in which we add redundant data to one or more tables. This can help us avoid costly joins in a relational database. Note that denormalization does not mean not doing normalization. It is an optimization technique that is applied after normalization. In a traditional normalized database, we store data in separate logical tables and attempt to minimize redundant data. We may strive to have only one copy of each piece of data in the database.
An SQL query is used to retrieve the required data from the database. However, there may be multiple SQL queries that yield the same results but with different levels of efficiency. An inefficient query can drain the database resources, reduce the database speed or result in a loss of service for other users. So it is very important to optimize the query to obtain the best database performance.
There are three operators available in SQL namely: Arithmetic Operators Logical Operators Comparison Operators
We can use User-defined functions in PL/SQL or Java to provide functionality that is not available in SQL or SQL built-in functions. SQL functions and User-defined functions can appear anywhere, that is, wherever an expression occurs. For example, it can be used in: Select a list of SELECT statements. Condition of the WHERE clause. CONNECT BY, ORDER BY, START WITH, and GROUP BY The VALUES clause of the INSERT statement. The SET clause of the UPDATE statement.
User-Defined Functions allow people to define their own T-SQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type. Different Kinds of User-Defined Functions created are: 1. Scalar User-Defined Function A Scalar user-defined function returns one of the scalar data types. Text, image, and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value. 2. Inline Table-Value User-Defined Function An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and, in essence, provide us with a parameterized, non-updateable view of the underlying tables. 3. Multi-statement Table-Value User-Defined Function A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view, as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a TSQL select command or a group of them gives us the capability to, in essence, create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, it can be used in the FROM clause of a T-SQL command, unlike the behavior found when using a stored procedure which can also return record sets.
Stored Procedures are created to perform one or more DML operations on databases. It is nothing but a group of SQL statements that accepts some input in the form of parameters and performs some task and may or may not return a value. For more details please refer to our Stored procedures in the SQL article.
For doing operations on data SQL has many built-in functions, they are categorized into two categories and further sub-categorized into seven different functions under each category. The categories are: Aggregate functions: These functions are used to do operations from the values of the column and a single value is returned. Scalar functions: These functions are based on user input, these too return a single value. For more details, please read the SQL | Functions (Aggregate and Scalar Functions) article.
Aliases are the temporary names given to a table or column for the purpose of a particular SQL query. It is used when the name of a column or table is used other than its original name, but the modified name is only temporary. Aliases are created to make table or column names more readable. The renaming is just a temporary change and the table name does not change in the original database. Aliases are useful when table or column names are big or not very readable. These are preferred when there is more than one table involved in a query. For more details, please read the SQL | Aliases article.
Set Operations in SQL eliminate duplicate tuples and can be applied only to the relations which are union compatible. Set Operations available in SQL are : Set Union Set Intersection Set Difference UNION Operation: This operation includes all the tuples which are present in either of the relations. For example: To find all the customers who have a loan or an account or both in a bank. SELECT CustomerName FROM Depositor UNION SELECT CustomerName FROM Borrower ; The union operation automatically eliminates duplicates. If all the duplicates are supposed to be retained, UNION ALL is used in place of UNION. INTERSECT Operation: This operation includes the tuples which are present in both of the relations. For example: To find the customers who have a loan as well as an account in the bank: SELECT CustomerName FROM Depositor INTERSECT SELECT CustomerName FROM Borrower ; The Intersect operation automatically eliminates duplicates. If all the duplicates are supposed to be retained, INTERSECT ALL is used in place of INTERSECT. EXCEPT for Operation: This operation includes tuples that are present in one relationship but should not be present in another relationship. For example: To find customers who have an account but no loan at the bank: SELECT CustomerName FROM Depositor EXCEPT SELECT CustomerName FROM Borrower ; The Except operation automatically eliminates the duplicates. If all the duplicates are supposed to be retained, EXCEPT ALL is used in place of EXCEPT.
T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has huge importance since all the communications with an instance of an SQL server are done by sending Transact-SQL statements to the server. Users can also define functions using T-SQL. Types of T-SQL functions are : Aggregate functions. Ranking functions. There are different types of ranking functions. Rowset function. Scalar functions.
ETL is a process in Data Warehousing and it stands for Extract, Transform, and Load. It is a process in which an ETL tool extracts the data from various data source systems, transforms it in the staging area, and then finally, loads it into the Data Warehouse system. These are three database functions that are incorporated into one tool to pull data out from one database and put data into another database.
Sometimes, in SQL, we need to create an exact copy of an already defined (or created) table. MySQL enables you to perform this operation. Because we may need such duplicate tables for testing the data without having any impact on the original table and the data stored in it. CREATE TABLE Contact List(Clone_1) LIKE Original_table; For more details, Please read Cloning Table in the MySQL article.
SQL injection is a technique used to exploit user data through web page inputs by injecting SQL commands as statements. Basically, these statements can be used to manipulate the application’s web server by malicious users. SQL injection is a code injection technique that might destroy your database. SQL injection is one of the most common web hacking techniques. SQL injection is the placement of malicious code in SQL statements, via web page input. For more details, please read the SQL | Injection article.
Yes, we can disable a trigger in PL/SQL. If consider temporarily disabling a trigger and one of the following conditions is true: An object that the trigger references is not available. We must perform a large data load and want it to proceed quickly without firing triggers. We are loading data into the table to which the trigger applies. We disable a trigger using the ALTER TRIGGER statement with the DISABLE option. We can disable all triggers associated with a table at the same time using the ALTER TABLE statement with the DISABLE ALL TRIGGERS option.
Some common differences between SQL and PL/SQL are as shown below: SQL PL/SQL SQL is a query execution or commanding language PL/SQL is a complete programming language SQL is a data-oriented language. PL/SQL is a procedural language SQL is very declarative in nature. PL/SQL has a procedural nature. It is used for manipulating data. It is used for creating applications. We can execute one statement at a time in SQL We can execute blocks of statements in PL/SQL SQL tells databases, what to do? PL/SQL tells databases how to do. We can embed SQL in PL/SQL We can not embed PL/SQL in SQL
BETWEEN: The BETWEEN operator is used to fetch rows based on a range of values. For example, SELECT * FROM Students WHERE ROLL_NO BETWEEN 20 AND 30; This query will select all those rows from the table. Students where the value of the field ROLL_NO lies between 20 and 30. IN: The IN operator is used to check for values contained in specific sets. For example, SELECT * FROM Students WHERE ROLL_NO IN (20,21,23); This query will select all those rows from the table Students where the value of the field ROLL_NO is either 20 or 21 or 23.
The LIKE operator of SQL is used for this purpose. It is used to fetch filtered data by searching for a particular pattern in the where clause. The Syntax for using LIKE is, SELECT column1,column2 FROM table_name WHERE column_name LIKE pattern; LIKE: operator name pattern: exact value extracted from the pattern to get related data in result set. The required query is: SELECT * FROM Employees WHERE EmpName like 'A%' ; You may refer to this article WHERE clause for more details on the LIKE operator.
The primary key cannot have NULL values, the unique constraints can have NULL values. There is only one primary key in a table, but there can be multiple unique constraints. The primary key creates the clustered index automatically but the unique key does not.
An SQL Join statement is used to combine data or rows from two or more tables based on a common field between them. Different types of Joins are: INNER JOIN: The INNER JOIN keyword selects all rows from both tables as long as the condition is satisfied. This keyword will create the result set by combining all rows from both the tables where the condition satisfies i.e. the value of the common field will be the same. LEFT JOIN: This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of the join. For the rows for which there is no matching row on the right side, the result set will be null. LEFT JOIN is also known as LEFT OUTER JOIN RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of the join. For the rows for which there is no matching row on the left side, the result set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN. FULL JOIN: FULL JOIN creates the result set by combining the results of both LEFT JOIN and RIGHT JOIN. The result set will contain all the rows from both tables. For the rows for which there is no matching, the result set will contain NULL values.
A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of data. Data can be stored only in one order on a disk. To support faster access according to different values, a faster search like a binary search for different values is desired. For this purpose, indexes are created on tables. These indexes need extra space on the disk, but they allow faster search according to different frequently searched values.
An ‘ON DELETE CASCADE’ constraint is used in MySQL to delete the rows from the child table automatically when the rows from the parent table are deleted. For more details, please read MySQL – On Delete Cascade constraint article.
The WITH clause provides a way relationship of defining a temporary relationship whose definition is available only to the query in which the with clause occurs. SQL applies predicates in the WITH clause after groups have been formed, so aggregate functions may be used.
The indexing has various attributes: Access Types: This refers to the type of access such as value-based search, range access, etc. Access Time: It refers to the time needed to find a particular data element or set of elements. Insertion Time: It refers to the time taken to find the appropriate space and insert new data. Deletion Time: Time is taken to find an item and delete it as well as update the index structure. Space Overhead: It refers to the additional space required by the index.
The cursor is a Temporary Memory or Temporary Work Station. It is Allocated by Database Server at the Time of Performing DML operations on the Table by the User. Cursors are used to store Database Tables.
There are various relationships, namely: One-to-One Relationship. One to Many Relationships. Many to One Relationship. Self-Referencing Relationship.
The trigger is a statement that a system executes automatically when there is any modification to the database. In a trigger, we first specify when the trigger is to be executed and then the action to be performed when the trigger executes. Triggers are used to specify certain integrity constraints and referential constraints that cannot be specified using the constraint mechanism of SQL.
SQL DELETE SQL TRUNCATE The DELETE statement removes rows one at a time and records TRUNCATE TABLE removes the data by deallocating the data pages used to store an entry in the transaction log for each deleted row. the table data and records only the page deallocations in the transaction log. DELETE command is slower than the identityTRUNCATE command. While the TRUNCATE command is faster than the DELETE command. To use Delete you need DELETE permission on the table. To use Truncate on a table we need at least ALTER permission on the table. The identity of the column retains the identity after using The identity of the column is reset to its seed value if the table contains an identity column. DELETE Statement on the table. The delete can be used with indexed views. Truncate cannot be used with indexed views.
CLUSTERED INDEX NON-CLUSTERED INDEX The clustered index is faster. The non-clustered index is slower. The clustered index requires less memory for operations. The non-Clustered index requires more memory for operations. In a clustered index, the index is the main data. In the Non-Clustered index, the index is a copy of data. A table can have only one clustered index. A table can have multiple non-clustered indexes. The clustered index has an inherent ability to store The non-Clustered index does not have the inherent ability to store data on the disk. data on the disk. Clustered indexes store pointers to block not data. The non-Clustered index store both value and a pointer to the the the actual row that holds data. In Clustered index leaf nodes are actual data itself. In a Non-Clustered index, leaf nodes are not the actual data itself rather they only contain included columns. In the Clustered index, the Clustered key defines In the Non-Clustered index, the index key defines the order of data within the index the order of data within the table. . A Clustered index is a type of index in which table A Non-Clustered index is a special type of index in which the logical order of index does not match the physical stored order of the rows on the disk. records are physically reordered to match the index.
Livelock occurs when two or more processes continually repeat the same interaction in response to changes in the other processes without doing any useful work. These processes are not in the waiting state, and they are running concurrently. This is different from a deadlock because in a deadlock all processes are in the waiting state.
Control statements form an important part of most languages since they control the execution of other sets of statements. These are found in SQL too and should be exploited for uses such as query filtering and query optimization through careful selection of tuples that match our requirements. In this post, we explore the Case-Switch statement in SQL. The CASE statement is SQL’s way of handling if/then logic. syntax: 1 CASE case_value WHEN when_value THEN statement_list [WHEN when_value THEN statement_list] … [ELSE statement_list]END CASE syntax: 2 CASE WHEN search_condition THEN statement_list [WHEN search_condition THEN statement_list] … [ELSE statement_list]END CASE For more details, please read the SQL | Case Statement article.
There are three types of case manipulation functions available in SQL. They are, LOWER: The purpose of this function is to return the string in lowercase. It takes a string as an argument and returns the string by converting it into lower case. Syntax: LOWER(‘string’) UPPER: The purpose of this function is to return the string in uppercase. It takes a string as an argument and returns the string by converting it into uppercase. Syntax: UPPER(‘string’) INITCAP: The purpose of this function is to return the string with the first letter in uppercase and the rest of the letters in lowercase. Syntax: INITCAP(‘string’)
In contrast, global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters. Local Variable: Local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them. .
In SQL the spaces at the end of the string are removed by a trim function. Syntax: Trim(s) Where s is a any string.