Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Friday, June 12, 2015

MySQL Commands

Login via MySql client:
$ mysql -u XXXXX -pXXXXX db_name
Create a new user:
CREATE USER 'user1'@'localhost' IDENTIFIED BY 'pass1';
GRANT ALL ON
*.* TO 'user1'@'localhost';
CREATE USER
'user1'@'%' IDENTIFIED BY 'pass1';
GRANT ALL ON
*.* TO 'user1'@'%';
List users:
select host, user, password, Create_priv from mysql.user;
List databases and tables:
show databases;
show tables
;
Rename column:
ALTER TABLE Article change article_id id bigint(20);
Make column non-null:
ALTER TABLE Person MODIFY firstName varchar(255) NOT NULL;
Make column unique:
ALTER TABLE Person ADD UNIQUE INDEX(memberId);
Calculate the database size:
SELECT table_schema "DB Name", sum(data_length + index_length) / 1024 / 1024  "DB size in MB" FROM information_schema.TABLES GROUP BY table_schema;

Sunday, May 17, 2015

Write a SQL Program to Swap the values in a single update query.

Given a Student table, Swap all Male to Female value and vice versa with a single update query.

Id Name Sex Salary
----------------------------
1 Ranga Male 2500
2 Vasu Female 1500
3 Raja Male 5500
4 Amma Female 500

Program:
------------------------
UPDATE Gender SET sex = CASE sex WHEN 'Male' THEN 'Female' ELSE 'Male' END

Write a SQL Program to Select every Nth record.

