You are on page 1of 14

DDL and DML Commands in SQL

MODULE - 2 CREATING AND MANAGING DATABASES IN POSTGRES


Lesson - 4 DDL and DML Commands in SQL

DDL stands for Data Definition Language and refers to SQL commands used to create,
modify, and delete database structures such as tables, indexes, and views. DML stands for
Data Manipulation Language and refers to SQL commands used to insert, update, and
delete data within a database. Now, let’s learn about the DDL and DML commands in depth.

What are DDL Commands in SQL?

DDL (Data Definition Language) is a type of SQL command used to define data structures
and modify data. It creates, alters, and deletes database objects such as tables, views,
indexes, and users. Examples of DDL statements include CREATE, ALTER, DROP and
TRUNCATE.

What are DML Commands in SQL?

DML (Data Manipulation Language) is a type of SQL command used to manipulate data in a
database. It inserts, updates, and deletes data from a database table. Examples of DML
statements include INSERT, UPDATE, and DELETE.

Types of DDL Statements

Snega is a talented programmer who has been eager to learn more about the various
aspects of Python programming. One day, she comes across a tutorial about databases and
SQL queries. She is particularly interested in learning about the basics of databases, such
as Data Definition Language (DDL) and Data Manipulation Language (DML). She eagerly
starts reading the tutorial. Lets help her in the journey.

1. CREATE: It is used to create objects in the database, such as tables, views, stored
procedures, and more.
2. ALTER: It is used to modify the structure of an existing database object.
3. DROP: It is used to delete an entire object or part of an object from the database.
4. TRUNCATE: Used to delete all records from a table but does not delete the table
structure.
5. RENAME: Used to rename an existing database object.

Types of DML Statements

1. INSERT: Used to add new records to a database table.


2. UPDATE: Used to modify existing records in a database table.
3. DELETE: Used to delete existing records from a database table.
4. MERGE: Used to combine data from two or more tables into one.
5. SELECT: Used to retrieve data from one or more tables in a database.
6. CALL: Used to call a stored procedure or function.

DDL vs DML Commands


Explore the difference between DDL and DML commands in the below table. Understand
how DDL commands shape database structures, while DML commands manipulate data
within the database.

DDL DML
Used to define database objects like tables, indexes,
Used to manipulate data within the database.
views, etc.
Examples of DML statements include
Examples of DDL statements include CREATE,
SELECT, INSERT, UPDATE, and
ALTER, and DROP.
DELETE.
Changes made using DDL affect the structure of the Changes made using DML affect the data
database. stored in the database.
DDL statements are not transactional, meaning they DML statements are transactional, meaning
cannot be rolled back. they can be rolled back if necessary.
DDL statements are usually executed by a database DML statements are executed by application
administrator. developers or end-users.
DDL statements are typically used during the design DML statements are used during normal
and setup phase of a database. operation of a database.
Examples of DDL statements: CREATE TABLE,
Examples of DML statements: SELECT,
DROP TABLE, ALTER TABLE, CREATE INDEX,
INSERT, UPDATE, DELETE, etc.
etc.

Benefits of DDL and DML

1. DDL (Data Definition Language) provides the ability to define, create and modify
database objects such as tables, views, indexes, and users.
2. DML (Data Manipulation Language) allows for manipulating data in a database, such
as inserting, updating, and deleting records.
3. DDL and DML commands can be used to ensure data integrity in the database.
4. DDL and DML commands provide a way to control access to the database by
granting and revoking privileges.

DDL (Data Definition Language) Example

CREATE TABLE Employees (

EmployeeID INT,

FirstName VARCHAR(255),

LastName VARCHAR(255),

Department VARCHAR(255)

);

ALTER TABLE Employees

ADD Salary INT;

DROP TABLE Employees;

DML (Data Manipulation Language) Example

INSERT INTO Employees (EmployeeID, FirstName, LastName, Department)


VALUES (1, 'John', 'Smith', 'IT');

UPDATE Employees

SET Salary = 50000

WHERE EmployeeID = 1;

SELECT * FROM Employees;

DELETE FROM Employees

WHERE EmployeeID = 1;

Difference between MIS and DSS

The following table highlights the important differences between MIS and DSS −

Key MIS DSS

MIS stands for Management Information System. DSS stands for Decision Support
Full Form
System.

The primary purpose of an MIS is to provide the A DSS, on the other hand, is designed
management with the information they need to make to support specific decision-making
Purpose operational and strategic decisions. An MIS is focused processes and is often used by
on the internal operations of an organization and is individuals or small groups within an
designed to support the needs of managers at all levels. organization.

