SQL Between Operator overview and examples

SQL Between Operator overview and examples

SQL Between Operator overview and examples

SQLShack

SQL Server training Español

SQL Between Operator overview and examples

June 11, 2019 by Rajendra Gupta We extract data from SQL Server tables along with various conditions. Usually, we have data in large amounts and SQL Between operator helps to extract a specific range of data from this huge data. For example, suppose we want to know the product sales between Jan 2019 to May 2019. In this case, we can use this operator in a SQL query. In this article, we will explore the SQL Between operator and its usage scenarios.

The Syntax of SQL Between operator

We use SQL Between operator in the Where clause for selecting a range of values. The syntax for SQL Between is as follows 1234567 SELECT Column_nameFROM tableWHEREtest_expressionBETWEEN min_value(expression) AND max_value; Test_Expression: It is the expression or column on which we need to define a range Min_value(expression): We define a minimum range for the between operator. Its data type should be the same as of test_expression Max_value)expression): It is the maximum range for the between operator. It should also be the same data type as of min_value(expression) and test_expression In my example, product sales between Jan 2019 to May 2019, we have min_value as Jan 2019 and max_value as May 2019. The SQL Between operator returns TRUE if the Test_expression value is greater than or equal to the value of min_value(expression) and less than or equal to the value of max_value ( expression). If the condition is not satisfied, it returns FALSE. Usually, developers confuse on whether the result will be inclusive or exclusive of the specified range. For example, does the result set include (in product sales between Jan 2019 to May 2019) both Jan 2019 and May 2019 sales data and exclude Jan 2019 and May 2019. We will look at this with the next section of examples. Let’s prepare a sample table and insert data into it. I am using ApexSQL Generate as shown in the following screenshot. You can specify a custom date range to select appropriate data. Once we generate the date, you can check the sample data in the table.

Example 1 SQL Between operator with Numeric values

We can specify numeric values in the SQL Between operator. Suppose we want to get data from Productdata table for ProductID between 101 and 105. Execute the following query to get the data. You can specify numeric value directly in between operator without any single quote. 123 SELECT *FROM productdataWHERE ProductID BETWEEN 101 AND 105; Previously, we thought of a question – whether the between operator contains inclusive or exclusive values. In the output, we can see that both ProductID 101 and 105 are included in the output of SQL Between.

Example 2 SQL Between operator with Date Range

We can use SQL Between operator to get data for a specific date range. For example, in the following query, we want to get data from ProductSaleDate table in the range of 1st Jan 2019 and 1st April 2019. You need to specify the dates in a single quote. 1234 SELECT *FROM productdataWHERE ProductSaleDate BETWEEN '2019-01-01' AND '2019-04-01'ORDER BY ProductSaleDate;
We can use the CAST function to convert the value in the desired date format explicitly. For example, in the following query, we use the CAST function to convert a string into a date data type. 1234 SELECT *FROM productdataWHERE ProductSaleDate BETWEEN CAST('20190101' as date) AND CAST('20190401' as date)ORDER BY ProductSaleDate; Similarly, we can use the CAST function to convert a string into a datetime2 data type. 1234 SELECT *FROM productdataWHERE ProductSaleDate BETWEEN CAST('20190101' as datetime2) AND CAST('20190401' as datetime2)ORDER BY ProductSaleDate; In our sample data, productsaledate contains date along with the timestamp. In the SQL between the operator, we didn’t specify timestamp to get the required data. If you do not specify any timestamp, SQL automatically specifies timestamp as midnight. We need to b careful in using SQL Between with date columns. Let’s explore these using a further example. Let’s create a table variable and insert few records in it. In the insert statement, you can see we are using timestamp for a few users while few users have the only date. 1234567 DECLARE @Users TABLE(Name varchar(40), ModifyDate DateTime)INSERT INTO @Users (Name, ModifyDate) VALUES ('Raj', '2019-02-01');INSERT INTO @Users (Name, ModifyDate) VALUES ('Raju', '2019-02-01 09:32:42');INSERT INTO @Users (Name, ModifyDate) VALUES ('Rajendra', '2019-02-01 15:04:09');INSERT INTO @Users (Name, ModifyDate) VALUES ('Akshita', '2019-02-03');INSERT INTO @Users (Name, ModifyDate) VALUES ('Kashish', '2019-02-03 21:42:43'); In the records, you can see SQL Server added timestamp automatically in case we do not specify timestamp explicitly. This scenario is also applicable once we retrieve the records using SQL Between operator. Let’s select the data from the table variable using the following query. 123 select * from @Users WHERE ModifyDate BETWEEN '2019-02-01' AND '2019-02-03'ORDER BY ModifyDate We should get all the records in the table but let’s view the output. In the output, we do not have a record for user Kashish. As stated earlier, if we do not specify timestamp in the SQL Between operator, SQL Server automatically uses timestamp until midnight. Due to this reason, we get the output until 2019-02-03 00:00:00.000. For User Kashish modifieddate is 2019-02-03 21:42:43 and it does not fulfill condition in SQL Between operator. Due to this, we do not get this user in the output. Let’s execute the command again with a timestamp in SQL Between operator. 123 select * from @Users WHERE ModifyDate BETWEEN '2019-02-01' AND '2019-02-03 22:00:00'ORDER BY ModifyDate We get all records this time because it checks for data until 2019-02-03 22:00:000.

Example 3 SQL Between operator with a string

In this example, we want to get data from Productdata table having ProductCode between A and D. We also need to use a single quote for a string to get inclusive data. 1234 SELECT *FROM productdataWHERE ProductCode BETWEEN 'A' AND 'C'ORDER BY ProductCode; In the output, you can see data for productcode between A and C.

Example 4 SQL NOT Between operator with a string

We might also want to exclude a particular range of data in the output. In this case, we can use SQL Between operator with Not statement. Suppose, we want to get the top 10 records from the ProductData table but do not want to include ProductID 104 and 108. We can specify this condition using Not Between operator. 1234 SELECT top 10 *FROM productdataWHERE ProductID Not BETWEEN 104 and 108ORDER BY ProductID; In the output, we do not have data from ProductID 104 and 108.

Conclusion

In this article, we explored SQL Between operator along with its use cases. We should be familiar with the function to get a specific range of data. If you have any comments or questions, feel free to leave them in the comments below. Author Recent Posts Rajendra GuptaHi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book "DP-300 Administering Relational Database on Microsoft Azure". I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at [email protected]

View all posts by Rajendra Gupta Latest posts by Rajendra Gupta (see all) Copy data from AWS RDS SQL Server to Azure SQL Database - October 21, 2022 Rename on-premises SQL Server database and Azure SQL database - October 18, 2022 SQL Commands to check current Date and Time (Timestamp) in SQL Server - October 7, 2022

Related posts

Term Extraction Transformation in SSIS Top SQL Server Books SQL Convert Date functions and formats SQL Union vs Union All in SQL Server Static Data Masking in SSMS 18 74,117 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ▼Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ▼Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!