Tuesday, May 14, 2024

How to get rows between two dates in Microsoft SQL Server? MSSQL Example

Problem: You want all records between two dates e.g. start_date and end_date. For example, you have a Course table, which contains course_name, price and start_date. If want all the course which are starting next month, how will you do that?

Solution : You can get the records between two dates in SQL SERVER by using dates in WHERE clause, for example, below query will return all the courses for which start date is greater than 2025/01/01 and less than 2025/01/31

Tuesday, May 7, 2024

How to Remove duplicate rows from table in SQL Server using temp table? Example

One of the easiest way to remove duplicate rows from a table in SQL is copy unique data into temp table, delete the original table and create a new table from the temp table without any duplicates. Sometime when you don't have a unique key or primary key in table, you end up with duplicate rows i.e. more than one rows where all columns are identical. You can easily find those duplicate rows by using GRPUP BY, as seen in our previous SQL interview questions. You can also print just unique rows by using distinct clause, but how do you go about removing duplicate rows from table altogether? That's what you will learn in this article. Actually there are multiple ways to remove duplicates and you will learn couple of them in this article. 

Wednesday, May 1, 2024

Difference between Primary key Unique key in Database SQL

Hello friends, both primary key and unique key are two important concepts in a relational database which are used to uniquely identify a row in a table. For example, EmployeeId is often primary key in Employee table which can uniquely identify any employee which is denoted by a row in Employee table. Similarly, a employee can also be identify with EmployeeName if there is no duplicate but if its not primary key then we call it a unique key. While both primary key and unique keys can identify a row uniquely but there is some subtle difference between them which we will see in this article.