Course

Creating a Table - Clauses

You've learned to use constraints to set a default timestamp. But what if we wanted an "updatedAt" field that reflected when the last change was?

Do we need to do it in our code when we make updates to the row in the table? Not at all! There's a fourth part to our fields besides the name, type, and constraints. It's called a 'clause', and it's like a special instruction that we can attach to certain data types to define additional behavior or functionality.

Clauses allow us to automate things in our database based on certain actions.

For instance, if we add an "ON UPDATE" clause to a new field called 'updatedAt' in our table:

updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

The 'ON UPDATE CURRENT_TIMESTAMP' is our 'Clause'

Image

It means "On every update to this entry- set this value to 'CURRENT_TIMESTAMP'"

ID (INT)name (VARCHAR)email (VARCHAR) (UNIQUE)updatedAt (TIMESTAMP)
1Amirsame@email.com2024-04-17 21:10:52
2Jackiejackie@email.com2024-04-17 21:10:52
ID (INT)name (VARCHAR)email (VARCHAR) (UNIQUE)updatedAt (TIMESTAMP)
2Jackjackie@email.com2024-04-17 21:10:52
ID (INT)name (VARCHAR)email (VARCHAR) (UNIQUE)updatedAt (TIMESTAMP)
1Amirsame@email.com2024-04-17 21:10:52
2Jackjackie@email.com2024-04-17 21:10:52

Putting it all together we have this:

CREATE TABLE Users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

And we can now begin inserting some data!

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Inserting Data