TM07 Using Basic Structured Query Language
TM07 Using Basic Structured Query Language
AdministrationLevel-III
November, 2023
Addis Ababa, Ethiopia
Table of Contents
Acknowledgment ............................................................................................................................ 1
Acronym ......................................................................................................................................... 1
Introduction to the Module ............................................................................................................. 2
Unit One:Fundamental concepts of relational database.................................................................. 3
1.1. Data management approaches................................................................................... 4
1.2. Relational Database Management System ................................................................ 9
1.3. Structured query language ...................................................................................... 13
Self Check 1 .................................................................................................................................. 19
Operation sheet 1.1: Install SQL server 2012 ............................................................................... 21
Lap Test ........................................................................................................................................ 40
Unit Two: Data definition language ............................................................................................ 42
2.1. Introduction to SQL data definition language commands............................................ 42
2.2. Database planning ................................................................................................... 43
2.3. Usage of relevant naming convention for all database elements ............................ 44
2.4. Database structure creation and manipulation ........................................................ 53
Self-Check 2.................................................................................................................................. 63
Operation sheet 2.1: Create Database structure ............................................................................ 65
Lap Test ........................................................................................................................................ 67
Unit Three: Data manipulation language ...................................................................................... 68
3.1. Overview of SQL data manipulation language commands .......................................... 69
3.2. Data insertion .......................................................................................................... 69
3.3. Modification of existing data .................................................................................. 71
3.4. Data deletion ........................................................................................................... 73
Self check 3.1 ................................................................................................................................ 75
Operation sheet 3.1 Data Insertion................................................................................................ 76
Lap Test ........................................................................................................................................ 78
Unit Four: Data query language .................................................................................................... 79
4.1. Overview of SQL data query language ................................................................... 80
4.2. Selection of data from a single table ....................................................................... 82
4.3. Retrieval of data selectively .................................................................................... 84
4.4. Working with functions .......................................................................................... 97
4.5. Working with subqueries ...................................................................................... 108
Self-check 4 ................................................................................................................................ 109
Operation sheet 4.1 Inserting data into a database ...................................................................... 110
Lap Test ...................................................................................................................................... 113
Reference .................................................................................................................................... 115
Developer‘s Profile ..................................................................................................................... 116
Acknowledgment
Ministry of Labor and Skills wish to extend thanks and appreciation to the many representatives of
TVET instructors and respective industry experts who donated their time and expertise to the development
of this Teaching, Training and Learning Materials (TTLM).
Acronym
SQL ----------------------------------------------- Structured query language
DBA------------------------------------------------Database administrator
For effective use of this module trainees are expected to follow the following module instruction:
1. Read the information written in each unit
2. Accomplish the Self-checks at the end of each unit
3. Perform Operation Sheets which were provided at the end of units
4. Do the ―LAP test‖ given at the end of each unit
The way in which computers manage data has come a long way over the last few decades. Today‘s users
take for granted the many benefits found in a database system. However, it wasn‘t that long ago that
computer relied on a much less elegant and costly approach to data management called the file-based
system.
Integrity problems
Problems with data integrity is another disadvantage of using a file-based system. It refers to the
maintenance and assurance that the data in a database are correct andconsistent. Factors to consider when
addressing this issue are:
Data values must satisfy certain consistency constraints that are specified in the application programs.
What is a database?
A database is a shared collection of related data used to support the activities of a particular organization.
A database can be viewed as a repository of data that is defined once and then accessed by various
users.With the database approach, we can have the traditional banking system where Personnel
Department, the Account Department and the Loan Department access the shared corporate database.
1.1.3Database Properties
A database has the following properties:
The following system requirements cover SQL Server 2012 Standard Edition on 32-bit and x64platforms,
as well as Itanium-based systems.
SQLServer201264-bitHardwareRequirements:
SQLServer201264-bitSoftwareRequirements:
Operating System: SQL Server 2012 supports a variety of Windows Server andWindows
client operating systems. The specific editions of SQL Server 2012 (Enterprise, Standard,
etc.) may have different requirements. It's important to check the official documentation
for the exact operating system requirements for your specific edition.
.NET Framework: SQL Server 2012 requires the .NET Framework. The installer will
typically install the required version of .NET Framework for you.
SQL Server 2012 Edition: Make sure you have the correct edition of SQL Server 2012
(e.g., Enterprise, Standard, and Express) for your needs and licensing.
SQL Server 2012 Service Pack: It's advisable to install the latest service pack or
cumulative update for SQL Server 2012 for bug fixes and enhancements.
Please keep in mind that these requirements are subject to change based on updates and service
packs.AlwaysrefertotheofficialMicrosoftSQLServerdocumentationforthemostaccurate and up-to-
date information, especially if you have specific needs or configurations.
SQLServer201232-bitSoftwareRequirements:
Operating System: SQL Server 2012 32-bit supports a variety of 32-bit and 64-bit
Windows Server and Windows client operating systems. The specific editions of SQL
Server2012(Enterprise,Standard,etc.)mayhavedifferentsupportedoperatingsystems.
Check the official documentation for exact details.
.NET Framework: SQL Server 2012 requires .NET Framework 3.5 SP1 for installation.
Theinstallerwilltypicallyinstallthisforyou.Youmayalsoneed.NETFramework4.0or later for
some features.
SQLServer2012Edition:MakesureyouhavethecorrecteditionofSQLServer2012 (e.g.,
Enterprise, Standard, Express) for your needs and licensing.
SQLServer2012ServicePack:It'sadvisabletoinstallthelatestservicepackor
cumulative update for SQL Server 2012 for bug fixes and enhancements.
SQL is a flexible language that you can use in a variety of ways. It‘s the mostwidely used tool for
communicating with a relational database.SQL is a standard database language specifically designed for
storing, retrieving, managing or manipulating the data inside a relational database management system
(RDBMS). SQL became an ISO standard in 1987.
SQL is the most widely-implemented database language and supported by the popular relational database
systems, like MySQL, SQL Server, and Oracle. However, some features of the SQL standard are
implemented differently in different database systems.SQL is both a powerful language and one that is
relatively easy to learn. SQL is both a de factoand an official standard language for database. management.
History of SQL
SQL was originally developed at IBM in the early 1970s. Initially it was called SEQUEL (Structured
English Query Language) which was later changed to SQL (pronounced as S-Q-L). During the 1970s, a
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987. Since then, the standard has been revised to
include a larger set of features. Despite the existence of such standards, though, most SQL code is not
completely portable among different database systems without adjustments.
You can set permissions or access control within the database for data security.
You can create views to avoid typing frequently used complex queries.
The list does not end here; you can perform many other database-related tasks with SQL. You will learn
about most of them in detail in upcoming chapters.
The SQL keywords are words that are reserved words that are not used as a user defined data. The
most commonly used SQL key words according to ANSI/ISO SQL keywords are as follows:
COUNT GO VIEW
CURRENT WITH
CURSOR WORK
1.3.2Types of SQL Statements
Although SQL is considered a sublanguage because of its nonprocedural nature, it is nonetheless a
complete language in that it allows you to create and maintain database objects, secure those objects, and
manipulate the data within the objects. One common method used to categorize SQL statements is to
divide them according to the functions they perform. Based on this method, SQL can be separated into
three types of statements:
Data Definition Language (DDL) statements are used to create, modify, or delete database objects
such as tables, views, schemas, domains, triggers, stored procedures, and the database itself. The
SQL keywords most often associated with DDL statements are CREATE, ALTER, and DROP. For
example, you would use the CREATE TABLE statement to create a table, the ALTER TABLE
statement to modify the table‘s properties, and the DROP TABLE statement to delete the table
definition from the database.
Data Control Language (DCL)protects your database from becoming corrupted. Used correctly,
the DCL provides security for your database; the amount of protection depends on the
implementation. If your implementation doesn‘t provide sufficient protection, you must add that
protection to your application program. DCL statements allow you to control who or what (a
database user can be a person or an application program) has access to specific objects in your
database. With DCL, you can grant or restrict access by using the GRANT, Deny or REVOKE
statements, the three primary DCL commands. The DCL statements also allow you to control the
type of access each user has to database objects. For example, you can determine which users can
view a specific set of data and which users can manipulate that data.DDL and DCL statements are
6. Which normalization form ensures that there are no partial dependencies in a relational database?
A) First Normal Form (1NF)
B) Second Normal Form (2NF)
C) Third Normal Form (3NF)
D) Fourth Normal Form (4NF)
Step 1: Open installation media in new window and right click on setup file to run it ―As Administrator‖.
After running the setup file, you‘ll be redirected to Installation Media Center where you find various
options. As we‘re working on the installation, we won‘t dig other parts. Click on Installation section and
you‘ll find something like the following window.
After successful completion of previous step, setup will again run a check to ensure everything looks good
for the installation.
If you select ―All Features with Default‖, the following things will be set by default:
Select the components you want to install on your machine. The following is the description for above
listed components.
Database Engine Services: Allow you to install SQL Server instance.
Analysis Services: Allow you to install an Analysis Services instance on standalone or on cluster
node.
Reporting Services: Allow you to install the server as report server.
SQL Server Data Tool: Allow you to install SQL Server Developer tool to work with integration
packages. In SQL Server 2008 installation you‘ll find this service named as ‗Business Intelligence
Development Studio‘.
Integration Services: Allow you to install Integration Services.
After selecting the features to install, setup again runs a check to ensure whether your machine‘s
configuration is compatible or not to proceed further.
If
all looks good, click Next.
Step 12: Instance Configuration
Select type of instance you want to install. If you want to change the root directory of your instance, you
can change it from ‗Instance root directory‘ option. It‘ll also show you the instance already installed on
your machine. As shown in above screenshot, I already installed 2 instances on my machine.
After doing instance configuration, click Next.
Step 13: Disk Space requirement summary
At this step, you‘ll get disk space summary which will show how much disk space your instance will take
on the machine.
Under Service Account tab, you‘ll find option to set account name and password for any of the services;
also you can choose start-up type of those services. You can set startup type as Manual or Automatic. It‘s
recommended to set Start-up type of SQL Services to Automatic.
Next, you‘ll find Collation tab where you can set collation level for SQL Server and Analysis Services.
This is the most important step because over here you‘ll configure your servers configuration, data
directories and file stream options.
At Server Configuration tab, you‘ll find authentication mode and SQL Server System Administrator [SA]
account configuration.
If you had chosen Analysis Services to be installed on your machine, you‘ll find this option during
installation process.Complete this step by choosing server mode and adding Analysis Services
Administrator.
At this step, you‘ll find Distributed Replay Controller. This feature helps you assess the impact of future
SQL Server upgrades.
At this step, setup will perform a final check to ensure everything looks good for installation operation.
This will take some time, relax and just watch the progress.
Step 23: Installation completed
After successful installation you‘ll get the following window. This will show you the components installed
on your machine with ‗Succeeded‘ message in Status column.
Conclusion
We‘ve successfully installed SQL Server 2012 named instance on our machine. We have seen the steps
involved in the installation.
Lap Test
This unit is developed to provide you the necessary information regarding the following content
coverage and topics:
This unit will also assist you to attain the learning outcomes stated in the cover page.
Specifically, upon completion of this learning guide, you will be able to:
Explain Data definition language
Identify DDL commands
Apply SQL DDL to create and manipulate database structures
Identify the key components of a relational database (tables, rows, columns).
Understand the concept of table relationships (e.g., one-to-many, many-to-many).
Utilize INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN to combine data from
multiple tables.
Define and enforce data integrity using constraints (e.g., PRIMARY KEY, FOREIGN KEY,
UNIQUE).
Understand the purpose of constraints in maintaining data quality.
Understand the purpose and benefits of creating views
The database itself contains catalogs. Sometimes the database is referred toas a cluster.
A database table is a two-dimensional array made up of rows and columns.You can create a table by using
the SQL CREATE TABLEcommand. Within the command, you specify the name and data type of each
column. After you create a table, you can start loading it with data. (Loading data is a DML, not a DDL,
function.). If requirements change, you can change a table‘s structure by using the ALTER
TABLEcommand. If a table outlives its usefulness or becomes obsolete, you can eliminate it with the
DROPcommand. The various forms of the CREATEand ALTERcommands, together with the
DROPcommand, make up SQL‘s DDL.
The objects in a SQL-based database are identified by assigning them unique names. Names are
used in SQL statements to identify the database object on which the statement should act.
The ANSI/ISO SQL standard specifies tables names (which identify tables), column names (which
identify columns), and user names (which identify users of the database)
The SQL database Name should not be empty and special characters. The ANSI/ISO standards
specifies that SQL names must contain 1 to 18 characters, begin with a letter, and my not contain
any spaces or special punctuation characters.
TableName
When you specify a table name in a SQL statement, SQL assumes that you are referring to one
of your own tables (that is, a table that you created). With the proper permission, you can also
refer to tables owned by other users using a qualified table name.
ColumnName
DataTypes
Thereis astandard that specifies various types ofdata that canbe stored in SQL-baseddatabase
and manipulated by the SQL languages.
Characterstrings:
char(n) or Fixed-lengthcharacterstring.Maximum8,000characters N
character(n)
varchar(n) Variable-lengthcharacterstring.Maximum8,000characters
varchar(max) Variable-lengthcharacterstring.Maximum1,073,741,824
characters
Text Variable-lengthcharacterstring.Maximum2GBoftextdata
Unicodestrings:
nchar(n) Fixed-lengthUnicodedata.Maximum4,000characters
nvarchar(n) Variable-lengthUnicodedata.Maximum4,000characters
nvarchar(max) Variable-lengthUnicodedata.Maximum536,870,912characters
Ntext Variable-lengthUnicodedata.Maximum2GBoftextdata
Binarytypes:
binary(n) Fixed-lengthbinarydata.Maximum8,000bytes
varbinary(n) Variable-lengthbinarydata.Maximum8,000bytes
varbinary(max) Variable-lengthbinarydata.Maximum2GB
Image Variable-lengthbinarydata.Maximum2GB
Numbertypes:
Version-I
Level III
Datetypes:
timestamp Stores a unique number that gets updated every time a row gets created
or modified.Thetimestampvalueisbaseduponaninternalclockanddoesnot
correspond to real time. Each table may have only one timestamp
variable
Version-I
Level III
Otherdatatypes:
Datatype Description
uniqueidentifier Storesagloballyuniqueidentifier(GUID)
Table Storesaresult-setforlaterprocessing
Fixed-length character strings: columns holding these types of data typically store
names of people and companies, addresses, descriptions, and so on.
Integers: columns holding this types of data typically store counts, quantities, ages, and
so on. Integer‘s columns are also frequently used to contain Id numbers, such as
customers, employee. And order numbers.
Decimal numbers: columns with this type store numbers that have fractional parts and
must becalculated exactly, suchas rates and percentages.Theyarealso frequentlyused to
store money amounts.
ExtendeddataTypes
Variable-lengthCharacterstring: SQLwhichsupportsVARCHATdata.Whichallowsa
column to store character strings that vary in length from row to row, up to some maximum
length.
Datesandtimes:supportsfordate/timevalues.
Booleandata:supportslogical(TRUEorFALSE)valuesasanexplicittype.
Version-I
Level III
DataTypesDifferences
Thedifferencesb/nthedatatypesofferedinvariousSQLimplementationisoneofthepractical barriers
to the portability of SQL based applications.
Example:Date/timedataprovidesanexcellentexampleofthesesdifferences.
Date:w/cstoresadatelikeJune30,2009or30June2009
Constants
InsomeSQLstatementsanumeric,character,ordatedatavaluemustbeexpressedintextform.
Forexample:INSERTstatement,w/caddsastudenttothedatabase:
SELECT
city
FROMoffice
s
NumericWHERETARGET
constant >(1.1*SALES)+1000.00
Integersanddecimalconstants(alsocalledexactnumericliterals)arewrittenasordinarydecimal numbers in
SQL statements, with an optional leading plus or minus sign
Useacommabetweenthedigitsofanumeric constant
Version-I
Level III
String Constant
TheANSI/ISOstandardspecifiesthatSQLconstantsforcharacterdatabeenclosedinsingle quotes
(‘……’)
Ifasinglequotesistobeusedincludedintheconstanttext,itis writtenwithintheconstantastwo
consecutive single quote characters. This isconstant value:
Example:―Ican‘t‖
InSQLproductsthesupportsdate/timedata.Constantvaluesfordates,times,andtimeintervalsare
specified as string constants.The format of these constants varies from one DBMS to the next.
Example:
SELECTName,dept
FROMstudent
WHEREhire-date=To-date(‗June30,2009‘,‗monDDyyyy‘)
Expressions
ExpressionsareusedintheSQLLanguagestocalculatevaluesthatareretrievedfromthedatabaseand
to calculate values used in searching the database.
SELECTcity,target,sales,(sales/target)*100
FROMoffices
Version-I
Level III
Example2:
SELECT city
FROMoffices
WHEREsales>target+50000.00
Missingdata(NullValues)
Itisavaluewhosevalueismissing,unknown,ordon‘tapply.
SQLsupportsmissing,unknown,orinapplicable dataexplicitlythroughtheconceptsof null values.
AnullValueisanindicatorthattellsSQL(andtheuser)thatthedataismissingornot applicable.
Example:givenastudenttablebelowthathasmissingvalues
Version-I
Level III
CUSTOMER.FirstName, CUSTOMER.LastName, CUSTOMER.Street, CUSTOMER.City,
CUSTOMER.State, CUSTOMER.Zipcode, and CUSTOMER.Phone. All of these attributes are more
closely related to the customer entity than to any other entity in a database that may contain many tables.
These attributes contain all the relatively permanent customer information that your organization keeps on
file.Most database management systems provide a graphical tool for creating database tables. You use SQL
Server management studio which is a graphical tool provided by Microsoft to connect to MS SQL Server
for creating database tables You can also create such tables by using an SQL command. Since a database
contains all other objects including tables, you need to create database first before you create tables and
other objects.
The SQL CREATE DATABASE statement is used to create new SQL database.
Syntax:
Basic syntax of CREATE DATABASE statement is as follows:
CREATE DATABASE DatabaseName;
Always database name should be unique within the RDBMS.
Example:
If you want to create new database <testDB>, then CREATE DATABASE statement would be as follows:
Eg. Create database testDB
You need to execute the command to create the specified database. Once you create a database and made it
the active (currently selected) database, now you can create as many objects as you want including tables.
The following example demonstrates a command that creates your CUSTOMER table:
CREATE TABLE CUSTOMER (customerid INTEGER NOT NULL, firstname CHARACTER (15),
lastname CHARACTER (20) NOT NULL, Street CHARACTER (25), City CHARACTER (20), State
CHARACTER (2), Zipcode INTEGER, Phone CHARACTER (13) ) ;
For each column, you specify its name (for example, CustomerID), its data type (for example, INTEGER),
and possibly one or more constraints (for example, NOT NULL).
View:- At times, you want to retrieve specific information from the CUSTOMER table.
You don‘t want to look at everything — only specific columns and rows. What you need is a view.
A view is a virtual table. In most implementations, a view has no independent physical existence. The
view‘s definition exists only in the database‘s metadata, but the data comes from the table or tables from
which you derive the view. The view‘s data is not physically duplicated somewhere else in online disk
Relationships
If one table in a database contains as a foreign key a column that is a primary key in another table in the
database, you can add a constraint to the first table so that it references the second table.
Example:
CREATE TABLE CUSTOMERS(ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT
NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID) );
CREATE TABLE ORDERS (ID INT NOT NULL, O_DATE DATETIME, CUSTOMER_ID INT foreign
key references CUSTOMERS(ID),AMOUNT Decimal(8,2), PRIMARY KEY (ID));
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE CUSTOMERS(ID INT NOT NULL,NAME VARCHAR (20) NOT NULL,AGE INT
NOT NULL, ADDRESS CHAR (25),SALARY DECIMAL (18, 2), PRIMARY KEY (ID, NAME));
CHECK Constraint:
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn‘t entered into the table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
we add a CHECK with AGE column, so that you can not have any CUSTOMER below 18 years:
CREATE TABLE CUSTOMERS(ID INT NOT NULL, NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),ADDRESS CHAR (25) ,SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
SQL NOT NULL Constraint
CREATETABLEPersons
(P_IdintNOTNULL,
LastNamevarchar(255)NOTNULL, FirstName
varchar(255),
Addressvarchar(255),
City varchar(255))
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is
created:
CREATETABLEPersons (P_IdintNOTNULLUNIQUE,
Addressvarchar(255),
City varchar(255))
CREATETABLEPersons (P_IdintNOTNULL,
CONSTRAINTuc_PersonIDUNIQUE(P_Id,LastName))
The default value will be added to all new records, if no other value is specified.
The following SQL creates a DEFAULT constraint on the "City" column when the ―Persons"
table is created:
TheDEFAULTconstraintcanalsobeusedtoinsertsystemvalues,byusingfunctionslike GETDATE():
Auto-incrementallowsauniquenumbertobegeneratedwhenanewrecordisinsertedintoa table.
AUTOINCREMENTaField
Wewouldliketocreateanauto-incrementfieldinatable.
SyntaxforSQLServer
ThefollowingSQLstatementdefinesthe"P_Id"columntobeanauto-incrementprimarykey field in
the "Persons" table:
CREATETABLEPersons (
P_IdintPRIMARYKEYIDENTITY,
LastNamevarchar(255)NOTNULL, FirstName
varchar(255),
Addressvarchar(255),
City varchar(255))
TheMSSQLServerusestheIDENTITYkeywordtoperformanauto-incrementfeature.
The SQL statement above would insert a new record into the "Persons" table. The "P_Id"
columnwouldbeassignedauniquevalue.The"FirstName"columnwouldbesetto"Lars"and the
"LastName" column would be set to "Monsen".
ALTER
After you create a table, you‘re not necessarily stuck with that exact table forever. As you use the table,
you may discover that it‘s not everything you need it to be. You can use the ALTER TABLE command to
change the table by adding, changing, or deleting a column in the table. In addition to tables, you can also
ALTER columns and domains.To create a PRIMARY KEY constraint on the "ID" column when
CUSTOMERS table above already exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).
If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for
specifying a foreign key by altering a table. ALTER TABLE ORDERS ADD FOREIGN KEY
(Customer_ID) REFERENCES CUSTOMERS (ID);
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table
already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for
specifying a foreign key by altering a table.
ALTER TABLE ORDERS ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you
would write a statement similar to the following:
ALTER TABLE CUSTOMERS ADD CONSTRAINT myCheckConstraintCHECK(AGE >= 18);
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following
SQL:
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
ALTERTABLEPersons
ADDCONSTRAINTuc_PersonIDUNIQUE(P_Id,LastName)
ALTERTABLEPersons
ALTERCOLUMNCitySETDEFAULT'SANDNES'
DROP
Removing a table from a database schema is easy. Just use a DROP TABLE <tablename>command. You
erase all the table‘s data as well as the metadata that defines the table in the data dictionary. It‘s almost as
if the table never existed. Eg Drop table Customers.
Delete Primary Key:-You can clear the primary key constraints from the table, Use Syntax:
ALTER TABLE CUSTOMERS DROP PRIMARY KEY PK_CUSTID;
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS DROP FOREIGN KEYCustomer_ID;
TodropaUNIQUEconstraint,usethefollowing SQL:
ALTERTABLEPersons DROPCONSTRAINTuc_PersonID
The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.
If you want to delete an existing database <testDB>, then DROP DATABASE statement would be as
follows: Drop database testDB
The sporting goods store database contains four tables: CUSTOMER, PRODUCT, INVOICE, and
INVOICE_LINE.
Exercise Write the SQL DDL command that implements the database. Name the database
Sporting_goods.
Table Column Data type Constraint
CustomerID INTEGER Primary key
CUSTOMER
FirstName CHARACTER (15)
Zipcode INTEGER
VendorID INTEGER
InvoiceDate DATE
InvoiceNumber Integer
ProductID INTEGER
Quantity INTEGER
Notice that some of the columns in the above Table contain the constraint primary key and NOT NULL.
These columns are either the primary keys of their respective tables or columns that you decide must
contain a value. A table‘s primary key must uniquely identify each row. To do that, the primary key must
contain a nonnull value in every row. The tables relate to each other through the columns that they have in
common.
The following list describes these relationships.
The CUSTOMER table bears a one-to-many relationship to the INVOICEtable. One customer can make
multiple purchases, generating multiple invoices. Each invoice, however, deals with one and only one
customer.
The INVOICE table bears a one-to-many relationship to the INVOICE_LINEtable. An invoice may have
multiple lines, but each line appears on one and only one invoice.
The PRODUCT table also bears a one-to-many relationship to the INVOICE_LINE table. A product may
appear on more than one line on one or more invoices. Each line, however, deals with one, and only
oneproduct.
Self-Check 2
Part I: Choose the correct answer from the alternatives provided
3. Which of the following SQL statements is used to remove a table from the database?
A) REMOVE TABLE
B) DROP TABLE
C) DELETE TABLE
A) VARCHAR
B) INTEGER
C) FLOAT
D) DATE
Step 2: Create the following student table in your Sample_db database based on the information given
below.
createtable student(StudentID varchar(10) Primarykey,Name char(30)Notnull, Sex char(6)
Default'Female'check( sex='male'or sex='Female'),BirtDatedatetimeNotnull,Section char(6)
,DeptName char (40) Notnull)
STUDENT
Field Data type size Constraint
StudentID varchar 10 Primary key
Name char 30 Not null
Sex char 6 Default ―Female‖ , validate ―male‖ or
―Female‖
BirtDate datetime Not null
Section char 6
DeptName char 40 Not null
Step 3: Create the following Course table in your Sample_db database based on the information given
below.
createtable course(Course_Code varchar(8) Primarykey,Course_Title char (40)
Notnull,Creditint )
COURSE
Field Data type size Constraint
Course_Code varchar 8 Primary key
Course_Title char 40 Not null
Credit int
This unit will also assist you to attain the learning outcomes stated in the cover page.
Specifically, upon completion of this learning guide, you will be able to:
Explain Data manipulation language
Identify DML commands
Perform data manipulation using INSERT, UPDATE, and DELETE statements.
Understand the impact of these statements on the database.
The DDL is the part of SQL that creates, modifies, or destroys database structures; it doesn‘t deal with the
data. The Data Manipulation Language (DML)is the part of SQL that operates on the data. Some DML
statements read likeordinary English-language sentences and are easy to understand. Because SQLgives
you very fine control of data, other DML statements can be fiendishly
complex. If a DML statement includes multiple expressions, clauses, predicates, or subqueries,
understanding what that statement is trying to do canbe a challenge.
All the above statements would produce the following records in CUSTOMERS table:
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
INSERTINTOPersons(P_Id,LastName,FirstName) VALUES
(5, 'Tjessem', 'Jakob')
The"Persons"tablewillnowlooklikethis:
5 Tjessem Jakob
The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be
affected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not
need to use WHERE clause and UPDATE query would be as follows:
The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise all the
records would be deleted.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would DELETE a customer, whose ID is 6:
DELETE FROM CUSTOMERS WHERE ID = 6;
Now, CUSTOMERS table would have the following records:
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
If you want to DELETE all the records from CUSTOMERS table, you do not need to use
WHERE clause and DELETE query would be as follows:
A) MODIFY
B) ALTER
C) UPDATE
D) Insert
A) MODIFY
B) ALTER
C) UPDATE
D) CHANGE
3. Which SQL command is used to remove all records from a table without removing the table itself?
A) DELETE
B) TRUNCATE
C) REMOVE
D) DROP
Step 4:Create a SQL command to change the student birthdate for students that belongs to
Electrical department
update student setbithdate='4/6/1984'wheredeptname=’Electrical’
In many ways, queries are the heart of the SQL language. The SELECT statement, which is used to
express SQL queries, is the most powerful and complex of the SQL statements.
Despite the many options afforded by the SELECT statement, it's possible to start simply and then work up
to more complex queries.
The SELECT statement retrieves data from a database and returns it to you in the form of query results.
SELECTcolumn_name(s)
FROM table_name
and
SELECT*FROMtable_name
Note:SQLisnotcasesensitive.SELECTisthesameasselect.
SELECTLastName, FirstNameFROMPersons
Theresult-setwilllooklikethis:
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
SELECT * Example
SELECT*FROMPersons
NavigationinaResult-set
Mostdatabasesoftwaresystemsallownavigationintheresult-setwithprogrammingfunctions, like:
Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.
Programmingfunctionslikethesearenotapartofthistutorial.
SQLSELECTDISTINCTStatement
TheDISTINCTkeywordcanbeusedtoreturnonlydistinct(different)values.
SELECTDISTINCTcolumn_name(s) FROMtable_name
SELECTDISTINCTExample: The"Persons"table:
WeusethefollowingSELECTstatement:
SELECTDISTINCTCityFROMPersons
Theresult-setwilllooklikethis:
City
Sandnes
TheWHEREclauseisusedtoextractonlythoserecordsthatfulfillaspecifiedcriterion.
SQLWHERESyntax
SELECTcolumn_name(s)
FROM table_name
WHEREcolumn_nameoperatorvalue
WHEREClauseExample
The"Persons"table:
QuotesaroundTextFields
SQLusessinglequotesaroundtextvalues(mostdatabasesystemswillalsoacceptdouble quotes).
Although,numericvaluesshouldnotbeenclosedinquotes. For
Thisiscorrect:
SELECT*FROMPersonsWHEREFirstName='Tove'
Ministry of Labor and Skills ThisQuery
Basic Structure Version-I
is wrong:
Page 85 of 119 Author/Copyright November, 2023
LanguageLevel III
SELECT*FROMPersonsWHEREFirstName=Tove
text values:
Fornumericvalues:
Thisiscorrect:
SELECT*FROMPersonsWHEREYear=1965 This
is wrong:
SELECT*FROMPersonsWHEREYear='1965'
OperatorsAllowedintheWHERE Clause
WiththeWHEREclause,thefollowingoperatorscanbeused:
Operator Description
= Equal
<> Not equal
> Greaterthan
< Lessthan
>= Greaterthanorequal
<= Lessthan orequal
BETWEE Betweenaninclusiverange
N
LIKE Searchfora pattern
IN Ifyouknowtheexactvalueyouwanttoreturnforatleastoneofthe columns
Note:InsomeversionsofSQLthe<>operatormaybewrittenas!=
SQLAND&OR Operators
TheANDoperatordisplaysarecordifboththefirstandthesecondconditionistrue.
TheORoperatordisplaysarecordifeitherthefirstconditionorthesecondconditionistrue.
ANDOperatorExample
The"Persons"table:
WeusethefollowingSELECTstatement:
Theresult-setwilllooklikethis:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn23 Sandnes
OROperatorExample
WeusethefollowingSELECTstatement:
Theresult-setwilllooklikethis:
CombiningAND&OR
YoucanalsocombineANDandOR(useparenthesistoformcomplexexpressions).
Nowwewant toselect onlythepersonswiththelastnameequalto "Svendson"ANDthefirst name
equal to "Tove" OR to "Ola":
WeusethefollowingSELECTstatement:
SELECT*FROMPersonsWHERE LastName='Svendson'
AND(FirstName='Tove'ORFirstName='Ola')
Theresult-setwilllooklikethis:
SQLORDERBYKeyword
TheORDERBYkeywordisusedtosorttheresult-set.
TheORDERBYkeywordisusedtosorttheresult-setbyaspecifiedcolumn. The
ORDER BY keyword sort the records in ascending order by default.
If youwanttosorttherecordsinadescendingorder,youcanusetheDESCkeyword.
SQLORDERBYSyntax
ORDERBYcolumn_name(s)ASC|DESC
ORDERBYExample
The"Persons"table:
WeusethefollowingSELECTstatement:
SELECT*FROMPersons
ORDER BY LastName
Theresult-setwilllooklikethis:
ORDERBYDESCExample
Theresult-setwilllooklikethis:
SQLUPDATEStatement
TheUPDATEstatementisusedtoupdateexistingrecordsinatable.
SQLUPDATESyntax
UPDATEtable_name
SETcolumn1=value,column2=value2,... WHERE
some_column=some_value
Note:NoticetheWHEREclauseintheUPDATEsyntax.TheWHEREclausespecifieswhich record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
The"Persons"table:
5 Tjessem Jakob
Nowwewanttoupdatetheperson"Tjessem,Jakob"inthe"Persons"table. We use
the following SQL statement:
UPDATEPersons
SETAddress='Nissestien67',City='Sandnes'
WHERELastName='Tjessem'ANDFirstName='Jakob'
The"Persons"tablewillnowlooklikethis:
SQLUPDATEWarning
UPDATEPersons
SETAddress='Nissestien67',City='Sandnes'
The"Persons"tablewouldhavelookedlikethis:
P_Id LastName FirstName Address City
SQLDELETEStatement
TheDELETEstatementisusedtodeleterows/recordsinatable.
SQLDELETESyntax
Note:NoticetheWHEREclauseintheDELETEsyntax.TheWHEREclausespecifieswhich record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
SQLDELETEExample
The"Persons"table:
Nowwewanttodeletetheperson"Tjessem,Jakob"inthe"Persons"table. We use
the following SQL statement:
DELETEFROMPersons
WHERELastName='Tjessem'ANDFirstName='Jakob'
The"Persons"tablewillnowlooklikethis:
DeleteAllRows
DELETEFROMtable_nameor
DELETE*FROMtable_name
Note:Beverycarefulwhendeletingrecords.Youcannotundothisstatement!
1. CharacterandStringComparisonOperators:
=(Equalto):Comparesiftwocharacterorstringvaluesareidentical.
LIKE:Comparesacharacterorstringvaluewith apattern,oftenusingwildcardcharacters (%
and _).
Example:
DateandTimeComparisonOperators:
=(Equalto):Comparesiftwodateortimevaluesareequal.
!=or<>(Notequalto):Comparesiftwodateortimevaluesarenotequal.
<(Lessthan):Checksifonedateortimevalueisearlierthananother.
>(Greaterthan):Checksifonedateortimevalueislaterthananother.
<=(Lessthanorequalto):Checksifonedateortimevalueisearlierthanorequalto another.
>=(Greaterthanorequalto):Checksifonedateortimevalueislaterthanorequalto another.
Example:
When using these comparison operators in your SQL queries, be sure to match the data types
appropriately. For example, when comparing dates, make sure the date format matches the one
used in your database. Also, consider the collation (sorting and comparison rules) for character
and string data when using comparison operators for text-based data.
Using parentheses is especially important when combining AND and OR operators in the same
query to make your intentions explicit and avoid unexpected behavior.
2. Checkingforarangeofvalues
Youcanusecomparisonoperatorstofilterrowsbasedonarangeofvalues.Forexample,to retrieve
products with prices between $50 and $100:
SELECT*FROMproductsWHEREprice>=50ANDprice<=100;
Selectingvaluesfromalist
You can use the IN operator to filter rows based on a list of values. For example, to retrieve
orders from customers in New York or California:
SELECT*FROMordersWHEREcustomer_stateIN('NewYork','California');
This query retrieves rows from the "orders" table where the "customer_state" is either 'New
York' or 'California'.
CheckingforValuesthatMatchaPattern
Version-I
Level III
You can use the LIKE operator with wildcard characters to match values that fit a specific
pattern. For example, to retrieve products with names starting with 'Laptop':
SELECT*FROMproductsWHEREproduct_nameLIKE'Laptop%';
This query retrieves rows from the "products" table where the "product_name" starts with
'Laptop'. The '%' wildcard matches any sequence of characters, so it matches 'Laptop,' 'Laptop
Pro,' 'Laptop 2023,' and so on.
You can also use the NOT LIKE operator to exclude rows that match a particular pattern. For
example, to retrieve products with names that don't start with 'Accessory':
SELECT*FROMproductsWHEREproduct_nameNOTLIKE'Accessory%';
Thisqueryretrievesrowswherethe"product_name"doesnotstartwith'Accessory'.
These SQL techniques are commonly used to filter and retrieve specific data from a database
based on various criteria, making it easier to work with the data that meets your specific
requirements.
Takingactiontoexecutenullvaluesfromaqueryresult
In SQL, you can take action to handle and filter out null values from a queryresult using the IS
NULL and IS NOT NULL operators. Here's how you can use them:
3. FilteringRowswithNullValues(ISNULL):
Toretrieverowsthatcontainnullvaluesinaspecificcolumn,youcanusetheISNULL
operator.Forexample,toretrieveallproductswithnullvaluesinthe"description"column:
Version-I
Level III
Thisquerywillreturnrowswherethe"description"columnisnull.
FilteringRowswithoutNullValues(ISNOTNULL):
To retrieve rows that do not contain null values in a specific column, you can use the IS NOT
NULL operator. For example, to retrieve all products with a non-null value in the "price"
column:
SELECT*FROMproductsWHEREpriceISNOTNULL;
Thisquerywillreturnrowswherethe"price"columnisnotnull.
HandlingNullValuesintheResult(COALESCE):
If you want to replace null values in the query result with a specific default value, you can use
the COALESCE function. For example, if you want to replace null values in the "description"
column with "No description available":
SELECTproduct_name,COALESCE(description,'Nodescriptionavailable')ASdescription
FROM products;
This query uses the COALESCE function to replace null values with the specified default
value in the result set.
Handling null values is important to ensure the accuracy and completeness of your query
results. Themethodsmentioned aboveallow youto filter andmanagenull values effectivelyin
yourSQL queries.
MDXsupportsthearithmeticoperatorslistedinthefollowingtable.
Operator Description
Version-I
Level III
+ (Add) Addstwonumbers.
/ (Divide) Dividesonenumberbyanothernumber.
*(Multiply) Multipliestwonumbers.
- (Subtract) Subtractstwonumbers.
^(Power) Raisesonenumberbyanothernumber.
Orderof Precedence
ThefollowingrulesdeterminetheorderofprecedenceforarithmeticoperatorsinanMDX expression:
Whenthereismorethanonearithmeticoperatorinanexpression,MDXperforms
multiplication and division first, followed by subtraction and addition.
Whenallarithmeticoperatorsinanexpressionhavethesamelevelofprecedence,the order of
execution is left to right.
Expressionswithinparenthesestakeprecedenceoverallotheroperations.
In SQL, you can perform arithmetic operations using operators such as +, -, *, and /. It's
important to understand operator precedence when combining multiple operators in an
expression.
Version-I
Level III
Example: Suppose you have a table called "Products" with columns "Price" and
"Quantity."You want to calculate the total cost for each product, considering the unit price and
quantity. The SQL statement would be:
In this example, the * operator is used to multiply the "Price" and "Quantity" columns to obtain
the "TotalCost."
UsingStringFunctionsandOperators:
SQL provides various string functions and operators for working with text data. For
instance,you can use the CONCAT function to concatenate strings.
Example:
UsingMathematicalFunctions:
SQLoffersmathematicalfunctionsforperformingoperationslikerounding,absolutevalue, square
root, etc.
Example:
Version-I
Level III
Suppose you have a table called "Orders" with a "TotalAmount" column. You want to calculate
the square root of the total amount. The SQL statement would be:
Inthisexample,theSQRTfunctioncalculatesthesquarerootofthe"TotalAmount."
UsingDateFunctions:
SQLprovidesvariousdatefunctionsforworkingwithdateandtimedata. Example:
Suppose you have a table called "Events" with a "EventDate" column, and you want to find the
events that occurred within the last 30 days. The SQL statement would be:
UsingSQLAggregateFunctions:
SQLaggregatefunctionsareusedtoperformcalculationsonsetsofvalues.
AVG()-TheAVG()functionreturnstheaveragevalueofanumericcolumn.
AVG()Syntax
Example
Version-I
Level III
COUNT()–TheCOUNT()functionreturnsthenumberofrowsthatmatchesaspecified criterion.
COUNT()Syntax
Example
MIN()-Returnsthesmallestvalue
SUM()-TheSUM()functionreturnsthetotalsumofanumericcolumn.
SUM()Syntax
WHEREcondition;
Example:
Version-I
Level III
In this example, the SUM function calculates the total sales for orders placed between
January1, 2023, and December 31, 2023.
These examples demonstrate the use of arithmetical, string, mathematical, date, and
aggregate functions in SQL queries to obtain the desired query output, depending on the
data and calculations you need.
SQLstatementsthatuseaggregationandfiltering
UsingClausetoAggregateDatabyMultipleColumns:
When you want to aggregate data based on multiple columns, you can use the GROUP BY
clause. This clause allows you to group rows by one or more columns and apply aggregate fun
SQL
GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns.
SQLGROUPBYSyntax
Version-I
Level III
SELECTcolumn_name,aggregate_function(column_name)
FROMtable_name
WHEREcolumn_nameoperatorvalue
GROUPBYcolumn_name
SQLGROUPBYExample1
Wehavethefollowing"Orders"table:
O_Id OrderDate OrderPrice Customer
Nowwewanttofindthetotalsum(totalorder)ofeachcustomer.
GROUPBYCustomer
Version-I
Level III
Theresult-setwilllooklikethis:
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
Nowwewanttofindifthecustomers"Hansen"or"Jensen"haveatotalorderofmorethan 1500.
Having clause
WeaddanordinaryWHEREclausetotheSQLstatement:
SELECTCustomer,SUM(OrderPrice)FROMOrders
GROUPBYCustomer
HAVINGSUM(OrderPrice)>1500
Theresult-setwilllooklikethis
Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000
WecanalsousetheGROUPBYstatementonmorethanonecolumn,likethis:
Version-I
Level III
Suppose you have a table called "Sales" with columns "Product," "Region," and "Revenue." To
aggregate data by both "Product" and "Region" and calculate the total revenue for each
combination, you can use the following SQL statement:
In this example, the data is grouped by both "Product" and "Region," and the SUM function
is applied to calculate the total revenue for each group.
SortingAggregateDatainQueryOutput:
You can sort the aggregate data in the query output using the ORDER BY clause. This
allows you to specify the order in which the results should be displayed.
Use ORDER BY if you want to order rows according to a value returned by an aggregate
function likeSUM(). The ORDER BY operator is followed by the aggregate function (in
our example,SUM()). DESC is placed after this function to specify a descending sort order.
Thus, the highest aggregate values are displayed first, then progressively lower values are
displayed. To sort inascendingorder, you can specifyASC or simplyomit eitherkeyword, as
ascendingis the default sort order.
Version-I
Level III
Example1:
Continuing with the "Sales" table, if you want to see the total revenue for each product and
region combination, sorted in descending order of revenue, you can use the following SQL
statement:
In this example, the data is first aggregated, and then the results are sorted in descending
order of the "TotalRevenue" column.
FilteringAggregateDataUsingtheHAVINGClause:
The HAVING clause is used to filter the results of aggregate functions. It allows you to specify
conditions that the aggregated data must meet.
SQLHAVINGSyntax
SELECTcolumn_name,aggregate_function(column_name)
FROMtable_name
WHEREcolumn_nameoperatorvalue
GROUPBYcolumn_name
HAVINGaggregate_function(column_name)operatorvalue
SQLHAVINGExample1
Version-I
Level III
Wehavethefollowing"Orders"table:
SELECTCustomer,SUM(OrderPrice)FROMOrders GROUP
BY Customer
HAVINGSUM(OrderPrice)<2000
following SQL statement:
Theresult-setwilllooklikethis:
Customer SUM(OrderPrice)
Nilsen 1700
Example2:
Supposeyouwanttofindproduct-regioncombinationswithatotalrevenuegreaterthan
$10,000.YoucanusethefollowingSQLstatement:
SELECTProduct,Region,SUM(Revenue)ASTotalRevenue FROM Sales
HAVINGTotalRevenue>10000;
In this example, the HAVING clause filters the results to include only those
combinationswhere the "TotalRevenue" is greater than $10,000.
These SQLstatements demonstrate how to aggregate data, sort the results, and filter
aggregated datausingthe GROUP BY,ORDER BY, and HAVING clauses, respectively.
Theseclausesare essential for summarizing and manipulating data in SQL queries.
ASubquery or Inner query or Nested query is a query within another SQL query and embedded within
the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN etc.
Self-check 4
Part I: Choose the correct answer
A) SEARCH
B) EXTRACT
C) SELECT
D) RETRIEVE
D) To join tables
A) Combine
B) Concatenate
C) Merge
D) List
Step 1. Write a query to display the student information for all students.
select*from student
Step 2. Write a query that displayscourse_code and course_title fromthe Course table.
selectCourse_code,Course_titlefrom course
Step 3. Write a query to display the student name for all students those who score grades ‗B‘.
SELECTstudent.Name,grade_report.GradeFROM course
INNERJOINgrade_reportONcourse.Course_Code=grade_report.Course_CodeINNERJOIN
student ONgrade_report.StudentID=student.StudentID
WHERE (grade_report.Grade='B')
Step 4. Write a query to display the student ID and name for all male students those who score
grades ‗A‘ and who learn in Java course.
SELECT student.StudentID, student.NameFROM course INNER JOIN
grade_report ON course.Course_Code = grade_report.Course_Code INNER JOIN student ON
grade_report.StudentID = student.StudentIDWHERE (student.Sex = 'male') AND
(course.Course_Code = 'ICT002') AND (grade_report.Grade = 'A')
Step 5. Write a query to display the student for all students those who score grades ‗A‘ and
who learn in computer science department, then sort by Department name descending and
name ascending order.
Step 7. Write a query to display the student for all students those who score grades between
‗A‘ and ‗D‘ and who learn in PhP course.
select*from student
whereStudentIDin(selectdistinctStudentIDfromgrade_reportwhereCourse_Code='ICT001'and
grade='A'orCourse_Code='ICT001'and grade='b'orCourse_Code='ICT001'and
grade='c'orCourse_Code='ICT001'and grade='d')
Step 8. Write a query to display the student ID and name for all students who study in a
computer science department with any student whose name contains a ‗T‘.
SELECTstudentid,NAMEFROM student WHEREDeptName='Computer Science'or Name LIKE'%T%'
Step 9.Write a query to display the student information who didn‘t take a course.
Step 10. Write a query to display the student information who didn‘t scorec.
select * from student where StudentID in(select studentID from grade_report where grade<>'c' )
Step 11. Write a query that displays only the unique grade letters.
Step 12. Write a query that displays studentid and no of course for students who takes more
than one course.
selectstudentID,count(*)total fromgrade_reportgroupbystudentidhavingcount(*)>1
select * from student where StudentID in(select studentID from grade_report group by
studentid having count(*)>1 )
Lap Test
Instruction: Use ABC database (from unit three lap test) in order to perform the following tasks
Task 1: Display customers first name and last name whose country is Addis ababa
Task 2: Multiply total amount column by 1.1 to get the tax included amount and display as
tax_included_amount
Task 3: Delete customer_order whose order number ORD123
Task 4: Update the City of a customer in to Addis ababa whose last name is Haregawi
Task 6:Group orders by CustomerId and calculate the total amount for each customer
Task 7:Retrieve the maximum total amount from customer_Order using a subquery
Fundamental_of_Database_Systems
a_taylor_sql_for_dummies_2003
Database-Design-2nd-Edition-1660153697
SQL_All-in-One_For_Dummies.pdf
URL
https://www.tutorialspoint.com/
https://www.w3schools.com/sql/default.asp#gsc.tab=0&gsc.q=date%20functions%20sql
http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/sql/sql_select.asp.html
Qualificatio Organization/
No Name Field of Study Mobile number E-mail
n Institution
Version-I
Level III