Primary MIS identifies the information required. DSS identifies the tools to be used in
Task the decision process.

An MIS typically uses data that is internal to the A DSS may use both internal and
organization, such as data from financial systems, HR external data, and is often used to
Data systems, and sales systems. analyze large amounts of data to
identify trends and patterns that can help
inform decision making.

Dependency Dependent on computer systems. Dependent on management jurisdiction.

MIS is used in control process DSS is used in planning, staffing and


Usage
decision making.

MIS is used by middle level, low level users and senior DSS is used by analysts, professionals
Users
executives in some cases. and managers.
Focus is on information processing. Focus is on decision making, support
Focus
and analysis.

An MIS is typically a centralized system that is used by A DSS is often more decentralized, and
Structure all parts of an organization. is used by specific departments or
individuals as needed.

An MIS is typically a batch processing system, A DSS is often an online system that
meaning that it processes data in batches at regular allows users to interact with the data in
Interactivity
intervals. real-time and get immediate feedback
on their queries and analyses.

Conclusion

To conclude, MIS focuses on efficiency, whereas DSS focuses on effectiveness.


Overall, the main difference between an MIS and a DSS is the scope of their
purpose and the types of data and decision-making processes they support.

alidation Rules

Validation rules prevent bad data being saved in your table. Basically, they look like
criteria in a query.

You can create a rule for a field (lower pane of table design), or for the table (in the
Properties box in table design.) Use the table's rule to compare fields.

There is one trap to avoid. In some versions of Access, you will not be able to leave the
field blank once you add the validation rule, i.e. you must enter something that satisfies
the rule. If you need to be able to leave the field blank, add OR Is Null to your rule. (Some
versions accept Nulls anyway, but we recommend you make it explicit for clarity and
consistency.)

This article explains how to use validation rules, and concludes with some thought
provoking on when to use them.

Validation Rules for fields

When you select a field in table design, you see its Validation Rule property in the lower
pane.

This rule is applied when you enter data into the field. You cannot tab to the next field
until you enter something that satisfies the rule, or undo your entry.

Examples:

To do this ... Validation Explanation


Rule for Fields

Accept letters Is Null OR Not Any character outside the range A to Z is rejected. (Case
(a - z) only Like "*[!a-z]*" insensitive.)

Accept digits Is Null OR Not Any character outside the range 0 to 9 is rejected.
(0 - 9) only Like "*[!0-9]*" (Decimal point and negative sign rejected.)

Is Null Or Not
Letters and
Like "*[!a-z OR Punctuation and digits rejected.
spaces only
"" ""]*"

Is Null OR Not
Digits and Accepts A to Z and 0 to 9, but no punctuation or other
Like "*[!((a-z)
letters only characters.
or (0-9))]*"

Exactly 8 Is Null OR Like


The question mark stands for one character.
characters "????????"

Is Null OR
Between 1000 For Number fields.
Exactly 4 And 9999
digits
Is Null OR Like
For Text fields.
"####"

Positive
Is Null OR >= 0 Remove the "=" if zero is not allowed either.
numbers only

Is Null OR
No more than 100% is 1. Use 0 instead of -1 if negative percentages are
Between -1
100% not allowed.
And 1

Not a future Is Null OR <=


date Date()

