Transact SQL Statements can be classified into DDL, DML, and DCL Statements and in terms of Computer Programming, DML statements can be referred to as CRUD operations. In this article, we can see in more detail the CRUD operations and how we can use those statements in SQL Server with examples.
CRUD Operations:
CRUD is an acronym for CREATE, READ(SELECT), UPDATE, and DELETE statements in SQL Server. CRUD in database terms can be mentioned as Data Manipulation Language (DML) Statements as well. Data Manipulation Language is used to manage or manipulate the data present inside database Tables. Even though CRUD operations are supported on Database object View, Views have several restrictions and hence in this article, we can test the CRUD operations on Tables. Before diving into the individual CRUD Operations or DML Statements in more detail, we can create a table named Employee in the geek's database to test our various CRUD operation-related queries.
Let's first create a database named geeks using the below command in SQL Server Management Studio by opening a new query window:
Query:
CREATE DATABASE geeks;
Output:
In Query Window, connect to the geek's database just created using the below command.
Query:
USE geeks
Now, create a test table named Employee using the below command.
Query:
CREATE TABLE Employee (EMPId Int Identity NOT NULL,
EmpNo varchar (10), SSN varchar (10), DOB DATE,
CreatedDt Datetime, CreatedBy varchar(10));
CREATE:
CREATE often refers to the INSERT statement which is used to insert new data to any of the SQL Server tables. To INSERT records into a table, we need to use the INSERT command and the syntax for the INSERT command would be:
Query:
INSERT INTO TABLE_NAME (COLUMNS_NAMES_LIST)
VALUES (COLUMNS_VALUES_LIST);
In the above INSERT command syntax, we need to specify the Table Name along with the list of Column Names and a few things to note:
- The list of Column names provided should match the order of the Column values provided.
- The list of Column names specified need not match with the order of the Column names available in the Table.
- If the Columns names list includes the Identity Columns, then we need to specify the SET IDENTITY_INSERT option set to ON before trying to insert values for Identity columns.
- For string and date datatype columns, we need to specify the values within Single quotes.
- In the INSERT command, the Column names list need not be mandatorily specified, however, if not specified, then the values should be specified in the order the columns are available in the table.
Now, let’s try to INSERT some values into the Employee table created above with various possible scenarios as listed below. Default scenarios specifying values in the order columns are present excluding the Identity Datatype column EmpId.
Query:
INSERT INTO Employee (EmpNO, SSN, DOB, CreatedDt, CreatedBy)
VALUES (1,'1234567890','2000-01-01', GETDATE(), 'system');
Output:
Let’s try Inserting records into the table in a different column order with EmpNo at the end as shown below.
Query:
INSERT INTO Employee (SSN, DOB, CreatedDt, CreatedBy, EmpNO)
VALUES ('0123456789','1999-01-01', GETDATE(), 'system', 2);
Output:
To insert records into the table for the Identity datatype column, we need to use the SET IDENTITY_INSERT option as shown below:
Query:
SET IDENTITY_INSERT Employee ON;
INSERT INTO Employee (EmpId, SSN, DOB, CreatedDt, CreatedBy, EmpNO)
VALUES (3, '0123456789','1999-01-01', GETDATE(), 'system', 2);
SET IDENTITY_INSERT Employee OFF;
Output:
To Insert Multiple values into the Employee column with a single INSERT statement, we need to use the below syntax:
Query:
INSERT INTO Employee (EmpNo, SSN, DOB)
VALUES
('4', '1231544984', '2000-02-01')
,('5', '5487946598', '2001-01-01')
,('6', '8789453115', '2002-01-01');
Output:
To Insert records from some other table, we can also use the SELECT statement as shown below:
Query:
INSERT INTO Employee (EmpNo, SSN, DOB)
SELECT EmpNo, SSN, DOB
FROM Employee_history;
Output:
While selecting records from some other table, we can also use the TOP Clause or DISTINCT clause, or other criteria.
We can also insert records into a table by passing the results from the execution of Stored Procedure let’s say sp_Employee_History using the below syntax:
Query:
INSERT INTO Employee (EmpNo, SSN, DOB)
EXEC sp_Employee_History;
Output:
READ:
READ often refers to SELECT statement or Data Retrieval operation from Tables or Views. The default syntax of a SELECT statement would be:
Query:
SELECT *
FROM object_name;
Where object_name can be a Table or View or functions. We need to specify the braces while trying to SELECT records from functions. The SELECT statement can be combined with various possible operations like:
- Aggregate operations like MIN, MAX, SUM, and COUNT operations with GROUP BY operation.
- SELECT TOP number of records
- SELECT DISTINCT result sets
- SELECT filtered records using WHERE conditions
- HAVING clause to filter records based upon Aggregated columns.
- ORDER BY Clause to sort the result set based upon Selected columns.
To SELECT records from Employee Table, we can use the below syntax.
Query:
SELECT *
FROM Employee;
Output:
Even though using the * symbol in the SELECT clause returns all columns in the table, it is recommended to explicitly specify the required column names in the SELECT clause to avoid any Application code breakages later due to any changes in Table structure or columns. To SELECT specific columns like EmpNo, SSN, and DOB alone from the Employee table, we can use the below query:
Query:
SELECT EmpNo, SSN, DOB
FROM Employee;
Output:
To SELECT TOP 5 records from Employee Table, we can use the below query.
Query:
SELECT TOP 5 EmpNo, SSN, DOB
FROM Employee;
Output:
To SELECT a unique combination of records from the Employee table for certain columns, we can use the DISTINCT clause along with the columns where we need to fetch the unique values as shown below:
Query:
SELECT DISTINCT EmpNo, SSN
FROM Employee;
Output:
To SELECT specific records from Employee Table, we can use the WHERE clause as shown below:
Query:
SELECT EmpNo, SSN, DOB
FROM Employee
WHERE EmpNo = '1';
Output:
To Aggregate the result set using any Aggregate operation, we would need to use the syntax below:
Query:
SELECT EmpNo, SSN, COUNT(*) cnt
FROM Employee
GROUP BY EmpNo, SSN;
Output:
To Order the above result set based upon EmpNo, we can use the ORDER BY Clause as shown below:
Query:
SELECT EmpNo, SSN, COUNT(*) cnt
FROM Employee
GROUP BY EmpNo, SSN
ORDER BY EmpNo;
Output:
To perform filtering on Aggregated values, we need to use the HAVING clause as shown below.
Query:
SELECT EmpNo, SSN, COUNT(*) cnt
FROM Employee
GROUP BY EmpNo, SSN
HAVING COUNT(*) = 2
ORDER BY EmpNo;
Output:
To SELECT records from Multiple tables, we would need to use the JOIN clause which can be either INNER JOIN or LEFT OUTER JOIN or RIGHT OUTER JOIN or other types as shown below.
Query:
SELECT e.EmpNo, e.SSN, e.DOB, eh.EmpNo as Older_EmpNo
FROM Employee e
INNER JOIN Employee_history eh on e.EmpNo = eh.EmpNo
WHERE e.EmpNo = 1
ORDER BY e.EmpNo;
Using SELECT statement, we can even create a Table and while creating a table we can create the table with or without data using the below options
- Create a Table with Data:
Query:
SELECT *
INTO Employee_backup
FROM Employee;
Output:
Selecting from the Backup table will show the records as shown below:
Query:
SELECT *
FROM Employee_backup;
Output:
- Create Table without Data (Schema only):
Query:
SELECT *
INTO Employee_backup
FROM Employee
WHERE 1 = 2;
Output:
As we can see above 0 rows are affected indicating no Data changes happened out and selecting from the Backup table will show no records as shown below:
Query:
SELECT *
FROM Employee_backup;
Output:
UPDATE:
UPDATE operation refers to changing any data existing in the Table and the UPDATE operation or statement in SQL Server includes the SET clause to specify which columns to be updated and use the WHERE clause to UPDATE specific records. The general syntax to update records inside a table will be:
Query:
UPDATE Table_Name
SET column_Name = column_value
WHERE Column_name = Filter_condition;
Output:
To update the record with EmpId = 3 to make EmpNo unique on the Employee table, we can use the below query:
Query:
UPDATE Employee
SET EmpNo = '3'
, SSN = '4984564512'
, DOB = '1998-01-01';
Upon careful verification of the above query, we can notice that there is no "WHERE condition" specified out, and without a WHERE condition, execution of the above query will UPDATE all the records in the Employee table. Hence, we should be more careful whenever executing an UPDATE statement by ensuring appropriate WHERE clauses as shown below:
Query:
UPDATE Employee
SET EmpNo = '3'
, SSN = '4984564512'
, DOB = '1998-01-01'
WHERE EmpId = 3;
Output:
We are able to see the EmpId valued 3 updated successfully with the correct values now. We can also use Common Table Expression to do the equivalent operation using the below query.
Query:
; with cte as (
SELECT *
FROM Employee
WHERE EmpId = 3)
UPDATE cte
SET EmpNo = '3'
, SSN = '4984564512'
, DOB = '1998-01-01';
Similar to the INSERT clause, we can also UPDATE only limited records using the TOP clause as shown below:
Query:
UPDATE TOP (5) Employee
SET CreatedDt = GETDATE()
, CreatedBy = 'system'
WHERE CreatedDt IS NULL;
Output:
We can notice that the above UPDATE query has updated only 5 records even though we have a lot of records with CreatedDt as NULL values.
Now, let’s create some Default values for CreatedDt and CreatedBy columns using the query below.
Query:
ALTER TABLE Employee ADD CONSTRAINT
CK_CreatedDt DEFAULT GETDATE() FOR CreatedDt;
ALTER TABLE Employee ADD CONSTRAINT
CK_CreatedBy DEFAULT GETDATE() FOR CreatedBy;
Output:
Now, let’s try to UPDATE all records using the default values with the below query:
Query:
UPDATE Employee
SET CreatedDt = DEFAULT
, CreatedBy = DEFAULT
WHERE CreatedDt IS NULL;
Output:
To UPDATE records in a table using values from another table, the UPDATE statement supports the JOIN clause with another table as shown in the below query. We can specify the alias name of the table that needs to be updated in the UPDATE clause and JOIN any number of tables in the FROM Clause.
Query:
UPDATE e
SET CreatedDt = eh.CreatedDt
, CreatedBy = eh.CreatedBy
FROM Employee e
INNER JOIN Employee_Backup eh on e.EmpId = eh.EmpId;
DELETE:
DELETE operation is used to delete or remove any existing records from the table. Similar to the UPDATE operation, one should be much more careful while executing the DELETE statement and ensure that it has the necessary WHERE clause to avoid accidental deletion of the entire table.
To DELETE records from a table would be:
Query:
DELETE FROM Table_name
WHERE column_name = Filter_condition;
To Delete records from Employee Table, we can use the below query:
Query:
DELETE FROM Employee
WHERE EmpId = 10;
Output:
We can use the TOP Clause to delete only limited records for the selected WHERE condition as shown below.
Query:
DELETE TOP(1) FROM Employee
WHERE EmpId = 11;
Output:
We can also use Common Table Expression to delete records with the appropriate WHERE clause like below.
Query:
; with cte as (
SELECT *
FROM Employee
WHERE EmpId = 12
)
DELETE FROM cte;
Output:
Similar to the UPDATE operation, we can also DELETE records from a table by performing a JOIN operation with other tables using the query below.
Query:
DELETE e
FROM Employee e
JOIN Employee_Backup eh on e.EmpId = eh.EmpId
WHERE e.EmpId = 10;
Output:
CRUD Operations as Stored Procedures
Till now, we have gone through the CRUD operations in detail and to make any changes to these CRUD operations faster in SQL Server, it is recommended to create 4 Stored Procedures one for each table with the procedure name template as shown below
• CREATE/INSERT – Schema_name.Table_name_INSERT
• READ/SELECT – Schema_name.Table_name_SELECT
• UPDATE – Schema_name.Table_name_UPDATE
• DELETE – Schema_name.Table_name_UPDATE
If we have these individual CRUD operations created as Procedures for any logic changes during DML operations, we can simply modify the stored procedures involved without major code changes and avoid Code Rebuild times for most of the cases.
Conclusion
Today, we have understood about CRUD operations and how to perform CRUD operations with various possible syntax in SQL Server with demo as well. In addition to that, we have also discussed about the benefits of having these CRUD operations performed via Stored Procedures which can ease the Development/Enhancement process and during troubleshooting any logic issues as well. In We can use the SQL Complete tool to perform Auto Complete of any Transact SQL Statements or DML statements to improve the Productivity of Developers.
Similar Reads
DBMS Tutorial â Learn Database Management System Database Management System (DBMS) is a software used to manage data from a database. A database is a structured collection of data that is stored in an electronic device. The data can be text, video, image or any other format.A relational database stores data in the form of tables and a NoSQL databa
7 min read
Basic of DBMS
Introduction of DBMS (Database Management System)DBMS is a software system that manages, stores, and retrieves data efficiently in a structured format.It allows users to create, update, and query databases efficiently.Ensures data integrity, consistency, and security across multiple users and applications.Reduces data redundancy and inconsistency
6 min read
History of DBMSThe first database management systems (DBMS) were created to handle complex data for businesses in the 1960s. These systems included Charles Bachman's Integrated Data Store (IDS) and IBM's Information Management System (IMS). Databases were first organized into tree-like structures using hierarchica
7 min read
DBMS Architecture 1-level, 2-Level, 3-LevelA DBMS architecture defines how users interact with the database to read, write, or update information. A well-designed architecture and schema (a blueprint detailing tables, fields and relationships) ensure data consistency, improve performance and keep data secure.Types of DBMS Architecture There
6 min read
Difference between File System and DBMSA file system and a DBMS are two kinds of data management systems that are used in different capacities and possess different characteristics. A File System is a way of organizing files into groups and folders and then storing them in a storage device. It provides the media that stores data as well
6 min read
Entity Relationship Model
Introduction of ER ModelThe Entity-Relationship Model (ER Model) is a conceptual model for designing a databases. This model represents the logical structure of a database, including entities, their attributes and relationships between them. Entity: An objects that is stored as data such as Student, Course or Company.Attri
10 min read
Structural Constraints of Relationships in ER ModelStructural constraints, within the context of Entity-Relationship (ER) modeling, specify and determine how the entities take part in the relationships and this gives an outline of how the interactions between the entities can be designed in a database. Two primary types of constraints are cardinalit
5 min read
Generalization, Specialization and Aggregation in ER ModelUsing the ER model for bigger data creates a lot of complexity while designing a database model, So in order to minimize the complexity Generalization, Specialization and Aggregation were introduced in the ER model. These were used for data abstraction. In which an abstraction mechanism is used to h
4 min read
Introduction of Relational Model and Codd Rules in DBMSThe Relational Model is a fundamental concept in Database Management Systems (DBMS) that organizes data into tables, also known as relations. This model simplifies data storage, retrieval, and management by using rows and columns. Coddâs Rules, introduced by Dr. Edgar F. Codd, define the principles
14 min read
Keys in Relational ModelIn the context of a relational database, keys are one of the basic requirements of a relational database model. Keys are fundamental components that ensure data integrity, uniqueness and efficient access. It is widely used to identify the tuples(rows) uniquely in the table. We also use keys to set u
6 min read
Mapping from ER Model to Relational ModelConverting an Entity-Relationship (ER) diagram to a Relational Model is a crucial step in database design. The ER model represents the conceptual structure of a database, while the Relational Model is a physical representation that can be directly implemented using a Relational Database Management S
7 min read
Strategies for Schema design in DBMSThere are various strategies that are considered while designing a schema. Most of these strategies follow an incremental approach that is, they must start with some schema constructs derived from the requirements and then they incrementally modify, refine or build on them. What is Schema Design?Sch
6 min read
Relational Model
Introduction of Relational Algebra in DBMSRelational Algebra is a formal language used to query and manipulate relational databases, consisting of a set of operations like selection, projection, union, and join. It provides a mathematical framework for querying databases, ensuring efficient data retrieval and manipulation. Relational algebr
9 min read
SQL Joins (Inner, Left, Right and Full Join)SQL joins are fundamental tools for combining data from multiple tables in relational databases. For example, consider two tables where one table (say Student) has student information with id as a key and other table (say Marks) has information about marks of every student id. Now to display the mar
4 min read
Join operation Vs Nested query in DBMSThe concept of joins and nested queries emerged to facilitate the retrieval and management of data stored in multiple, often interrelated tables within a relational database. As databases are normalized to reduce redundancy, the meaningful information extracted often requires combining data from dif
3 min read
Tuple Relational Calculus (TRC) in DBMSTuple Relational Calculus (TRC) is a non-procedural query language used to retrieve data from relational databases by describing the properties of the required data (not how to fetch it). It is based on first-order predicate logic and uses tuple variables to represent rows of tables.Syntax: The basi
4 min read
Domain Relational Calculus in DBMSDomain Relational Calculus (DRC) is a formal query language for relational databases. It describes queries by specifying a set of conditions or formulas that the data must satisfy. These conditions are written using domain variables and predicates, and it returns a relation that satisfies the specif
4 min read
Relational Algebra
Introduction of Relational Algebra in DBMSRelational Algebra is a formal language used to query and manipulate relational databases, consisting of a set of operations like selection, projection, union, and join. It provides a mathematical framework for querying databases, ensuring efficient data retrieval and manipulation. Relational algebr
9 min read
SQL Joins (Inner, Left, Right and Full Join)SQL joins are fundamental tools for combining data from multiple tables in relational databases. For example, consider two tables where one table (say Student) has student information with id as a key and other table (say Marks) has information about marks of every student id. Now to display the mar
4 min read
Join operation Vs Nested query in DBMSThe concept of joins and nested queries emerged to facilitate the retrieval and management of data stored in multiple, often interrelated tables within a relational database. As databases are normalized to reduce redundancy, the meaningful information extracted often requires combining data from dif
3 min read
Tuple Relational Calculus (TRC) in DBMSTuple Relational Calculus (TRC) is a non-procedural query language used to retrieve data from relational databases by describing the properties of the required data (not how to fetch it). It is based on first-order predicate logic and uses tuple variables to represent rows of tables.Syntax: The basi
4 min read
Domain Relational Calculus in DBMSDomain Relational Calculus (DRC) is a formal query language for relational databases. It describes queries by specifying a set of conditions or formulas that the data must satisfy. These conditions are written using domain variables and predicates, and it returns a relation that satisfies the specif
4 min read
Functional Dependencies & Normalization
Attribute Closure in DBMSFunctional dependency and attribute closure are essential for maintaining data integrity and building effective, organized and normalized databases. Attribute closure of an attribute set can be defined as set of attributes which can be functionally determined from it.How to find attribute closure of
4 min read
Armstrong's Axioms in Functional Dependency in DBMSArmstrong's Axioms refer to a set of inference rules, introduced by William W. Armstrong, that are used to test the logical implication of functional dependencies. Given a set of functional dependencies F, the closure of F (denoted as F+) is the set of all functional dependencies logically implied b
4 min read
Canonical Cover of Functional Dependencies in DBMSManaging a large set of functional dependencies can result in unnecessary computational overhead. This is where the canonical cover becomes useful. A canonical cover is a set of functional dependencies that is equivalent to a given set of functional dependencies but is minimal in terms of the number
7 min read
Normal Forms in DBMSIn the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
The Problem of Redundancy in DatabaseRedundancy means having multiple copies of the same data in the database. This problem arises when a database is not normalized. Suppose a table of student details attributes is: student ID, student name, college name, college rank, and course opted. Student_ID Name Contact College Course Rank 100Hi
6 min read
Lossless Join and Dependency Preserving DecompositionDecomposition of a relation is done when a relation in a relational model is not in appropriate normal form. Relation R is decomposed into two or more relations if decomposition is lossless join as well as dependency preserving. Lossless Join DecompositionIf we decompose a relation R into relations
4 min read
Denormalization in DatabasesDenormalization 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 'reversing normalization' or 'not to normalize'. It is an optimization technique that is ap
4 min read
Transactions & Concurrency Control
ACID Properties in DBMSTransactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability even in case of failures / errors. This is where t
5 min read
Types of Schedules in DBMSScheduling is the process of determining the order in which transactions are executed. When multiple transactions run concurrently, scheduling ensures that operations are executed in a way that prevents conflicts or overlaps between them.There are several types of schedules, all of them are depicted
6 min read
Recoverability in DBMSRecoverability ensures that after a failure, the database can restore a consistent state by keeping committed changes and undoing uncommitted ones. It uses logs to redo or undo actions, preventing data loss and maintaining integrity.There are several levels of recoverability that can be supported by
5 min read
Implementation of Locking in DBMSLocking protocols are used in database management systems as a means of concurrency control. Multiple transactions may request a lock on a data item simultaneously. Hence, we require a mechanism to manage the locking requests made by transactions. Such a mechanism is called a Lock Manager. It relies
5 min read
Deadlock in DBMSA deadlock occurs in a multi-user database environment when two or more transactions block each other indefinitely by each holding a resource the other needs. This results in a cycle of dependencies (circular wait) where no transaction can proceed.For Example: Consider the image belowDeadlock in DBM
4 min read
Starvation in DBMSStarvation in DBMS is a problem that happens when some processes are unable to get the resources they need because other processes keep getting priority. This can happen in situations like locking or scheduling, where some processes keep getting the resources first, leaving others waiting indefinite
8 min read
Advanced DBMS
Indexing in DatabasesIndexing in DBMS is used to speed up data retrieval by minimizing disk scans. Instead of searching through all rows, the DBMS uses index structures to quickly locate data using key values.When an index is created, it stores sorted key values and pointers to actual data rows. This reduces the number
6 min read
Introduction of B TreeA B-Tree is a specialized m-way tree designed to optimize data access, especially on disk-based storage systems. In a B-Tree of order m, each node can have up to m children and m-1 keys, allowing it to efficiently manage large datasets.The value of m is decided based on disk block and key sizes.One
8 min read
Introduction of B+ TreeA B+ Tree is an advanced data structure used in database systems and file systems to maintain sorted data for fast retrieval, especially from disk. It is an extended version of the B Tree, where all actual data is stored only in the leaf nodes, while internal nodes contain only keys for navigation.C
5 min read
Bitmap Indexing in DBMSBitmap Indexing is a powerful data indexing technique used in Database Management Systems (DBMS) to speed up queries- especially those involving large datasets and columns with only a few unique values (called low-cardinality columns).In a database table, some columns only contain a few different va
3 min read
Inverted IndexAn Inverted Index is a data structure used in information retrieval systems to efficiently retrieve documents or web pages containing a specific term or set of terms. In an inverted index, the index is organized by terms (words), and each term points to a list of documents or web pages that contain
7 min read
SQL Queries on Clustered and Non-Clustered IndexesIndexes in SQL play a pivotal role in enhancing database performance by enabling efficient data retrieval without scanning the entire table. The two primary types of indexes Clustered Index and Non-Clustered Index serve distinct purposes in optimizing query performance. In this article, we will expl
7 min read
File Organization in DBMSFile organization in DBMS refers to the method of storing data records in a file so they can be accessed efficiently. It determines how data is arranged, stored, and retrieved from physical storage.The Objective of File OrganizationIt helps in the faster selection of records i.e. it makes the proces
5 min read
DBMS Practice