Apache Derby: 4 useful commands

Well, if you haven't heard of SQL, then this post is definitely not for you! You might want to visit http://w3schools.org/sql to learn the ropes!!


On the other hand, if you are one of those geniuses who have executed a simple SELECT, INSERT, UPDATE or DROP statement, then this is absolutely designed for you ;)


I am working with the Apache Derby database (also known as Java DB) and since tutorials on this one is hard to get, I am writing one of my own!!


Here are the top few tutorials and "hacks" that might help you like Apache Derby! I know that blank theory is like verse without prose, which is why I have explained only through examples. 


1. Create an auto-increment column in Apache Derby:
An auto-increment column would be useful in cases when you want to generate unique IDs for every row. A good instance would be a student database where each student would have a primary key as a STUDENT_ID and you don't want to take the dumb initiative of increasing the ID value manually.
This might come in handy for you! 


CREATE TABLE STUDENTS 
(
STUDENT_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
STUDENT_NAME VARCHAR(40),
STUDENT_GRADE TINYINT
)
 Of course, the warning I would like to give you is that the 'generated' keyword for the STUDENT_ID column cannot be modified no matter what!

2. Reset!
This is a good scenario:
You are designing a social network and after some days realize that all of the created accounts in your database are spammed!! Well, what would you do? Make arrangements to prevent spam (I don't know how) and then reset all your database data. 
Most of the folks would be happy by doing a DELETE FROM NETWORK_USERS or something like that.
However, what if you had a column that generated auto-incremented data and you wanted it to start from 1?

TRUNCATE TABLE NETWORK_USERS

One line statement that deletes the table and then re-creates it automatically!! Now that might come in handy!

3. Foreign keys!
The simplest and mostly the only way of making a column a foreign key in Derby would be by using a command like this:

ALTER TABLE APP.EMPLOYEE
ADD FOREIGN KEY (DNO)
REFERENCES APP.DEPARTMENT(DNUMBER)

However, note that the column named DNO must have already been created in the table!