Is Null OR
((Like "*?@?*.? Requires at least one character, @, at least one
Email address *") AND character, dot, at least one character. Space, comma,
(Not Like and semicolon are not permitted.
"*[ ,;]*"))

Same as setting the field's Required property, but lets


You must fill
Not Null you create a custom message (in the Validation
in Field1
Text property.)

Limit to Is Null OR "M" It is better to use a lookup table for the list, but this
specific Or "F" may be useful for simple choices such as Male/Female.
Is Null OR IN
choices The IN operator may be simpler than several ORs.
(1, 2, 4, 8)

The Yes/No field in Access does not support Null as other


Yes/No/Null Is Null OR 0 or databases do. To simulate a real Yes/No/Null data type,
field -1 use a Number field (size Integer) with this rule. (Access
uses 0 for False, and -1 for True.)

Validation Rules for tables

In table design, open the Properties box and you see another Validation Rule. This is the
rule for the table.

The rule is applied after all fields have been entered, just before the record is saved. Use
this rule to compare values across different fields, or to delay validation until the last
moment before the record is saved.

Examples:

Validation Rule for


To do this ... Explanation
Table

([StartDate] Is Null)
A booking OR
The rule is satisfied if either field is left blank;
cannot ([EndDate] Is Null)
otherwise StartDate must be before (or the same
end before it OR
as) EndDate.
starts ([StartDate] <=
[EndDate])

If you fill
in Field1, ([Field1] Is Null) OR The rule is satisfied if Field1 is blank; otherwise it
Field2 is ([Field2] Is Not Null) is satisfied only if Field2 is filled in.
required also

You must
([Field1] Is Null)
enter Field1
XOR ([Field2] Is XOR is the exclusive OR.
or Field2, but
Null)
not both

When to use validation rules

In designing a database, you walk a tightrope between blocking bad data and accepting
anything. Ultimately, a database is only as good as the data it contains, so you want to do
everything you can to limit bad data. On the other hand, truth is stranger than fiction, and
your database must handle those weird real-world cases where the data exceeds the
bounds of your imagination.

Field's validation rule

Take a BirthDate field, for example. Should you create a rule to ensure the user doesn't
enter a future date? We would need some radically different physics to ever be entering
people who are not yet born, so it sounds like a safe enough rule? But did you consider
that the computer's date might be wrong? Would it be better to give a warning rather than
block the entry?

The answer to that question is subjective. The question merely illustrates the need to
think outside the box whenever you will block data, not merely to block things just
because you cannot imagine a valid scenario for that data.

Validation Rules are absolute. You cannot bypass them, so you cannot use them for
warnings. To give a warning instead, use an event of your form, such as
Form_BeforeUpdate.

Table's validation rule

We suggested using this rule for comparing fields. In the ideal database design, the fields
are not dependent on each other, so if you are comparing fields, you might consider
whether there is another way to design the table.

Our first example above ensures that a booking does not end before it starts. There is
therefore a dependency between these two fields. Could we redesign the table without
that dependency? How about replacing EndDate with a Duration field? Duration would be a
number in an applicable unit (e.g. days for hotel bookings, periods for school classrooms,
or minutes for doctors appointments.) We use a calculated field in a query to get
the EndDate. This may not be the best design for every case, but it is worth considering
when you go to use the record-level validation rule.

Limitations

You cannot use a validation rule where:

 You want to call user-defined functions, or VBA functions beyond the ones in JET
such as IIf() and Date().
 The user should be able to bypass the rule.
 The expression is too complex.
 The expression involves data in other records or other tables. (Well, not easily,
anyway.)

Alternatives

Use these alternatives instead of or in combination with validation rules:

 Required: Setting a field's Required property to Yes forces the user to enter
something. (In addition to the obvious cases, always consider setting this to Yes for
your foreign key fields. See #3 in this article for details.)
 Allow Zero Length: Setting this property to No for text, memo, and hyperlink
fields prevents a zero-length string being entered. A ZLS is not the same as a Null,
so if you permit this you have confusing data for the user, more work checking for
both as a developer, more chance of a mistake, and slower executing queries. More
information in Problem Properties.
 Indexed: To prevent duplicates in a field, set this property to Yes (No Duplicates).
Using the Indexes box in table design, you can create a multi-field unique index to
the values are unique across a combination of fields.
 Lookups: Rather than creating a validation rule consisting of a list of valid values,
consider creating a related table. This is much more flexible and easier to
maintain.
 Input Mask: Of limited use. Users must enter the entire pattern (without them you
can enter some dates with just 3 keystrokes, e.g. 2/5), and they cannot easily
insert a character if they missed one.

Conclusion

Validation rules are very useful for keeping bad data out of your tables, but be careful not
to overdo them. You don't want to block things that might be valid, though unexpected.

An entity is a real-world object that represents data in RDBMS. For example, assume a
university management system. It stores information about students, lecturers, courses,
exams, etc. The Student, lecturer, course, and exam become the tables in the database.
A record in student table is called an entity. It represents a single student object.
Similarly, a record in lecturer table is an entity. It represents a one lecturer object. These
entities are called strong entities. There is another entity type as a weak entity. A weak
entity depends on another entity. For example, an exam entity depends on the course
entity.

So, it is a weak entity.


What is Attribute

Attributes are properties that describe an entity. Let’s look at the example of a
university management system again. The student entity has attributes such as student
id, name, age, address, GPA. The course entity has attributes such as course id, course
name, duration. Moreover, the exam entity has attributes such as exam number, date,
start time, end time, etc.

These are various types of attributes. They are as follows.

Simple attribute – We cannot divide a simple attribute further. E.g. – id, age
Composite attribute – It is a combination of more than one simple attributes. E.g. –
Name consists of first name, middle name, last name. The address can consist of house
number, street name, city, etc.
Single-valued attribute – It can only have a single value. E.g. – id, age
Multivalued attribute – There can be multiple values for this attribute. E.g. – email,
phone number

Degree in SQL refers to the number of attributes or columns in a relation or table. It


represents the horizontal size of the table. For example, if a table has three attributes, it
has a degree of three.

Cardinality in SQL refers to the number of tuples or rows in a relation or table. It


represents the vertical size of the table. For example, if a table has five rows, it has a
cardinality of five.

Degree and cardinality are important concepts in database design and optimization.
The degree of a table determines the number of attributes that need to be defined and
stored for each row, impacting the storage requirements and query performance.
Higher degrees can result in wider tables and potentially slower query execution.
Cardinality, on the other hand, affects the size of the table and the efficiency of query
processing. Tables with high cardinality may require more resources for storage and
retrieval.

o ER model stands for an Entity-Relationship model. It is a high-level data model. This


model is used to define the data elements and relationship for a specified system.
o It develops a conceptual design for the database. It also develops a very simple and
easy to design view of data.
o In ER modeling, the database structure is portrayed as a diagram called an entity-
relationship diagram.

Component of ER Diagram
1. Entity:

An entity may be any object, class, person or place. In the ER diagram, an entity can be
represented as rectangles.

Consider an organization as an example- manager, product, employee, department etc. can


be taken as an entity.

Co
mponent of ER Diagram
1. Entity:

An entity may be any object, class, person or place. In the ER diagram, an entity can be
represented as rectangles.

Consider an organization as an example- manager, product, employee, department etc. can


be taken as an entity.

Key
Attribute

The key attribute is used to represent the main characteristics of an entity. It represents a
primary key. The key attribute is represented by an ellipse with the text underlined.
An attribute that composed of many other attributes is known as a composite attribute. The
composite attribute is represented by an ellipse, and those ellipses are connected with an
ellipse.

Multivalued Attribute

An attribute can have more than one value. These attributes are known as a multivalued
attribute. The double oval is used to represent multivalued attribute.

For example, a student can have more than one phone number.

Relationship

A relationship is used to describe the relation between entities. Diamond or rhombus is used
to represent the relationship.

Whe
n only one instance of an entity is associated with the relationship, then it is known as one to
one relationship.

For example, A female can marry to one male, and a male can marry to one female.

One-to-many relationship

When only one instance of the entity on the left, and more than one instance of an entity on
the right associates with the relationship then this is known as a one-to-many relationship.

For example, Scientist can invent many inventions, but the invention is done by the only
specific scientist.

c. Many-to-one relationship

When more than one instance of the entity on the left, and only one instance of an entity on
the right associates with the relationship then it is known as a many-to-one relationship.
For example, Student enrolls for only one course, but a course can have many students.

Tell some of the most important uses of MS Access?

Uses of MS Access:

o MS Access is used as frontend when the backend is product of ODBC compliant.


o MS Access is widely used for small database applications are based on web and
hosted on IIS by making use of ASP.NET pages.
o Mainly, it is used by small firms and businesses, specific departments in large
organizations and some people for developing applications on desktop for data
applications.
o It can be used as RAD while developing standalone applications and prototype.

7) What is a super key? How is it different from a candidate key?

A superkey is a set of attributes within a table whose values can be used to uniquely identify
a tuple. On the other hand, a candidate key is a minimal set of attributes mandatory to
identify a tuple.

A candidate key is also called a minimal super key.

How can you maintain a relationship between different databases in


Access?

Whenever a relationship is established between different databases, the first table of one
database considered as a primary key whereas the new field in another database considered
as a foreign key.

11) What are queries in MS Access?

Queries can be seen as a request used to perform various operations on data such as sort
data, insert data, retrieve data, update data, delete data, etc.

12) How to create a simple query in MS Access 2013?

Follow these instructions to create a simple query:

o Open database.
o Click on -create tab.
o Go to query wizard icon.
o Select a query type.
o Select the appropriate table from the pull-down menu.
o Now, choose the required field in the query results.
o You can insert information from additional tables, by repeating step 5 and 6.
o Go to next.
o Choose the result that you would like to produce.
o Specify a title to your query.
o Now, click finish.

How a table can be created using Microsoft Access Object Library


(MAOL)?

Define a variable of type object and initialize it with CreateTableDef() method.

What are the advantages of MS Access over MS SQL Server?

Following are some of the advantages of MS Access over MS SQL Server:

o MS Access is much easier to handle.


o MS Access is more reliable as client can read and write directly into raw data table.
o MS Access is more scalable when number of users are less.
o MS Access is cheaper and more compatible.

You might also like