CREATE TABLE student(id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male'),
(10 ,null, 27, 'Male');

Program:
-----------------------------------------------
SELECT * FROM (
SELECT @row := @row +1 AS Rownum, name as Name FROM (SELECT @row :=0) r, student
) students
WHERE rownum %3 = 1;

Output:
-----------------------------------------------
Rownum Name
1 Ranga
4 Ranga
7 Vinod
10 (null)

Write a SQL Program to get the Sum value of same column with different conditions.

CREATE TABLE student(id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male');

Query:
-----------------------------------
SELECT SUM(CASE WHEN s.gender = 'Male' THEN 1 ELSE 0 END) AS MaleCount,
SUM(CASE WHEN s.gender = 'Female' THEN 1 ELSE 0 END) AS FemaleCount
FROM
student s;

Output:
------------------------------
MaleCount FemaleCount
4 2

Write a SQL Program to Get the Next and Previous values based on Current value?

CREATE TABLE student (id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male');

Query:
-----------------------------------
SELECT name as Name,
(SELECT name FROM student s1
WHERE s1.id < s.id
ORDER BY id DESC LIMIT 1) as Previous_Name,
(SELECT name FROM student s2
WHERE s2.id > s.id
ORDER BY id ASC LIMIT 1) as Next_Name
FROM student s
WHERE id = 7;

Output:
------------------------------------------------------
Name Previous_Name Next_Name
Vinod Pavi Vasu

How to get the Duplicate and Unique Records by using SQL Query?

CREATE TABLE student (id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male');

Getting the duplicate records:
---------------------------------------
SELECT DISTINCT name AS Name, COUNT(name) as Count FROM student GROUP BY name HAVING COUNT(name) > 1;

Output:
---------------------------------------
Name Count
Ranga 3
Vasu 2

Getting the Unique records:
---------------------------------------
SELECT DISTINCT name AS Name FROM student GROUP BY name;

Output:
---------------------------------------
Name
Pavi
Raja
Ranga
Reddy
Vasu
Vinod

What is the output of the following SQL Program. SELECT CASE WHEN null = null THEN 'I LOVE YOU RANGA' ELSE 'I HATE YOU RANGA' end as Message;

SELECT CASE WHEN null = null THEN 'I LOVE YOU RANGA' ELSE 'I HATE YOU RANGA' end as Message;
Output: 'I HATE YOU RANGA'
The reason for this is that the proper way to compare a value to null in SQL is with the is operator, not with =.
SELECT CASE WHEN null IS null THEN 'I LOVE YOU RANGA' ELSE 'I HATE YOU RANGA' end as Message;
Output: 'I LOVE YOU RANGA'

Write a SQL Program to generate the following output?

Input:
Employee:
Department:
Output:
Creating tables and inserting Data:
CREATE TABLE Employee (
e_id INT NOT NULL AUTO_INCREMENT,
e_name VARCHAR(100) NOT NULL,
age tinyint NOT NULL,
PRIMARY KEY (e_id)
);

CREATE TABLE Department (
d_id INT NOT NULL AUTO_INCREMENT,
d_name VARCHAR(100) NOT NULL,
e_id INT NOT NULL,
PRIMARY KEY (d_id),
FOREIGN KEY (e_id)
REFERENCES Employee(e_id)
ON DELETE CASCADE
);

INSERT INTO Employee VALUES (1,'Ranga', 27), (2, 'Raja', 50), (3, 'Vasu',45) ,
(4, 'Vinod', 27), (5, 'Manoj',27);

INSERT INTO Department VALUES (1,'HR', 2), (2, 'Finance', 4), (3, 'Software',1) ,
(4, 'Finance', 3), (5, 'Hardware',1), (6, 'Software', 5), (7, 'Finance', 1);
Query: 
SELECT group_concat(e.e_name) as Employee_Names, d.d_name as Department_Name FROM Employee e INNER JOIN Department d ON d.e_id = e.e_id GROUP BY d.d_name;
Happy Coding!!!

Sunday, January 25, 2015

How to display all tables in different databases

In this article, we will see how to connect to the different databases(MySQL, Oracle, PostgreSQL, DB2) and how to display the all table names. 


MySQL

Connect to the database:
mysql [-u username] [-h hostname] database-name

To list all databases, in the MySQL prompt type:
show databases

Then choose the right database:
use <database-name>

List all tables in the database:
show tables

Describe a table:

desc <table-name>

Oracle

Connect to the database: 
connect username/password@database-name;

To list all tables owned by the current user, type:
select tablespace_name, table_name from user_tables;

To list all tables in a database:
select tablespace_name, table_name from dba_tables;

To list all tables accessible to the current user, type:
select tablespace_name, table_name from all_tables;

To describe a table:
desc <table_name>;

PostgreSQL

Connect to the database:
psql [-U username] [-h hostname] database-name

To list all databases, type either one of the following:
list

To list tables in a current database, type:
\dt

To describe a table, type:
\d <table-name>

DB2

Connect to the database:
db2 connect to <database-name>;

List all tables:
db2 list tables for all;

To list all tables in selected schema, use:
db2 list tables for schema <schema-name>;

To describe a table, type:
db2 describe table <table-schema.table-name>;
Happy coding...

Sunday, December 28, 2014

Displaying the Greeting Message based on Time in MySQL


Hi, My requirement is based on Current time i want to display Greeting message.

For example, if time is less than 12PM then i need to display "Morning" and if time is less than 5PM then i need to display "Afternoon" and if time is above 5 PM i need to display "Evening".

Step1: Selecting the Current time.
SELECT now() from DUAL;
Output:
 '2014-12-28 17:35:46'

Step2: In the Current time getting the hours.
SELECT TIME_FORMAT(now(),'%H') from DUAL;
Output: 
17

Step3: Now based on hours we need to display greeting message. So we need to use if condition.
SELECT IF((SELECT TIME_FORMAT(now(),'%H') from DUAL) < 12,'Morning', IF((SELECT TIME_FORMAT(now(), 
'%H') from DUAL) < 17,'Afternoon','Evening'));
Output:
'Evening'

Happy coding!

Thursday, February 20, 2014

Case Insensitive Sorting Example in Oracle11g


Step1: Create Employee table 
create table employee(id int, name varchar(20));
 
Step2: Insert values to Employee table
insert into employee values(1,'Ranga');
insert into employee values(2,'rAnga Reddy');
insert into employee values(3,'Raja');
insert into employee values(4,'raJa Reddy');
insert into employee values(5,'raja');
insert into employee values(6,'Reddy');
insert into employee values(7,'ranga');
 
Step3: Select the Employee values with out sorting
select * from employee;
------------------------------------------- 
ID NAME
1 Ranga
2 rAnga Reddy
3 Raja
4 raJa Reddy
5 raja
6 Reddy
7 ranga
 
Step4: Select the Employee values with sorting 
select * from employee order by name;
------------------------------------------- 
ID NAME
3 Raja
1 Ranga
6 Reddy
2 rAnga Reddy
4 raJa Reddy
7 ranga
5 raja

 
Step5: Select the Employee values with case insensitive sorting 
select * from employee order by upper(name);
------------------------------------------- 
ID NAME
5 raja
3 Raja
4 raJa Reddy
7 ranga
1 Ranga
2 rAnga Reddy
6 Reddy
 
Click here to Run and Test the above example in online.


Tuesday, October 5, 2010

SQL Command


SQL Commands: 
SQL commands are broadly classified into 5 categories: They are
1. DDL (Data Definition Language)
2. DML (Data Manipulation Language)
3. DCL (Data Control Language)
4. TCL (Transaction Control Language)
5. DQL (Data Query Language)

1. Data Definition Language (DDL) - DDL commands are used to Creating, Modifying and Deleting the structure of database objects.
DDL Commands: CREATE, ALTER, DROP, TRUNCATE and RENAME

2. Data Manipulation Language (DML) - DML commands are used to storing, modifying and deleting the data in the database.
DML Commands: INSERT, UPDATE and DELETE

3. Data Control Language (DCL) - DCL commands are used for providing the security to database objects.
DCL Commands: GRANT and REVOKE.

4. Transaction Control Language (TCL) - TCL commands are used to allow the user to control the transactions in a database.
TCL Commands: COMMIT, ROLLBACK and SAVEPOINT

5. Data Query Language (DQL) - DQL command are used to get/retrieve the data from the database.
DQL Commands: SELECT

NOTE: SQL Commands are terminated by a semicolon(;)
Create Command - The CREATE TABLE command is used to create table(s) or relation(s) to store data.
Syntax:
CREATE TABLE table_name(
   column_name1 datatype,
   column_name2 datatype,
   column_name3 datatype,
   .....
   column_nameN datatype,
   PRIMARY KEY( one or more columns )
);
Example:
CREATE TABLE employee( 
  id number(5), 
  name varchar(20),   
  age number(2), 
  salary number(10),
  PRIMARY KEY(id)
);

Describe Command - The DESCRIBE or DESC command is used to view the description of a table.
Syntax:
Desc table_name;
Example:
Desc employee;

Insert command - Insert command is used to insert the values in a table.
Syntax:
INSERT INTO TABLE_NAME [ (column1,column2,column3,... columnN)] VALUES (value1, value2, value3,...valueN);
Example:
INSERT INTO employee(id, name, age, salary) VALUES(1, 'Ranga', 27, 3000);
INSERT INTO employee VALUES(2, 'Raja', 47, 8000);

Select Command - The SELECT statement is used to query or retrieve data from a table in the database.
A query may retrieve information from specified columns or from all of the columns in the table.
Syntax:
There are three ways we can retrieve data from a table:
  • Retrieve one column
  • Retrieve multiple columns
  • Retrieve all columns
SELECT column_name FROM table_name;
SELECT column_name1, column_name2, column_name3 FROM table_name;
SELECT * FROM table_name;
Example:
SELECT name FROM employee;
SELECT id, name, age FROM employee;
SELECT * FROM employee;
Update Command - The UPDATE command is used to update the values of a table.
Syntax:
UPDATE table_name SET column_name1=value1, column_name2=value2, ......column_namen=valuen WHERE condition;
Example:
UPDATE employee SET name='Ranga Reddy' WHERE id=1;
Alter Command : The ALTER command is used to alter the structure of a table. Alter command has three attributes namely add, modify and drop.
Add:      Adding a column in a table.
Modify: Modify the size of a column.
Drop:     Dropping a column of a table.
Add Column:
Syntax:
ALTER TABLE table_name ADD(column_name datatype);
Example:
ALTER TABLE employee ADD(company varchar(30));
Modify Column:
Syntax:
ALTER TABLE table_name MODIFY(column_name datatype);
Example:
ALTER TABLE employee MODIFY(name varchar(25));
Drop Column:
Syntax:
ALTER TABLE table_name DROP column column_name;
Example:
ALTER TABLE employee DROP column company;
Rename Command - The RENAME command is used to change the name of the table.
Syntax:
RENAME old_table_name TO new_table_name;
Example:
RENAME employee TO employees;
Delete Command - DELETE command is used to delete a row(s) from a table.
Syntax:
DELETE FROM table_name [WHERE condition];
Example:
DELETE FROM employee WHERE id=1;
Truncate command - The TRUNCATE command is used to delete all rows from a table and free the space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE employee;
Drop Command - The DROP command is used to drop the structure of a table permanently. If you drop a table, all the rows in the is deleted.
Syntax: 
DROP TABLE table_name;
Example:
DROP TABLE employee;
Commit Command - The COMMIT is used to save the transaction. It will saves all transactions to the database since the last COMMIT or ROLLBACK command.
Syntax & Example:
COMMIT
Rollback Command - ROLLBACK command is used to restoring the database to its original position since last COMMIT.
Syntax & Example:
ROLLBACK 
SavePoint Command- The SAVEPOINT command used to identifies the transaction in a database.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Example:
SAVEPOINT S1;
The ROLLBACK command is used to undo a group of transactions.
Syntax:
ROLLBACK TO SAVEPOINT_NAME;
Example:
ROLLBACK TO S1;
Grant Command: The GRANT command is used to grants(gives) user permissions to access the database objects.
Syntax:
GRANT privilege_name ON object_name TO {user_name |PUBLIC |role_name}[WITH GRANT OPTION]; 
privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE, and SELECT.
object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE.
Example:
CREATE USER rangareddy IDENTIFIED by ranga;
GRANT ALL privileges TO rangareddy;
Revoke Command: REVOKE command is used to rovokes(removes) the permission given to user.
Syntax:
REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name} 
Example:
REVOKE ALL ON employee FROM rangareddy;