6. SQL DML-Functions
DML Functions in SQL
Section titled “DML Functions in SQL”DML (“Data Manipulation Language”) functions are special functions provided by SQL to perform operations on data within the database. These functions can be used in various SQL statements such as SELECT, INSERT, UPDATE, and DELETE to manipulate and retrieve data effectively.
In this chapter, we will explore some of the most commonly used DML functions in SQL. After basic table operations, these commands are essential for working with data in a relational database.
The approach follows the well known CRUD paradigm:
- Create - Inserting new data into tables using the
INSERTstatement. - Read - Retrieving data from tables using the
SELECTstatement. - Update - Modifying existing data in tables using the
UPDATEstatement. - Delete - Removing data from tables using the
DELETEstatement.
The example table we will use throughout this chapter is as follows:
CREATE TABLE students ( student_id SERIAL PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(320) UNIQUE NOT NULL, birth_date DATE, class VARCHAR(10));CREATE TABLE students ( student_id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(320) UNIQUE NOT NULL, birth_date DATE, class VARCHAR(10));Insert Data
Section titled “Insert Data”A database table can be populated with data using the INSERT INTO statement. The basic syntax is as follows:
INSERT INTO table_name (column1, column2, column3, ...)VALUES (value1, value2, value3, ...) [, (value1, value2, value3, ...), ...];Example - Inserting a new student into the students table:
INSERT INTO students (first_name, last_name, email, birth_date, class)If not all values are known at the time of insertion, the columns can be omitted, and the database will assign default values (e.g., NULL or auto-incremented IDs):
Example - Inserting a new student with only the mandatory email field:
INSERT INTO students (first_name, last_name, email)You may also rearrange the order of columns in the INSERT statement as long as the values correspond correctly.
Example - Inserting a new student with rearranged columns:
INSERT INTO students (email, last_name, first_name, class)Finally, you can insert multiple rows in a single INSERT statement by separating the value sets with commas:
Example - Inserting multiple students at once:
INSERT INTO students (first_name, last_name, email, birth_date, class)VALUESRead Data
Section titled “Read Data”To retrieve data from a database table, the SELECT statement is used. The basic syntax is as follows:
SELECT column1, column2, column3, ...FROM table_name[WHERE condition];Example - Selecting all students:
SELECT student_id, first_name, last_name, email, birth_date, classFROM students;If you want to select all columns from a table, you can use the asterisk (*) wildcard:
SELECT *FROM students;The WHERE clause allows you to filter the results based on specific conditions.
Example - Selecting students from class ‘4A’:
SELECT *FROM studentsWHERE class = '4A';The WHERE clause can also use various operators such as =, <>, <, >, <=, >=, LIKE, IN, BETWEEN, EXISTS, NOT EXISTS, and logical operators like AND, OR, and NOT to create complex conditions.
Example - Selecting students born after January 1, 2011, in class ‘4B’:
SELECT *FROM studentsWHERE birth_date > '2011-01-01' AND class = '4B';Example - Selecting students with last names starting with ‘K’:
SELECT *FROM studentsWHERE last_name LIKE 'K%';Example - Selecting student’s name and email whose name is not ‘Alice’:
SELECT first_name, last_name, emailFROM studentsWHERE first_name <> 'Alice';Example - Selecting email addresses of students which are in class 4A or 4B:
SELECT emailFROM studentsWHERE class IN ('4A', '4B');Example - Selecting all students born in the year 2010:
SELECT *FROM studentsWHERE birth_date BETWEEN '2010-01-01' AND '2010-12-31';Sorting Results with ORDER BY
Section titled “Sorting Results with ORDER BY”By default, a database may return rows in any order — there is no guarantee that they come back the way you inserted them. To get a predictable order, add an ORDER BY clause at the end of your query.
SELECT first_name, last_name, birth_dateFROM studentsORDER BY last_name;By default, sorting is ascending (ASC): A → Z for text, small → large for numbers, oldest → newest for dates. To reverse it, use DESC (descending).
Example - Youngest student first (most recent birth date on top):
SELECT first_name, last_name, birth_dateFROM studentsORDER BY birth_date DESC;You can also sort by several columns. The result is sorted by the first column; rows that share the same value are then sorted by the next column.
Example - Sort by class first, and within each class alphabetically by last name:
SELECT class, last_name, first_nameFROM studentsORDER BY class ASC, last_name ASC;Removing Duplicates with DISTINCT
Section titled “Removing Duplicates with DISTINCT”Sometimes the same value appears in many rows, but you only want to see each value once. The keyword DISTINCT removes duplicate rows from the result.
Example - Without DISTINCT, every student’s class is listed, so “4A” and “4B” appear many times:
SELECT classFROM students;Example - With DISTINCT, each class is listed only once:
SELECT DISTINCT classFROM students;DISTINCT looks at all selected columns together. SELECT DISTINCT class, first_name keeps every unique combination of class and first name, not just unique classes.
Limiting the Number of Rows with LIMIT
Section titled “Limiting the Number of Rows with LIMIT”Tables can hold thousands or even millions of rows. Often you only want to see a few — for example the “top 3”, or just a quick peek at the data. The LIMIT clause restricts how many rows are returned.
Example - Return at most 5 students:
SELECT *FROM studentsLIMIT 5;LIMIT is especially useful together with ORDER BY to answer “top N” questions.
Example - The three youngest students:
SELECT first_name, last_name, birth_dateFROM studentsORDER BY birth_date DESCLIMIT 3;Update Data
Section titled “Update Data”To modify existing data in a database table, the UPDATE statement is used. The basic syntax is as follows:
UPDATE table_nameSET column1 = value1, column2 = value2, ...[WHERE condition];Example - Updating a student’s email address:
UPDATE studentsWHERE student_id = 1;You can update more than one row at a time by specifying a condition in the WHERE clause which matches multiple records.
Example - Updating the class of all students born before 2011 to ‘3A’:
UPDATE studentsSET class = '3A'WHERE birth_date < '2011-01-01';Also more than one column can be updated in a single UPDATE statement.
Example - Updating both the first name and last name of a student:
UPDATE studentsWHERE student_id = 1;Delete Data
Section titled “Delete Data”To remove data from a database table, the DELETE statement is used. The basic syntax is as follows:
DELETE FROM table_name[WHERE condition];Example - Deleting a student by their ID:
DELETE FROM studentsWHERE student_id = 1;You can delete multiple rows by specifying a condition in the WHERE clause that matches multiple records.
Example - Deleting all students from class ‘4A’:
DELETE FROM studentsWHERE class = '4A';SQL Functions
Section titled “SQL Functions”So far we have read values exactly as they are stored. But SQL can also transform values while it reads them. A function takes one or more input values and returns a new value. Functions can be used almost anywhere you can write a column name — most often in the SELECT list (to change how a value is displayed) or in the WHERE clause (to filter on a calculated value).
The original data in the table is never changed by these functions — only the result of the query is affected.
Text Functions
Section titled “Text Functions”These functions work on strings (text).
| Function | Description | Example | Result |
|---|---|---|---|
UPPER(text) | Converts to upper case | UPPER('Alice') | 'ALICE' |
LOWER(text) | Converts to lower case | LOWER('Alice') | 'alice' |
LENGTH(text) | Number of characters | LENGTH('Alice') | 5 |
TRIM(text) | Removes leading/trailing spaces | TRIM(' hi ') | 'hi' |
SUBSTRING(text, start, length) | Extracts part of a string | SUBSTRING('Database', 1, 4) | 'Data' |
Joining (concatenating) two strings is so common it has its own operator. In PostgreSQL, MariaDB, and MySQL you can use ||; many systems (and the SQL standard) also offer the CONCAT(...) function:
-- Display the full name as a single columnSELECT first_name || ' ' || last_name AS full_nameFROM students;
-- The same using CONCAT (works in MariaDB/MySQL and PostgreSQL)SELECT CONCAT(first_name, ' ', last_name) AS full_nameFROM students;Example - Find students whose last name starts with “k”, regardless of upper or lower case:
SELECT first_name, last_nameFROM studentsWHERE LOWER(last_name) LIKE 'k%';Numeric Functions
Section titled “Numeric Functions”These functions work on numbers.
| Function | Description | Example | Result |
|---|---|---|---|
ROUND(num, digits) | Rounds to a number of decimals | ROUND(3.14159, 2) | 3.14 |
ABS(num) | Absolute value (removes the sign) | ABS(-7) | 7 |
CEIL(num) | Rounds up to the next integer | CEIL(4.1) | 5 |
FLOOR(num) | Rounds down to the next integer | FLOOR(4.9) | 4 |
MOD(a, b) | Remainder of a division | MOD(10, 3) | 1 |
Example - Show each product price rounded to whole euros (using a products table):
SELECT name, ROUND(price, 0) AS rounded_priceFROM products;Date and Time Functions
Section titled “Date and Time Functions”These functions help you work with dates — for example, to read the year out of a date, or to get today’s date.
| Function | Description |
|---|---|
CURRENT_DATE | Today’s date |
NOW() | Current date and time |
EXTRACT(YEAR FROM date) | Reads a part (year, month, day) out of a date |
Reading the year out of a date is a good example of a dialect difference:
-- PostgreSQL (SQL standard)SELECT first_name, EXTRACT(YEAR FROM birth_date) AS birth_yearFROM students;
-- MariaDB / MySQL (shorter helper function)SELECT first_name, YEAR(birth_date) AS birth_yearFROM students;Example - Find all students who were born in the year 2010:
-- PostgreSQLSELECT first_name, last_nameFROM studentsWHERE EXTRACT(YEAR FROM birth_date) = 2010;
-- MariaDB / MySQLSELECT first_name, last_nameFROM studentsWHERE YEAR(birth_date) = 2010;This concludes our introduction to data manipulation in SQL. You can now insert, read (including sorting with ORDER BY, removing duplicates with DISTINCT, and limiting results with LIMIT), update, and delete data — and reshape values on the fly with built-in functions. In the following chapters, we will explore more advanced SQL features and techniques for working with relational databases.
Learning Outcomes: What you should be able to do after this chapter
Section titled “Learning Outcomes: What you should be able to do after this chapter”After completing this chapter, students should be able to:
- Name: name the DML commands
INSERT,SELECT,UPDATEandDELETE. - Describe: describe the structure of a
SELECTquery and the effect of the DML commands. - Apply: insert, query, update and delete data and apply SQL functions (string, date and numeric functions).
- Analyze: analyze the effect of an
UPDATEorDELETEstatement without aWHEREclause. - Evaluate: assess which SQL function is suitable for a given data preparation task.