Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Pull Data From Two Tables SQL Based on Date?

  • Last Updated : 16 Nov, 2021

In this article, we will see, How to write SQL queries to pull data from two tables based on date. We can perform the above function by performing the UNION operation on the tables. UNION operation appends the results of two queries and returns the result as a single set. 

Ways to use the UNION keyword:

 Syntax:

SELECT * from table1 (query1)
UNION
SELECT * from table2 (query2);

There are a few rules to be followed before using the UNION keyword:

  • The number and the order of the columns must be the same in the queries.
  • The data types of the chosen fields must be the same.

For demonstration purposes, perform the steps given below:

Step 1: Create a database

We can use the following command to create a database called geeks.

Query:

CREATE DATABASE geeks;

Step 2: Use database

Use the below SQL statement to switch the database context to geeks:

Query:

USE geeks;

Step 3: Table definition

We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database.

Query(demo_table1):

CREATE TABLE demo_table1(
ID int,
NAME VARCHAR(20),
AGE INT,
CITY VARCHAR(20) ,
DOB DATE);

Query(demo_table2):

CREATE TABLE demo_table2(
ID int,
NAME VARCHAR(20),
AGE int,
DOB DATE);

Step 4: Insert data into a table

Query(demo_table1):

INSERT INTO demo_table1 VALUES
(11,'Romy',23,'Delhi','1999-11-30'),
(23,'Rahul',23,'Delhi','1998-10-01'),
(31,'Nikhil',24,'Punjab','1990-05-03'),
(46,'Ranvir',23,'Punjab','2002-10-09'),
(52,'Samiksha',23,'Banglore','2017-08-10'),
(61,'Ashtha',24,'Banglore','2001-09-10'),
(77,'Tannu',30,'Patna','1996-08-01'),
(89,'Girish',30,'Patna','1930-09-30');

Query(demo_table2):

INSERT INTO demo_table2 VALUES
(31,'Fanny',25, '1996-07-08' ),
(77,'Prem', 30, '2003-05-09'),
(15,'Preeti',21, '2001-02-02'),
(46,'Samita',32, '1994-07-23'),
(09,'Rajan',45, '1993-05-05');

Step 5: View the content

Execute the below query to see the content of the table

Query(demo_table1):

SELECT * FROM demo_table1;

Output:

Query(demo_table2):

SELECT * FROM demo_table2;

Output:

STEP 6: SQL query to pull data from two tables based on dates. For demonstration, we will pull the data having DOB in-between  ‘1990-01-01’ to ‘2000-01-01’ date.

Query:

SELECT d1.NAME, d1.AGE, d1.DOB
FROM demo_table1 d1 WHERE DOB BETWEEN
'1990-01-01' and '2000-01-01'
UNION  
SELECT d2.NAME, d2.AGE, d2.DOB  
FROM demo_table2 d2 WHERE DOB BETWEEN
'1990-01-01' and '2000-01-01';

Output:

We can see that data from both the data is extracted based on the dates specified in the query.

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!