Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
My problem is this: I have a table "users": ``` id_us | name ------------- 1 | bob 2 | ken 3 | jones ``` and I also have a table for pets "pets" ``` id_pet | pet ------------- 1 | dog 2 | cat 3 | fish ``` and a table for storing the relation of user and pets "user\_pets" ``` id | id_u...
You might consider using `EXISTS` Inner Query bring all the dogs from the users. Then if `NOT EXISTS` any result mean Bob doesnt have a dog. ``` SELECT * FROM users u WHERE NOT EXISTS ( SELECT * FROM user_pets up WHERE up.id_pet = 1 AND up.id_us = u.id_us ) `...
``` SELECT usuario.name FROM usuario LEFT JOIN user_pets ON usuario.id_us = user_pets.id_us AND user_pets.pet = 1 WHERE user_pets.id is null ``` OR ``` SELECT usuario.name FROM usuario WHERE NOT EXISTS (SELECT id_ud FROM user_pets WHERE user_pets.pe...
How to use query irelationship in SQL
[ "", "mysql", "sql", "" ]
I've got a SQL table where I want to find the first and last dates of a group of records, providing they're sequential. ``` Patient | TestType | Result | Date ------------------------------------------ 1 | 1 | A | 2012-03-04 1 | 1 | A | 2012-08-19 1 | 1 | B ...
There are several ways to approach this. I like identifying the groups using the difference of row number values: ``` select patient, testtype, result, min(date) as startdate, max(date) as enddate from (select t.*, (row_number() over (partition by patient, testtype order by date) - r...
``` select patient, testtype, result, date as startdate, isnull(lead(date) over(partition by patient, testtype, result order by date), date) as enddate from tablename; ``` You can use `lead` function to get the value of date (as enddate) from the next row in each group. [SQL Fiddle](http://www.sqlfiddle.com/#!6/55a9...
Aggregate/Windowed Function To Find Min and Max of Sequential Rows
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I've come across ``` create table new_table as select * from old_table where 1=2; ``` What is the meaning of the `where 1=2` condition and what function does it perform?
`1=2` always evaluates as false. This is a common trick to utilize the create as select to copy a table's structure without copying any of its rows (as none of them will pass the test of `1=2`).
Just it will copy the structure of a `table` not `data` present in a `table`. `1=0 or 1=2` will always returns false in where clause so `select query` doesn't return any `rows` from table it's just a trick for create a `table` as like another `table` in your `schema` .
What is the meaning of 1=2 when copying database structure?
[ "", "sql", "oracle", "ddl", "create-table", "" ]
I know the question is a duplicate, but I am not able to find a solution to my problem below: ``` SELECT CAST(747448809352908.49434500000 AS Decimal(25,12)) AS [Value] ``` This is the value I am getting from one of my calculations. I am trying to insert into a Table with Value column ...
your total length of value is not matched with your data type. you are assigning `Decimal(25,12)` but length more than 25, actually 27 ``` SELECT CAST('747448809352908.49434500000' AS Decimal(27,12)) AS [Value] ``` In SQL Server, decimal and numeric are numeric data types that have fixed precision and scale. For a ...
tinka answer is correct but here is explanation the length of this `747448809352908.49434500000` is 27 so in DECIMAL should contain the maximum length of the number , so the error because you specify 25 , the number 12 is the number after the comma `49434500000` whic is 11.
Arithmetic overflow error converting numeric to data type numeric for Decimal(25,12)
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have a table called `ranks` which stores a 1-7 value and connects it with an item and user id. An item's rating is the average of all ratings it has been given. Ranks table: `id | userid | value | itemid.` To sort by average highest rating, I do (from an answer here): ``` select avg(value), itemid from ranks group...
Your `having` clause needs to come after your `group by` clause, so just reverse the order they appear in: ``` select avg(value), itemid from ranks group by itemid having avg(value) between 5 and 6 order by avg(value) desc ```
``` select * from ( select avg(value) as avgval, itemid from ranks group by itemid) t where avgval between 5 and 6; ``` You can do it with a sub-query.
Sort by average rating between 2 values
[ "", "mysql", "sql", "" ]
I have an attendance SQL table that stores the start and end day's punch of employee. Each punch (punch in and punch out) is in a separate record. I want to calculate the total working hour of each employee for a requested month. I tried to make a scalar function that takes two dates and employee ID and return the ca...
One more approach that I think is simple and efficient. * It doesn't require modern functions like `LEAD` * it works correctly if the same person goes in and out several times during the same day * it works correctly if the person stays in over the midnight or even for several days in a row * it works correctly if the...
My approach would be as follows: ``` CREATE FUNCTION [dbo].[MonthlyHoursByEmpID] ( @StartDate Date, @EndDate Date, @Employee NVARCHAR(6) ) RETURNS FLOAT AS BEGIN DECLARE @TotalHours FLOAT DECLARE @In TABLE ([Date] Date, [Time] Time) DECLARE @Out TABLE ([Date] Date, [Time] Time) INSERT INTO @In([Date], [Time]) SELECT...
Get total working hours from SQL table
[ "", "sql", "sql-server", "t-sql", "" ]
I have this query, ``` SELECT DISTINCT username, publishedapp FROM tbl_name WHERE username in ( SELECT username FROM tbl_name WHERE publishedapp = \"Mencap@Work2-1\" ) AND publishedapp NOT LIKE \"%Desktop%\" AND publishedapp NOT LIKE \"%RDP%\" GROUP BY username HAVING COUNT(DISTINCT publishedapp) > 1 ``` ...
What you do to troubleshoot something like this is to break down the query into pieces until you find the source of the problem. Sometimes you may need to use select \* or specify columns in the join or the where clause that you are not returning in the final product to see what is going on. I would do something like t...
Try simplifying the query. If I understand correctly: ``` SELECT username, group_concat(publishedapp) FROM tbl_name WHERE publishedapp NOT LIKE '%Desktop%' AND publishedapp NOT LIKE '%RDP%' GROUP BY username HAVING COUNT(DISTINCT publishedapp) > 1 AND SUM(publishedapp = 'Mencap@Work2-1') > 0; ``` There i...
Query not workin
[ "", "mysql", "sql", "" ]
I am unsure how to get SQL to do what I am trying to figure out. I have one student, and depending on their grade level, would be in one of three schools (schoolid). I need to return only the StudentID and SchoolID of the school the student is currently in, based on the grade level. How do I search in this way please?...
``` where GradesOfferedInSchool like '%' + cast(StudentCurrentGrade as varchar(max)) + '%' ``` But that is a terrible data design Should not have multiple values in one column This is still just a hack as this would find '12b' If this is a view then look for normalized data better but still a hack ``` where Gr...
This works for me using Microsoft SQL Server. The `CAST` is needed otherwise it was throwing an error due to the different datatypes of the fields. ``` SELECT StudentID, SchoolID FROM dbo.StudentFeederPatterns WHERE GradesOfferedInSchool LIKE '%' + CAST(StudentCurrentGrade AS VARCHAR) + '%' ``` [SQL Fiddle](http:/...
TSQL - How to search a string in multiple rows?
[ "", "sql", "sql-server", "t-sql", "" ]
I have the following table of transport records for a bus company: ``` CREATE TABLE ride_txn( passenger_no int(11) pk, txn_time timestamp, action varchar(10) ) ``` where the action could be "Board" or "Deboard". Say I have 2 rows where for passenger\_no. 100, he boarded at 1.30pm and alighted at 4.30pm. ``` passeng...
Here's a start: ``` select passenger_no, hr from ride_txn rt, ( select 0 hr union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 union al...
``` select id,y.tm from ( select id, max(case when action = 'Deboard' then hour(dt) end) as d_time, max(case when action = 'Board' then hour(dt) end) as b_time from tablename group by id) x join ( select distinct hour(dt) as tm from tablename ) y on y.tm between x.b_time and x.d_time ``` This would work as...
Finding hourly passenger loads given boarding and deboarding time
[ "", "mysql", "sql", "" ]
My table ``` ID Name Addr tDate ------------------------------- | 1 | Aa | street | 20151231 | 2 | Aa | street | 20130202 | 2 | Aa | street | 20120101 | 3 | Aa | way | 20150821 | 4 | Bb | street | 20150821 | 7 | Xb | street | 20150821 | 5 | Cc | way | 20150821 | 5 | Cc | way | ...
**EDIT** : *Complete change after your addition of tDate, and need for two result sets* Result Set 1: ``` SELECT id, Name, Addr, tDate FROM ( SELECT *, COUNT(*) OVER (PARTITION BY Name, Addr) AS occurrences FROM MyTable ) AS parsed WHERE occurrences > 1 ``` Result Set 2: ...
The [`dense_rank`](https://msdn.microsoft.com/en-us/library/ms173825.aspx) window function should do the trick: ``` SELECT ID, Name, Addr DENSE_RANK() OVER (PARTITION BY Name, Addr ORDER BY ID) AS nID FROM mytable ORDER BY 1, 4 ```
SELECT and create new ID for unique ids having identical values on 2 columns
[ "", "sql", "sql-server", "select", "sql-server-2012", "" ]
Say I have a table matching `person_id`s to `pet`s. I have a list of the ideal pets that a homeowner must have (at least one of each) and, from the following table, I want to see who meets the requirements. That list is, of course, `(dog, cat, tiger)`. People can definitely have more than one of each, but these are es...
One way of doing this is to count how many different pets each person has and to compare it (i.e. join it) with the total number of different pets: ``` SELECT person_id FROM (SELECT person_id, COUNT(DISTINCT pet) AS dp FROM pets GROUP BY person_id) a JOIN (SELECT COUNT(DISTINCT pet) AS dp FRO...
``` select person_id from house where pet = 'dog' intersect select person_id from house where pet = 'cat' intersect select person_id from house where pet = 'tiger' ``` You can use `intersect` to get people who have all the 3 pets.
Group by having at least one of each item
[ "", "sql", "postgresql", "select", "relational-division", "" ]
I'm trying to combine 2 fields from 2 tables into one field, not one record using **Delphi SQL**. This is what my tables look like: Table1: ``` ItemID ------ E001 E002 E004 I001 ``` Table2: ``` ItemID ------ E002 E003 I001 I002 ``` ItemID servers as a key between the two tables...
Seems like what you want is the following query: ``` select ItemID from Table1 union select ItemID from Table2 ``` The `union` eliminates duplicate rows. If you want to keep the duplicate, use `union all`.
Simple approach (assumed MySQL due to mysql tag): ``` select ItemId as ItemId from Table1 as t1 union select ItemId as ItemId from Table2 as t2 ``` [DEMO HERE](http://sqlfiddle.com/#!9/1a291/5) If you really want to have `*` as a part of you result then please use following code (simulated left oute...
How to combine 2 fields from 2 tables into one field using Delphi SQL
[ "", "sql", "delphi", "" ]
I have this query ``` SELECT DISTINCT publishedapp FROM tbl_name WHERE publishedapp LIKE "%@%" OR publishedapp LIKE "%Desk%" OR publishedapp LIKE "%RDP%" OR publishedapp LIKE "%CTX%\" ORDER BY publishedapp ``` It returns a list but from that list I want to filter a couple entries, Ive tried adding AND publishedapp NO...
Just use all the OR conditions in bracket. ``` SELECT DISTINCT publishedapp FROM tbl_name WHERE (publishedapp LIKE '%@%' OR publishedapp LIKE '%Desk%' OR publishedapp LIKE '%RDP%' OR publishedapp LIKE '%CTX%') AND publishedapp NOT LIKE '%ActiveH Desktop June 2013%' ORDER BY publishedapp ``` Here the problem is that t...
try the below code ``` SELECT DISTINCT publishedapp FROM tbl_name WHERE (publishedapp LIKE '%@%' OR publishedapp LIKE '%Desk%' OR publishedapp LIKE '%RDP%' OR publishedapp LIKE '%CTX%') ORDER BY publishedapp ```
SQL WHERE LIKE OR FILTER
[ "", "mysql", "sql", "" ]
Suppose I have a table as follows: ``` Name Part Address City ... Stuff Bob X1 Y1 Z1 ... Stuff1 Bob X2 Y1 Z1 ... Stuff1 Bob X3 Y1 Z1 ... Stuff1 Susan V1 Y2 Z2 ... Stuff2 Susan V2 Y2 Z2 ... Stuff2 .... ``` Here, Stuff is many columns. Notice that ...
Use [`ROW_NUMBER`](https://msdn.microsoft.com/en-us/library/ms186734.aspx) instead. > Returns the sequential number of a row within a partition of a result > set, starting at 1 for the first row in each partition. ``` SELECT * FROM ( SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Part) FR...
try this ``` WITH CTE AS ( SELECT ROW_NUMBER() OVER(PARTITION BY GroupColumn ORDER BY SomeColumn) as indx FROM YourTABLENAME ) select * from CTE where indx=1 ```
Select First Row from each group when many columns
[ "", "sql", "sql-server", "" ]
I am storing some filter data in my table. Let me make it more clear: I want to store some `where` clauses and their values in a database and use them when I want to retrieve data from a database. For example, consider a `people` table (entity set) and some filters on it in another table: ``` "age" , "> 70" "gender" ...
One solution is to use [Dynamic Linq Library](https://www.nuget.org/packages/System.Linq.Dynamic.Library/) , using this library you can have: ``` filterTable = //some code to retrive it var whereClause = string.Join(" AND ", filterTable.Select(x=> x.Left + x.Right)); var result = context.People.Where(whereClause).ToLi...
This is an interesting question. First off, make sure you're honest with yourself: you are creating a new query language, and this is *not* a trivial task (however trivial your expressions may seem). If you're certain you're not underestimating the task, then you'll want to look at [LINQ expression trees](https://msdn...
Entity Framework filter data by string sql
[ "", "sql", "sql-server", "linq", "entity-framework", "linq-expressions", "" ]
I'm implementing in my application an event logging system to save some event types from my code, so I've created a table to store the log type and an Incremental ID: ``` |LogType|CurrentId| |info | 1 | |error | 5 | ``` And also a table to save the concrete log record ``` |LogType|IdLog|Message ...
Can you achieve what you want with an identity column? Then you can just let SQL Server guarantee uniqueness. Example: ``` create table my_test_table ( ID int identity ,SOMEVALUE nvarchar(100) ); insert into my_test_table(somevalue)values('value1'); insert into my_test_table(somevalue)values('value2'); select * ...
Not much you can do here, but validate that: * table TBL\_ApplicationLogId is indexed by column LogType. * @LogType sp parameter is the same data type as column LogType in table TBL\_ApplicationLogId, so it can actually use the index if/when it exists. * If you have a concurrency issue, maybe forcing the lock level on...
SPROC that returns unique calculated INT for each call
[ "", "sql", "t-sql", "sql-server-2005", "" ]
After updating mysql version 5.7.8-rc-log, I granted privileges like this: ``` GRANT select ON test_db.* TO 'test'@'host'; ``` and getting following error: > SELECT command denied to user 'test'@'host' for table 'session\_variables' but when I grant privileges like this: ``` GRANT select ON *.* TO 'test'@'host'; `...
Here are the [article1](http://planet.mysql.com/entry/?id=5991741), [article2](https://github.com/rails/rails/issues/21108), [article3](http://code.openark.org/blog/mysql/baffling-5-7-globalstatus-variables-issues-unclean-migration-path) related to this issue. As per these articles, Workaround is setting `show_compatib...
Try with the following way, maybe you will get the result. ``` GRANT ALL PRIVILEGES ON bedgeaj_medmax.transactions to 'bedgeaj_root'@'%' IDENTIFIED BY 'password'; ``` (OR) ``` GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'%' WITH GRANT OPTION; ```
Command denied for table 'session_variables'
[ "", "mysql", "sql", "t-sql", "privileges", "sql-grant", "" ]
I have the following table (call it just `table`): ``` id name value group_id PK varchar(32) integer integer ``` Now, I need to write a query that returns me `SUM(value)` grouped by `group_id` and `COUNT(name)` where `name like '%me%'`( I don't need to just compute count grouped by `group...
With 9.4 you can use a filtered aggregate: ``` select group_id, sum(value) count(name) filter (where name like '%me%') from the_table group by group_id; ``` For earlier versions, you need to use a CASE statement: ``` select group_id, sum(value) count(case when name like '%me%' then 1 en...
It should be noted that case can be replaced by casting a bool to int which is shorter (`LIKE` can be replaced by `~~` but that is both shorter and less readable). ``` SELECT group_id ,Sum(value) AS sum_value ,Sum((name LIKE '%me%')::int) AS count_value FROM table GROUP BY group_id; ```
How to compute the count by a condition
[ "", "sql", "postgresql", "postgresql-9.2", "" ]
I need your help! I have a table: ``` CREATE TABLE `table` ( `id` int(11) NOT NULL AUTO_INCREMENT, `res` varchar(255) DEFAULT NULL, `value` int(6) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- Records of table INSERT INTO `table` VALUES (1, 'gold', 44); INSERT INT...
You can solve this with a `gaps and islands` solution. - Normally that involves `ROW_NUMBER()` which is not present in MySQL - The solution below mimics `ROW_NUMBER()` with variables and `ORDER BY` Link to example : <http://sqlfiddle.com/#!9/32e72/12> ``` SELECT MIN(id) AS id, res, value FROM ( ...
``` select t1.* from `table` t1 where not exists ( select 1 from `table` t2 where t1.id = 1+t2.id and t1.res = t2.res and t1.value = t2.value ); ``` works fine
How to ignore next duplicated row?
[ "", "mysql", "sql", "" ]
I have a simple query that give me the count of application types; it looks something like this: ``` SELECT Application_Type, COUNT(*) FROM Loan_Applications GROUP BY Application_Type; ``` It returns something like this: ``` Home 3 Car 21 Commercial 16 ``` There is a field in the database called ***Submission\_Dat...
You can try something like: ``` SELECT Application_Type, SUM(IF(Submission_Date BETWEEN CURRENT_DATE AND CURRENT_DATE - INTERVAL 1 WEEK, 1, 0)) AS 'This week', SUM(IF(Submission_Date BETWEEN CURRENT_DATE- INTERVAL 1 WEEK AND CURRENT_DATE - INTERVAL 2 WEEK, 1, 0)) AS 'Last week', SUM(IF(Submission_Date ...
You can make a SUMIF type of calculation. The following sums the number of rows where the submission date is within the last week. ``` SUM(CASE WHEN submission_date >= CURDATE() - 7 THEN 1 ELSE 0 END) ``` You could then repeat this for different ranges, to get any "bands" that you desire.
Grouping COUNT by Time in MySql
[ "", "mysql", "sql", "" ]
I currently use a pretty basic backup script to backup my SQL databases to a given directory, zipped with Winrar. I am looking to use the SQL compression command (currently commented out) prior to the Winrar IF the version of SQL the script is being used on is SQL Standard or higher. Here is what my current script lo...
This may not be the full, but I think you will get the point: ``` DECLARE @databaseName nvarchar(100) DECLARE @fileName nvarchar(100) DECLARE @serverEdition int; DECLARE @useCompression bit; SELECT @serverEdition = Cast(SERVERPROPERTY('EditionID') as int); -- Reference: http://stackoverflow.com/questions/2070396/how-...
Without checking anything. If compression is supported compress, if not error is raised and then backup normally. ``` BEGIN TRY BACKUP DATABASE @databaseName TO DISK = @filename WITH COMPRESSION; END TRY BEGIN CATCH BACKUP DATABASE @databaseName TO DISK = @filename; END CATCH ```
SQL Script to compress database backups if version allows it
[ "", "sql", "sql-server", "database", "backup", "" ]
Using MySQL, is there an efficient way to filter records on one table by checking for the presence of multiple rows on an associated table? For example, I have a table of images and another table identifying objects in that image: ``` table: images id | url ----+-------------------------------- 1 | http://www.ex...
I like to approach these types of queries ("set-within-set" queries) with `group by` and `having`: ``` select it.image_id from image_tags it where it.tag in ('cats', 'dogs') group by it.image_id having count(*) = 2; ``` Note the "2" needs to equal the number of tags you want matched in the `in` list.
Another alternative, although more verbose but perhaps more performant (?? - sorry don't have MySQL to test) than Gordon's answer is: ``` select i.id, i.url from images i where exists( select 1 from image_tags g where g.image_id=i.id and g.tag='cats' ) and exists( select 1 from image_tags g where g.image_id=i.i...
MySQL filter on multiple rows on associated table
[ "", "mysql", "sql", "" ]
I'm working with an oracle database and what I basically need to concatenate in one column, values from multiple columns for every row. Something like this: ``` col1 col2 col3 col4 col5 ____________________________________ 1 A B C D 2 A B C 3 C A 4...
Use below query ``` select col1,rtrim( col2||','||col3||','||col4||','||col5,' ,') as col2 from table_name ```
[SQL Fiddle](http://sqlfiddle.com/#!4/f4ea2/2) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE test (col1, col2, col3, col4, col5 ) AS SELECT 1, 'A', 'B', 'C', 'D' FROM DUAL UNION ALL SELECT 2, 'A', 'B', 'C', NULL FROM DUAL UNION ALL SELECT 3, 'C', 'A', NULL, NULL FROM DUAL UNION ALL SELECT 4, 'D', 'A', 'C...
Concatenate values from multiple columns in Oracle
[ "", "sql", "oracle", "loops", "" ]
Im trying to find query each model with their most used ram configuration. Table: ``` PC (code, model, speed, ram, hd, cd, price) ``` So far, I was able to list every model with every ram config and number of times the ram config has been used. ``` select model, ram, max(config) from (select model,ram,count(ram) ...
``` with x as (select model,ram,count(ram) as config from pc group by model,ram) , y as (select model, max(config) as mxconfig from x group by model) select x.model, x.ram --choose max(x.ram) or min(x.ram) in case of a tie and group by x.model from x join y on x.model = y.model and x.config = y.mxconfig ``` This so...
I think what you are looking for is: ``` SELECT model,ram FROM (SELECT model,ram,count(ram) AS config FROM pc GROUP BY model,ram) WHERE config=max(config) ``` The records should already be grouped by your sub query
sql issue with having clause
[ "", "sql", "oracle", "group-by", "having", "ora-00979", "" ]
I am trying to write a query to update several rows of my SQL table at once. Below is the code I have tried, and it doesn't appear to be proper SQL as it doesn't work. Is there a way to accomplish this is one query? ``` $query = "UPDATE table_names SET Name='Bob' WHERE ID=7 SET Name='Mike' WHERE I...
One way to do this is with a `case` expression: ``` UPDATE table_name SET name = CASE id WHEN 7 THEN 'Bob' WHEN 34 THEN 'Mike' END WHERE id IN (7, 34) ```
This solution is more practival than "case when" I found and you can update as many columns as wanted ``` UPDATE searches_group_library SET compiled_query = new_val.compiledq FROM (VALUES (28, 'fakecompilation'), (57, 'fakecompilation2') ) new_val (id, compiledq) WHERE new_val.id = searches_group_libr...
SQL update multiple rows on specific ID's
[ "", "sql", "sql-update", "" ]
Suppose we have the database: ``` ----------- | A -|- B | |----|----| | 1 | 1 | | 1 | 2 | | 2 | 1 | ----------- ``` Where `A` and `B` is the primary key. Suppose we want to get all `A`s that contain the elements in `B` of 1 and 2. ``` SELECT A FROM Table WHERE B = 1 AND B = 2; ``` The above fails because it n...
`GROUP BY` solution, return all a's that have more than 1 different b value in (1,2): ``` select a from table where b in (1,2) group by a having count(distinct b) > 1 ``` Or, `JOIN` solution: ``` select distinct a from (select a from table where b = 1) t1 join (select a from table where b = 2) t2 on t1.a = t2.a ``...
You can use the group by method from jarlh or make a Join with a 'distinct': ``` select distinct a from (select a from table where b = 1) t1 join (select a from table where b = 2) t2 on t1.a = t2.a ```
How to get an ID associated with at least all contents?
[ "", "sql", "" ]
So I have the following query where it does as i expect it to. It get the latest published article from each aothor. However now I want it to get the latest two article from each author. How can I do this? ``` SELECT author_article.ID FROM ( SELECT sorted_articles.ID, sorted_articles.AuthorID,...
If you want the authors and the article ids, then this will put them in one row: ``` SELECT ap.AuthorId, SUBSTRING_INDEX(GROUP_CONCAT(ap.AuthorId ORDER BY ap.PublishedDate DESC ), ',', 2) as Top2Articles FROM ArticlePage ap GROUP BY ap.AuthorId; ``` Note: the default length f...
Use a correlated sub-query to count all more recent articles by the same author. If there are 1 or less more recent articles, return the row. ``` SELECT * FROM ArticlePage t1 WHERE (select count(*) from ArticlePage t2 where t2.AuthorID = t1.AuthorID and t2.PublishedDate > t1.PublishedDate) <= 1 ```
GROUP BY and get the top two row
[ "", "mysql", "sql", "subquery", "" ]
I have 2 tables: Name, and Birthday. I need to get Names of people who are over 18, but I cannot manually enter a date. ``` UserID = int Name = varchar(50) Birthday = Date UserID Name UserID Birthday ----------- ----------------- 1 ABC 1 1997-05-15 2 DEF 2 1997-09-21 3 GHI 3 2011...
Do not do date math on the `Birthday` column. That requires calculating the expression for every row in the table! Instead, do the math on the other side of the equality or inequality. If your birth dates are stored with no time portion: ``` WHERE Birthday <= DateAdd(year, -18, GetDate) ``` If they are stored with a...
``` where DATEADD(YY,18,Birthday) >= getdate() ```
T-SQL Date difference greater than an integer
[ "", "sql", "sql-server", "t-sql", "" ]
I have found a few posts (ex. [SQL Query to find the last day of the month](https://stackoverflow.com/questions/16646585/sql-query-to-find-the-last-day-of-the-month) , [Get the last day of the month in SQL](https://stackoverflow.com/questions/1051488/get-the-last-day-of-the-month-in-sql)) to **get** the last day of the...
If you are using SQL Server 2012 or above, use `EOMONTH`: ``` SELECT my_date, IsEndOfMonth = IIF(my_date = EOMONTH(my_date), 1, 0) FROM my_table ```
There are two simple ways that come to mind. First, would be: ``` select testDate , case when month(testDate) <> month(dateadd(d,1,testDate)) then 'pass' else 'fail' end endOfMonth from tblTest ``` This tests if 1 day after the testDate falls on a month other than the month testDate is currently on. If...
SQL - How to tell if a date is the last day of the month?
[ "", "sql", "sql-server", "t-sql", "datetime", "" ]
I have two tables : ``` video (ID, TITLE, ..., UPLOADED_DATE) join_video_category (ID (not used), ID_VIDEO_ ID_CATEGORY) ``` rows in video : 4 500 000 | rows in join\_video\_category : 5 800 000 1 video can have many category. I have a query works perfectly, 20 ms max to get result : ``` SELECT * FROM video WHERE ...
First, the comparisons are to two very different queries. The first returns a bunch of videos whenever it encounters them. The second has to read *all* the videos and then sort them. Try rewriting this as a `JOIN`: ``` SELECT v.* FROM video v JOIN join_video_category vc ON v.id = bc.id_video WHERE vc.ID_CAT...
If it is 1:Many, don't use an extra table between Video and Category. However, your row counts imply that it is Many:Many. If it is 1:Many, simply have the category\_id in the Video table, then simplify all the queries. If it is Many:Many, then be sure to use *this* pattern for the junction table: ``` CREATE TABLE m...
order by makes query slow
[ "", "mysql", "sql", "performance", "database-indexes", "" ]
I have a simple table `data` to record a stream of data with columns `recorded_at` DateTime and `value` Integer. The data is not distributed at regular intervals, there may be multiple rows per minute, or none for hours. If I want to select a single value this query works great for my purposes, selecting the closest r...
To get multiple points: ``` select d.* from data d where recorded_at > '2015-01-01 01:01:01' order by recorded_at limit 100 ``` To get them efficiently, create an index on `data(recorded_at)`: ``` create index idx_data_recorded_at on data(recorded_at); ``` Also, a `union` would probably *not* help your cause. Alth...
You need ORDER by ``` select * from data where recorded_at > '2015-01-01 01:01:01' and recorded_at < '2015-01-02 01:01:01' order by recorded_at limit 1 ``` This is edited after OP edited his question If you want to have multiple dates and want to get closest dates for each of these, I would suggest using a lookup ...
SQL - how can I efficiently select multiple closest time series data points
[ "", "mysql", "sql", "" ]
I need to checking a column where numeric or not in SQL Server 2012. This my case code. ``` CASE WHEN ISNUMERIC(CUST_TELE) = 1 THEN CUST_TELE ELSE NULL END AS CUSTOMER_CONTACT_NO ``` But when the `'78603D99'` value is reached, it returns `1` which means SQL Server considered this string as numeric...
Unfortunately, the `ISNUMERIC()` function in SQL Server has many quirks. It's not exactly buggy, but it rarely does what people expect it to when they first use it. However, since you're using SQL Server 2012 you can use the `TRY_PARSE()` function which will do what you want. This returns NULL: `SELECT TRY_PARSE('786...
Although `try_convert()` or `try_parse()` works for a built-in type, it might not do exactly what you want. For instance, it might allow decimal points, negative signs, and limit the length of digits. Also, `isnumeric()` is going to recognize negative numbers, decimals, and exponential notation. If you want to test a...
SQL Server's ISNUMERIC function
[ "", "sql", "sql-server-2012", "" ]
Every 5 minutes my historical table is updated (by another process) with a new record (TAG\_NAME remains the same but TIME and VALUE are updated). I am using the following query to return the LATEST record while also grouping by TAG\_NAME. ``` SELECT TAG_NAME,max(TIME) as max_time, (select value from historical wher...
You could get the combined maximum, so if two times are the same you get the biggest value. ``` select TAG_NAME, max(concat(time,value)) as time_value from historical group by TAG_NAME ``` If necessary you can split time and value in mySQL, but you can also split it in the app.
Try this: ``` SELECT TAG_NAME, max(`TIME`) as max_time, max(`value`) as max_value FROM historical WHERE `TIME` IS NOT NULL GROUP BY TAG_NAME ; ```
Mysql query with sub-selects taking too long..
[ "", "mysql", "sql", "" ]
I use 3 tables to insert data for a 4th table. My tables : ``` Typology id_typo------PK name_typology---- Country id_country---PK name_country--- Brut id_brut------PK name_typology-- name_country--- Structure id_struct---PK id_typo-----fk id_country---fk ``` I want transfert the data from the table Brut to the tab...
Use left join if you dont have matching rows in table y & z so that atleast you get all rows from table x: ``` INSERT INTO structure (id_struct,id_typo,id_country) SELECT x.id_struct,y.id_typo, z.id_country, FROM brut AS x left join typology AS y on trim(x.name_typology) = trim(y.name_typology) l...
May be issue about space to name Use this query to remove space ``` INSERT INTO structure (id_struct,id_typo,id_country) SELECT x.id_struct,y.id_typo, z.id_country, FROM brut AS x, typology AS y, country AS z WHERE trim(x.name_typology) = trim(y.name_typology) AND trim(x.name_country) = trim(z.name_country) ```
Why one line only is inserted?
[ "", "mysql", "sql", "" ]
I have a city column field in my table with city names starting with @,&,\*,',$...(example- %york,$pradesh,@lorida and also having values delhi,New york...) My requirement is to only getthe city names(like delhi,New york) in the field starting only with Alphabets from A-Z. Please help me out.
You can do this with the REGEXP (Regular Expression): ``` SELECT * FROM cities where name REGEXP '^[A-Za-z]'; ``` It now gets you the lines only Starting with A-Z and a-z: Before: [![enter image description here](https://i.stack.imgur.com/NpqJL.png)](https://i.stack.imgur.com/NpqJL.png) After: [![enter image desc...
Depending on your DBMS system you can use regular expressions in WHERE clause. For example, PostgreSQL provides them like this. ``` SELECT * FROM cities WHERE name ~* '^[A-Z]'; ``` MySQL/MariaDB provides them as well (see [here](https://dev.mysql.com/doc/refman/5.1/en/regexp.html)).
How to Select rows from a field starts only with A-Z in sql
[ "", "mysql", "sql", "" ]
I was wondering if it is possible to set a declared variable to a return value from a select result? Something like: ``` @WatchedSeconds SET @WatchedSeconds = 200 DECLARE @SelectedVideo int SET @SelectedVideo = (SELECT TOP 1 * FROM Video v WHERE v.VideoID = 12) IF @SelectedVideo IS NOT NULL BEGIN IF @Selecte...
You can try something like (declare variables first...) ``` SELECT TOP 1 @var1=col1, @var2=col2, @var3=col3, [...] FROM YourTable WHERE YourFilter ``` EDIT: All together this seems not to be the best approach... With SQL you should not think in values and single rows but rather in result sets (set based programming)...
You can do this simply by running: ``` SELECT @videoSeconds = v.Length FROM Video v WHERE v.VideoID = @VideoID ``` so as to not add the `SET` part. Also, you must make sure that only 1 row is being returned by the query, otherwise it will generate an error.
SQL Set variable to select result
[ "", "sql", "sql-server", "stored-procedures", "" ]
Having touble getting only values that appear once. I currently have some sql code that gets out the all the entries that have 0 percent. The problem is that two rows can contain the same person With different percentages. If one of these is above 0 then i dont want it to come out in the Query ``` abridged table: Name...
Your example SQL and abridged table don't match. However, this looks like the basic idea you are after: ``` select * from dbo.table a where a.percent = 0 and not exists ( select 'x' from dbo.table b where a.Name = b.Name and b.percent > 0 ); ```
This is one method ``` select name,0 as percent from abridged group by name having min(percent)=0 and max(percent)=0 ```
SQL getting values that apear once, not distinct
[ "", "sql", "sql-server", "" ]
I have a table in SQL Server with a huge range of numbers. I want to be able to set a color for a specific range of values. If it falls between 0 to 20% it should be red then 21 to 40% it should be blue and on so on. I have tried some code but it is returning some NULL values and i don't understand why. How do I fix t...
Using BETWEEN you create gap between values. You need to use comparison operators. Try this: ``` WITH cte([% APL Population],[% APL PopulationPercent]) AS ( SELECT [% APL Population] ,[% APL PopulationPercent] = ( [% APL Population] / NULLIF(Max([% APL Population]) OVER(), 0) ) * 100 FROM ...
You can't use `between` in this scenario. ``` WHEN [% APL PopulationPercent] < 20 THEN 'red' WHEN [% APL PopulationPercent] >= 20 AND [% APL PopulationPercent ] <40 THEN 'blue' ... ``` Issue was because 20.5 is grather than 20 and less than 21. Then don't match any `case` condition.
How to set a color for a specific range of values in SQL Server?
[ "", "sql", "sql-server", "" ]
I have a very simple table where I keep player bans. There are only two columns (not actually, but for simplicity's sake) - a player's unique ID (uid) and the ban expire date (expiredate) I don't want to keep expired bans in the table, so all bans where expiredate < currentdate need to be deleted. To see if a player ...
Unfortunately you cannot have a delete statement inside a select statement... I got you a [link from sqlite docos](https://www.sqlite.org/lang_select.html) for your reference. Select statements are only used for retrieving data. Although a `select` could be used in a sub-query for a `delete` statement, it would still ...
``` DELETE FROM TableName WHERE expiredate < CURDATE(); ```
DELETE rows in a SELECT statement based on condition
[ "", "sql", "sqlite", "select", "sql-delete", "" ]
I have a table like this: | id | conn\_id | read\_date | | --- | --- | --- | | 1 | 1 | 2010-02-21 | | 2 | 1 | 2011-02-21 | | 3 | 2 | 2011-02-21 | | 4 | 2 | 2013-02-21 | | 5 | 2 | 2014-02-21 | I want the second highest read\_date for particular 'conn\_id's i.e. I want a group by on conn\_id. Please help me figure this...
Here's a solution for a particular `conn_id` : ``` select max (read_date) from my_table where conn_id=1 and read_date<( select max (read_date) from my_table where conn_id=1 ) ``` If you want to get it for all `conn_id` using `group by`, do this: ``` select t.conn_id, (select max(i.read_date) from my_table i wh...
Following answer should work in MSSQL : ``` select id,conn_id,read_date from ( select *,ROW_NUMBER() over(Partition by conn_id order by read_date desc) as RN from my_table ) where RN =2 ``` There is an intresting article on use of rank functions in MySQL here : [ROW\_NUMBER() in MySQL](https://stackoverflow.com/...
Get second highest values from a table
[ "", "mysql", "sql", "" ]
I recently took a new job and I am trying to simplify some older queries left around and for the life of me I cannot figure out how to get this down into two queries using union. There's got to be a way but I cant simplify more than what I have. ``` select ( select avg (Employee.salary) from Employee left...
Since you are only selecting 1 field in each of the subqueries, you don't need a "Group By". Also, depending on the the data, you might not need to link in the Job\_title Table. If you need the Job\_title table then... ``` SELECT Min(salary), Max(salary), Avg(salary), 'Non-Exempt' AS Status FROM (SELECT employee.s...
You should be able to do something like this: ``` select min(salary), max(salary), avg(salary), 'Non-Exempt' as otherThingy from ( select Employee.salary from Employee left join Job_title on Employee.job_title = Job_title.Job_title where Employee.Exempt_Non_Exempt_Status='0' ) thingy UNION select min(s...
Sql 2012 Simplify Query Union
[ "", "sql", "left-join", "union", "" ]
I would like to know what I'm doing wrong. What I'm trying to do is get the half of each month, lets say if i input 8/1/2015 it should return 7/16/2015 and if i used 8/31/2015 it should return 8/15/2015. I created a Sql Script which is isn't running, here is the code. ``` SELECT case when @rank = 'R' then month(DATEA...
That is an invalid statement as it is missing a few brackets, and it maybe missing an else statement for the first case when. I am unsure if this is what you are trying to achieve. ``` DECLARE @rank AS VARCHAR(50) = 'R'; DECLARE @date_from AS DATETIME = '1/1/2015'; SELECT CASE WHEN @rank = 'R' THEN ...
I am creating a subquery sir, the complete code looks like this ``` set @refdatefrom = ( SELECT case when @rank = 'R' then month(DATEADD(day, -15, @date_from)+'/'+ case when day(DATEADD(day, -15, @date_from)) between 1 and 15 then 1 else 16 end +'/'+year(DATEADD(day, -15, @date_from) DATEADD(month, -1, @date_from)...
Nested case statement in sql for date
[ "", "sql", "sql-server", "" ]
I have a table that contains some corrupted records, because I forgot to add an `UNIQUE` index for two columns. Take a look at the following table for an example: ``` +----+-------------+--------+------------+ | id | uuid | object | project_id | +----+-------------+--------+------------+ | 1 | 73621000001 | sc...
In MySQL, you can use a `join`, but you need to be careful about the `NULL` values: ``` delete om from uuid_object_mapping om join (select MAX(uuid) as uuid, object, project_id from uuid_object_mapping group by object, project_id ) omkeep on omkeep.object = om.object...
Please use partition by along with order by uuid clause. Search for partion by. It is the best technique to remove duplicate.
How to remove 'duplicate' records?
[ "", "mysql", "sql", "" ]
There is a table of the following structure: ``` CREATE TABLE history ( pk serial NOT NULL, "from" integer NOT NULL, "to" integer NOT NULL, entity_key text NOT NULL, data text NOT NULL, CONSTRAINT history_pkey PRIMARY KEY (pk) ); ``` The `pk` is a primary key, `from` and `to` define a position in the sequ...
I don’t know if it counts as “elegant,” but I think this will do what you want: ``` with Lagged as ( select pk, case when lag("to",1) over (order by pk) is distinct from "from" then 1 else 0 end as starts, entity_key from history ), LaggedGroups as ( select pk, sum(starts) over (order by pk) ...
Just for fun & completeness: a recursive solution to reconstruct the (doubly) linked lists of records. [ this will **not** be the fastest solution ] NOTE: I commented out the ascending pk condition(s) since they are not needed for the connection logic. ``` WITH RECURSIVE zzz AS ( SELECT h0.pk , h0."to...
Partitioning function for continuous sequences
[ "", "sql", "postgresql", "postgresql-9.3", "window-functions", "" ]
Tried to show it as simple as possible. I want to SELECT Subject if 2 cells in a row are equal Table ``` --------------------------------------------- Subject --- username --- Lastpostername --------------------------------------------- subject A --- user1 --- user3 Subject B --- user2 --- user3 Subject C...
``` SELECT t.subject FROM tab AS t WHERE t.username = t.Lastpostername ORDER BY t.id DESC ```
suppose your table name is 'abc' & then you can create bellow query, ``` SELECT Subject from abc WHERE abc.username = abc.Lastpostername ORDER BY abc.id DESC; ```
SELECT if 2 cells in a row are equal
[ "", "mysql", "sql", "" ]
I have read lots of post about how to update multiple columns but still can't find right answer. I have one table and I would like update this table from another table. ``` Update table1 set (a,b,c,d,e,f,g,h,i,j,k)=(t2.a,t2.b,t2.c,t2.d,t2.e,t2.f,t2.g,t2.h,t2.i,t2.j,t2.k) from ( SELECT ..... with join ... where .....
TSQL does not support [row-value constructor](https://connect.microsoft.com/SQLServer/feedback/details/299231/add-support-for-ansi-standard-row-value-constructors). Use this instead: ``` UPDATE table1 SET a = t2.a, b = t2.b, (...) FROM ( SELECT ..... with join ... WHERE .... ) t2 WHERE table1.id = table2.id...
You don't need to use a sub-query you can also simply do the following.... ``` Update t1 set t1.a = t2.a ,t1.b = t2.b ,t1.c = t2.c ,t1.d = t2.d ....... from table1 t1 JOIN table2 t2 ON t1.id = t2.id WHERE ....... ```
Sql server update multiple columns from another table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I don't know how to phrase my question but I will try my best. I am trying to accomplish something like this for a report in SSRS. ``` SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE WHERE COLUMN1 = CASE WHEN @VAR1 IS NOT NULL THEN @VAR1 WHEN @VAR1 IS NULL THEN IN (SELECT COLUMN1 FROM TABLE2) END ``` How do I rewrite m...
No - you can't use the IN as you'd like. You just need to re-work your two possibilities a little. ``` SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE WHERE (@VAR1 IS NOT NULL AND COLUMN1 = @VAR1) OR (@VAR1 IS NULL AND COLUMN1 IN (SELECT COLUMN1 FROM TABLE2) ) ``` **For NULLs:** To match NULLS, you can try: `...
How about this: ``` SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE WHERE COLUMN1 in (SELECT distinct Coalesce(@VAR1, TABLE2.COLUMN1) FROM TABLE2 UNION SELECT @VAR1 --In case it is possible TABLE2 is empty ) ``` It should make use of any indexes on `Column1` in `TABLE`. If your column is nullable, any index...
Can 'IN' Be Used In A Case Statement?
[ "", "sql", "sql-server", "t-sql", "reporting-services", "" ]
Query should return Naveed Rizwan Fayaz and Ahmed Name. SQL query for students who have enrolled in English or Urdu course but not in both. ``` declare @Student table(sid int identity(1, 1), sname varchar(250)) declare @Course table(cid int identity(1, 1), cname varchar(250)) declare @StudentCourse table(cid int, si...
``` select sid, max(cid) from StudentCourse group by sid having count(*)=1 ```
I kept practicing and finally i did it by this query do you guys have any other in your mind. ``` select s.*, count(1) as TotalEnrolledCourses from @Student s inner join @StudentCourse sc on s.sid = sc.sid where sc.cid in (1,2) group by s.sid, sname having TotalEnrolledCourses = 1 ```
SQL query to get students who have enrolled in English or Urdu course but not in both
[ "", "sql", "sql-server", "database", "" ]
I'm trying to execute the SQL query, but getting 'Missing right parenthesis' error: ``` ((SELECT CUST_ACCT FROM CUSTMASTER WHERE SITE_ID IN (SELECT SITE_ID FROM HOUSEMASTER WHERE FTAX=1)) AND (SELECT CUST_ACCT FROM CUSTMASTER WHERE SITE_ID IN (SELECT SITE_ID FROM HOUSEMASTER WHERE MGT=1))) ``` I feel...
It looks like you're trying to get the results from two different queries as one by adding a `and` operator between them. This won't work. You could use a `union` query, but it looks like it can be reduced to the query below. Maybe this is what you really wanted? ``` SELECT CUST_ACCT FROM CUSTMASTER WHERE SITE_ID I...
I think there have to be UNION: ``` ((SELECT CUST_ACCT FROM CUSTMASTER WHERE SITE_ID IN (SELECT SITE_ID FROM HOUSEMASTER WHERE FTAX = 1)) UNION (SELECT CUST_ACCT FROM CUSTMASTER WHERE SITE_ID IN (SELECT SITE_ID FROM HOUSEMASTER WHERE MGT=1))) ```
Unable to execute the query
[ "", "sql", "" ]
I have the following ranking system. ``` SET @1=0; SELECT id, username, magic_xp, @i:=@i+1 AS rank FROM hs_users ORDER BY magic_xp DESC; hs_users id username magic_xp rank 988 5hapescape 14926854 1 737 Ozan 13034431 2 989 Kurt 13034431 3 6 LEGACY 0 4 11 Bobb...
**query** ``` set @i := 0; set @lagxp := null; select id, username, magic_xp, @i := if(@lagxp = magic_xp, @i, if(@lagxp := magic_xp, @i + 1, @i + 1)) as rank from hs_users order by magic_xp desc ; ``` or ``` SELECT id, username, magic_xp, IF (@score=hs_users.magic_xp, @rank:=@rank, @rank:=@rank+1) as ra...
In MySQL, the most efficient way is to use variables: ``` select t.*, (@rank := if(@magic_xp = magic_xp, @rank, if(@magic_xp := magic_xp, @rank + 1, @rank + 1) ) ) as rank from table t cross join (select @rank := 0, @magic_xp := NULL) params ord...
SQL User Score ranking by grouping
[ "", "mysql", "sql", "mysql-variables", "" ]
I will start out by saying, I am working with two tables, that are a bit of a mess in terms of how they are organized. I am currently pleading my case to get this adjusted, but have no control over them. So the organization of the tables is out of my control. I have one table that looks like this **Customer** ``` | ...
This should get you started: ``` SELECT id , name , date_joined , NULL year_joined , NULL month_joined , NULL day_joined FROM Customer WHERE id NOT IN (SELECT id FROM Customer2) UNION ALL SELECT id , name , NULL , year_joined , month_joined , day_joined FROM Customer2 ORDER BY id ; ``` Alterna...
You would have to make the data match up exactly. Something like this could work: ``` select * from ( select id, name, datepart(year,date_joined) as year_joined, datepart(month,date_joined) as month_joined, datepart(day,date_joined) as day_joined from customer union select id, name, year_joined, month_joined, ...
SQL Union prefer records from one table?
[ "", "sql", "sql-server", "duplicates", "union", "" ]
I am trying to connect two tables with left join and a date. **My SQL Query** ``` SELECT ord.`ordernumber` bestellnummer, his.`change_date` zahldatum FROM `s_order` ord LEFT JOIN `s_order_history` his ON ((ord.`id`=his.`orderID`) AND (ord.`cleared`=his.`payment_status_id`)) #AND MIN(his.`change_date`)...
You can group data by `ordernumber` ``` SELECT ord.`ordernumber` bestellnummer, MIN(his.`min_change_date`) as zahldatum FROM `s_order` ord LEFT JOIN `s_order_history` his ON ((ord.`id`=his.`orderID`) AND (ord.`cleared`=his.`payment_status_id`)) #AND MIN(his.`change_date`) WHERE ord.`ordertime` >= \...
MIN is an aggregate function so you can't use it in a JOIN straight up like you've tried above. You also are not comparing it to a value in your JOIN. You'll want to do something like: ``` his.`change_date` = (SELECT MIN(his.`change_date`) FROM s_order_history where ord.`id` = his.`orderID`) ``` in your `JOIN`.
Using left join with min
[ "", "mysql", "sql", "left-join", "min", "" ]
I'm looking for the following query in SQL - i.e. select ID from table where entry is within 'last hour' and **the last** check-in value was 'false'. Sample Data 'Table1': ``` ID(int), Check-In(boolean), Name(nvarchar), Entry(DateTime)*, PersonID(int) *DateTime Format: DD/MM/YYYY HH:MM:SS 1, true, Klaus, 14/05/2015 ...
This is other way using `partition`. I can't run the explain now. But my guess is this version have to do less scans than a `exists` for each row. [**SQL Fiddle Demo**](http://sqlfiddle.com/#!3/09463/2) > Take note fiddle doesn't have the 1 hour validation > Also sql server bit field is (0,1) not (false, true) * ...
To make sure the **last** checkin is `false`, you must check that there is not a newer row in the table. You can do that with a "not exists" clause. Try this one: ``` select * from table1 t1 where entry > DATE_SUB(NOW(), INTERVAL 1 HOUR) and checkin = false and not exists ( select * from table1...
Sql query to only select rows if last entry of item meets condition
[ "", "sql", "sql-server", "" ]
I have two tables with a many to many relationship and I am trying to merge the 2 tables in a select statement. I want to see all of the records from both tables, but only match 1 record from table A to 1 record to table b, so null values are ok. For example table A has 20 records that match only 15 records from table...
I'm imagining something like this. You want to pair of the rows side by side but one side is going to have more than the others. ``` select * /* change to whatever you need */ from ( select *, row_number() over (partition by "code#" order by "something") as rn from tableA ) as a full ou...
A regular Left-join should do it for you. ``` select tableA.* , tableB.* from tableA left join tableB on tableB.PrimaryKey = tableA.PrimaryKey ```
How to query 2 tables in sql server with many to many relationship to identify differences
[ "", "sql", "sql-server", "join", "m2m", "" ]
I have a query ``` with x as (select row_number() over(partition by FirstName order by Investment_DT desc) as rn, * from [dbSuppHousing].[dbo].[tblABC]) select Login_Name ,r.Role_Name ,Investment_DT ,FirstName ,LastName ,Login_Name ,Investment_DT ,Investment_ID from x jo...
``` with x as (select row_number() over(partition by FirstName order by Investment_DT desc) as rn, * from [dbSuppHousing].[dbo].[tblABC]) select Login_Name ,r.Role_Name ,Investment_DT ,FirstName ,LastName ,Login_Name ,Investment_DT ,Investment_ID into #temptable from x jo...
You simply need to put the insert statement between the common table expression (CTE) and your select statement: ``` with x as (select row_number() over(partition by FirstName order by Investment_DT desc) as rn, * from [dbSuppHousing].[dbo].[tblABC]) /* place insert statement here */ select Login_Name ,r....
Create a new table based on a query SQL Server
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to find geometric average of values from a table with millions of rows. For those that don't know, to find the geometric average, you mulitply each value times each other then divide by the number of rows. You probably already see the problem; The number multiplied number will quickly exceed the maximum all...
Very easy to check. For example, SQL Server 2008. ``` DECLARE @T TABLE(i int); INSERT INTO @T(i) VALUES (2147483647), (2147483647); SELECT AVG(i) FROM @T; ``` **result** ``` (2 row(s) affected) Msg 8115, Level 16, State 2, Line 7 Arithmetic overflow error converting expression to data type int. ``` There is no ma...
Most databases don't support a `product()` function the way they support an average. However, you can use do what you want with logs. The product (simplified) is like: ``` select exp(sum(ln(x)) as product ``` The average would be: ``` select power(exp(sum(ln(x))), 1.0 / count(*)) as geoaverage ``` or ``` select E...
How does the Average function work in relational databases?
[ "", "sql", "math", "rdbms", "" ]
``` cCode cName2 cFather iLevel cCatCode 1 Assets NULL 1 NULL 11 Current assets 1 2 NULL 1101 Cash on Hand 11 3 12012 110101 Cash on Hand 1101 4 **...
One method (that should work in all databases) is using a correlated subquery. For your particular data, this (or something very similar) will work in most databases: ``` update chart set cCatCode = (select c2.cCatCode from chart c2 where c2.cCode = chart.Father ...
1. For **SQL Server:** ``` update c1 set c1.cCatCode=c2.cCatCode from chart c1 join chart c2 on c1.cFather LIKE CAST(c2.cfather as varchar(max))+'%' and c1.cCode<>c2.cCode where c1.cCatCode IS NULL and c2.cCatCode IS NOT NULL ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/0ba29/1) demo...
I want to run a sql update query to a database to do the following
[ "", "sql", "" ]
Below is my Table Structure with data: ``` ID Date EmpId 67 2015-08-24 10:44:33.087 293 68 2015-08-24 10:41:49.950 293 69 2015-08-24 10:42:49.951 293 70 2015-08-24 10:45:15.157 013 71 2015-08-24 10:46:33.131 013 72 2015-08-24 10:42:33.134 013 73 2015-08-24 10:47...
``` select ID,Date,EMPID from ( select ID, Date, EMPId, ROW_NUMBER() over (partition by EMPId order by Date desc) as RowNUm from Employee ) A where RowNUm = 1 ```
Try this ``` WITH TempId AS ( SELECT *, row_number() OVER(PARTITION BY EmpID ORDER BY ID desc) AS [Num] FROM Employee1 ) DELETE TempId WHERE [Num] > 1 --For deleting record Select * from Employee1 --For Selecting record ``` Find solution in Fiddle <http://sqlfiddle.com/#!6/80f3d/3>
Delete Duplicate Records with condition
[ "", "sql", "sql-server", "t-sql", "" ]
I have query ``` SELECT Site, Risk_Time_Stamp,COMPUTER_NAME, [IP_ADDR1_TEXT],Number_of_Risks FROM dbo.sem_computer WHERE [dbo].[V_SEM_COMPUTER].COMPUTER_ID = SEM_COMPUTER.COMPUTER_ID GROUP BY Site, Risk_Time_Stamp,COMPUTER_NAME, [IP_ADDR1_TEXT],Number_of_Risks ``` which gives 4 rows of output and another...
You are not getting 1,000 rows because the JOIN doesn't have 1,000 matches. If you want to get all the rows, even when there's no match, use a LEFT JOIN starting on SEPM\_Site table. ``` ; with cte as (SELECT Site, Risk_Time_Stamp,COMPUTER_NAME, [IP_ADDR1_TEXT],Number_of_Risks FROM dbo.sem_computer WHERE [dbo]...
I think you want a `left join`: ``` with cte (. . .) select * from SEPM_Site ss left join cte on cte.Site = ss.Site ``` Note: I reverse the order of the tables. For your original query, you would want a `right join`. I prefer `left join`.
SQL with cte, how to concat data, not join
[ "", "sql", "sql-server", "common-table-expression", "" ]
I have a very unusual request. I have some filtered data in a table, columns being ID, Date, and Event. Event is an XML column where in one of the tag is StartWork and EndWork. From huge data I have filtered out data for a request. My Sample data has 6 rows, in sequence of StartWork, EndWork, StartWork, EndWork and so ...
``` Select DateDiff(minute,StartWork.datacreated,EndWork.datacreated) from (Select datacreated,LineNb=row_number() over(Order by datacreated) from Table where eventdata.value('(/data/status/text())[1]','varchar(15)')='StartWork') StartWork INNER JOIN (Select datacreated,LineNb=row_number() over(Order by datacreated) ...
This should help you: ``` declare @xmlStart XML='<data><status>StartWork</status></data>'; declare @xmlENd XML='<data><status>EndWork</status></data>'; declare @tbl TABLE(id INT,datecreated DATETIME,eventdata XML); INSERT INTO @tbl VALUES(1,{ts'2015-07-29 09:17:34'},@xmlStart) ,(2,{ts'2015-07-29...
transform sql rows to column
[ "", "sql", "sql-server", "pivot", "" ]
I want to get records who are about reach todays date with in 2 days ProjectEnddt. i want to show Projects who are going to end with in 2 days. want to show 2 days before.
**Query** ``` SELECT ProjectEndDt , ProjectRenewalDt , ProjectUpgradeDt FROM tbl_project WHERE CONVERT(VARCHAR(10), DATEADD(DAY, 2, ProjectEndDt)) >= CONVERT(VARCHAR(10), GETDATE()); ```
Try this: ``` SELECT ProjectEndDt ,ProjectRenewalDt ,ProjectUpgradeDt FROM tbl_project WHERE CONVERT(DATE,[ProjectEndDt]) < DATEADD(DAY, 3,CONVERT(DATE,GETDATE())) ```
how to get records who is reaching todays date
[ "", "sql", "sql-server", "" ]
I want to select a record from a table where the date format stored as **'Jan 27 2015 12:00AM'** When I select I should covert the date to the following format **'27/01/2015 00:00:00'**. I tried the following it works for Date but not for TIME. So I used get date. ``` select CONVERT(VARCHAR(10), CONVERT(date,StartDa...
## Convert MMM dd yyyy HH:MM[AM|PM] to dd/MM/yyyy hh:mm:ss ``` Declare @Date VARCHAR(20) = 'Jan 27 2015 12:05AM' SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, @Date),103) + ' ' + CONVERT(VARCHAR(8), CONVERT(DATETIME, @Date),108) Result: 27/01/2015 00:05:00 ```
Check this: Hope this answers your question... EDIT: Hope this is the format you need:L ``` declare @d VARCHAR(100) ='Jan 27 2015 11:59AM'; SELECT CONVERT(VARCHAR(10),CAST(@d AS DATE),103) + ' ' + CAST(CAST(@d AS TIME) AS VARCHAR(8)) ``` I'm not used to the AM/PM format and I had assumed, that 12:00AM is midday and...
SQL Select Specific Date format dd/mm/YYYY hh:mm:ss
[ "", "sql", "sql-server", "date", "datetime", "" ]
The query below calculates what we need but for only one specific column. How can we do this for all the columns within that table, without having to duplicate the case statement multiple times. This needs to be done for hundreds of tables, so duplicating the case statement is not ideal. ``` Select SUM(cast(case when...
Solution by Jens Suessmeyer from [Finding the percentage of NULL values for each column in a table](http://blogs.msdn.com/b/samlester/archive/2012/09/22/tsql-solve-it-your-way-finding-the-percentage-of-null-values-for-each-column-in-a-table.aspx) ``` SET NOCOUNT ON DECLARE @Statement NVARCHAR(MAX) = '' DECLARE @Statem...
First, you can simplify the logic to: ``` Select AVG(case when column is null then 0.0 else 1.0 end) from [Table] ``` Then, you can generate the code. The following generates the `from` expressions. You can copy them over into the query: ``` select replace(' avg(case when [@col] is null then 0.0 else 1.0 end) a...
How do you calculate data completeness for multiple tables based on null values within columns?
[ "", "sql", "sql-server", "database-design", "" ]
I have table `borrower` with a column named `given_names`. I want a SQL query to display all the initials of the `given_names` column Meaning every first letter of a word in the `given_names` column I tried: ``` select substring(cast (given_names as text),1,1) + substring(given_names,charindex('')+(' ',given_names)+...
As mentioned in my comment above, `regexp_split_to_table` will help out a lot here. The idea is that we split your names up into seperate records using a space as a delimiter. `split_to_table` will generate a new record for each token encountered. We can also capture a `row_number()` for each `firstname` so we can st...
I got another solution using *regex* ``` SELECT string_agg(arr [1], '') AS initials FROM ( SELECT row_number() OVER () AS rn ,regexp_matches(fname, '\y(?!(the|of)\y)\w', 'gi') arr FROM tblnames ) t GROUP BY rn ``` [**SQL Fiddle example**](http://sqlfiddle.com/#!15/a684e/2) --- Solution 1 ``` SE...
First letter of each word in a column
[ "", "sql", "postgresql", "" ]
Input : 123 Output : One Two Three No Hundreds No Thousand No Thirty-Twenty Only Clean Digits are to be spelled.Has Anyone Got an Idea about it ?
In *SQL-Server* you can do It with `CASE` statement, you have to use `COALESCE` to convert null values to blank strings, something like: ``` DECLARE @val INT = 123 SELECT COALESCE(CASE WHEN @val LIKE '%0%' THEN 'Zero ' END,'') + COALESCE(CASE WHEN @val LIKE '%1%' THEN 'One ' END,'') + COALESCE(CASE W...
Try this ``` declare @Input varchar(max)='123' declare @ouput varchar(max)='' declare @temp int=1 declare @char nvarchar(max)='' WHILE @temp <=LEN(@Input) BEGIN set @char = SUBSTRING(@Input, @temp, 1) set @ouput += (case when @char=1 then 'One ' when @char=2 then 'Two ' when @char=3 then 'Three ' else 'so on...
Do we have Sql Query That Returns Single Digits Like "One Two Three" When we give input 123?
[ "", "sql", "sql-server", "" ]
I have to update a table in oracle db as batch of 10k. I tried this: ``` BEGIN WHILE (true) LOOP UPDATE TOP (10000) CUSTOMERS SET ACTIVE = 'N' WHERE ACTIVE='Y'; IF sql%notfound THEN EXIT; END IF; COMMIT; END LOOP; END; ``` It doesn't works as plsql does...
your pl/SQL block, using JVA's suggestion, should be completed like this (somce you are new to pl/sql I am adding some syntactical suggestions that you could be interested in): ``` BEGIN -- WHILE (TRUE) can be omitted: "loop ... end loop;" -- already is an endless loop LOOP UPDATE CUSTOMER...
``` UPDATE CUSTOMERS SET ACTIVE = 'N' WHERE ACTIVE='Y' AND ROWNUM <= 10000; -- first 10k rows ```
updating 1 million records in oracle DB as batch of 10k;
[ "", "sql", "database", "oracle", "plsql", "sqlplus", "" ]
I'm trying to perform a simple `IF` statement. I have a table named 'products' that has a column `count` which is a current count of that specific product in stock. The `count` column in the database is of data type `INT`. I can only get this to work if I statically assign the variable `@count`. If I assign a select s...
Try: ``` DECLARE @count INT SET @count = isnull((SELECT TOP 1 [count] from products WHERE [count] > 1),0) IF (@count > 1) BEGIN PRINT 'It works!' END ``` count is a [SQL Keyword](https://msdn.microsoft.com/en-us/library/ms189822.aspx) that's why you need to use `[]` when you are using any `keywords` a...
You'd normally use EXISTS ``` IF EXISTS (SELECT * from products WHERE count > 1) BEGIN PRINT 'It works!' END ```
SQL Server : Not So Simple IF Statement
[ "", "sql", "sql-server", "database", "" ]
I want to use IF-Else in Insert Query in sproc. I have tried this code, and getting error. What's wrong? ``` create procedure sp_m_ii_2_kaydet @mtu int, @mod int, @moid int, @uid int as insert into m_ii2_alisfatura (muhtur, mturid, muhodm, modmid, uid) values (@mtu, IF (@mtu = 3) SELECT MAX(id) FROM m_ii1_vsf_p...
That's not a valid syntax try this You need to use three different insert statements ``` CREATE PROCEDURE Sp_m_ii_2_kaydet @mtu INT, @mod INT, @moid INT, @uid INT AS IF ( @mtu = 3 ) INSERT INTO m_ii2_ali...
I am getting wrong MAX(ID) values with this combined code; ``` ...procedure [dbo].[sp_m_ii_2_kaydet] @mtu int, @mod int, @uid int as declare @mtuid int declare @modid int if (@mtu = 3 and @mod = 1) set @mtuid = (select MAX(id) from m_ii1_vsf_personel) set @modid = (select MAX(id) from m_kasa_personel); if (@m...
Using IF - ELSE in SQL Server Insert Query
[ "", "sql", "sql-server", "t-sql", "" ]
What are alternatives to UNION ALL for joining many tables to see aggregated data from many source systems? I am looking for solution beyond T-SQL. Suppose we have 3 source tables and we want to join them by id: TableA ``` id Adata 1 8383 2 2707 3 6181 4 6708 ``` TableB ``` id Bdata 1 2669 1 8582 2 ...
With your example, a simple join seems to be enough, why would you need to `UNION ALL` ? ``` SELECT A.id, SUM(A.Adata), SUM(B.Bdata), SUM(C.Cdata) FROM TableA A JOIN TableB B ON A.id = B.id JOIN TableC C ON A.id = C.id GROUP BY A.id ``` If you want to show the overall total, you can use `WITH ROLL...
You are miximg concepts. UNION ALL is something rarely needed and used. You use it when glueing similar result sets together. This is not the case here. In order to join tables, you should use joins of course. You get a result row per group you state with GROUP BY (the ID in your case). You use aggregation functions s...
Alternatives to UNION ALL to get aggregate data
[ "", "sql", "sql-server", "join", "union-all", "" ]
In this query it is partitioning the records but i need to assign row number for all the result set a row number should not be repeated it should be unique fpr each row.Anyone help ? Thanks in advance. ``` select * from Store order by row_number() over (partition by category order by storename),category ``` Tab...
Try something like this: ``` WITH data AS ( SELECT ROW_NUMBER() OVER (PARTITION BY Category ORDER BY Category) rn, * FROM STORE ) SELECT ROW_NUMBER() OVER (ORDER BY rn, Category) rn , StoreId , StoreName , Category , Price , Quantity , Address FROM data ...
``` SELECT ROW_NUMBER() OVER (ORDER BY Category) AS Id, -- New Id * FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY Category ORDER BY StoreName) PartitionId, * FROM Store ) data WHERE PartitionId = 1 -- Get one record for each category ``` [SQL Fiddle](http://sqlfiddle.com/#!6/76...
Assigning unique ROW NUMBER() for all the PARTITIONED RECORDS
[ "", "sql", "sql-server", "window-functions", "" ]
Every time implement this part of my select statement I get an Divide by zero exception. I tried replacing ISNULL with NUllIF. Same error. here is my code: ``` isnull([Balance], 0) * isnull(sce.tradepoundsperunit, 0) * (isnull(limitallocation_limitcommodity.priceperpound, 0) / CASE WHEN ISNULL(limit_limitcommodity.pr...
I think any of the clauses: ISNULL(limit\_limitcommodity.priceperpound, 1) ISNULL(l.PoundsPerUnit, 1) ISNULL(targetu.bushelsperunit, 1) could be returning 0 because you are only checking for null and not zero. e.g. if l.PoundsPerUnit=0 then checking ISNULL(l.PoundsPerUnit,1) is still going to return zero. I think tha...
I believe the answer may be in this bit: ``` * ISNULL(targetu.bushelsperunit, 1) ``` If targetu.bushelsperunit is 0, the code could be executing that \* before it executes the previous /, resulting in a divide by 0. Is that field meant to be in the denominator?
Divide by zero error in Sql View
[ "", "sql", "select", "view", "dividebyzeroexception", "" ]
We are using 3-Tier Architecture in ASP.Net. There are 3 Layers 1. Presentation 2. Business 3. Data Access The Data Access Layer contains the GetData and ExecuteQuery etc function. What I want to know is that, that want to call the View directly from the Presentation Layer. Is there any chance of SQL injection in ca...
How are you "calling a view"? If you're running an ad-hoc query of: ``` SELECT <columns> FROM View WHERE ColumnX = 'Y' ``` and if that query is being constructed using (potentially) hostile input then yes, of course that can be subject to SQL injection - the whole point of injection is that the attacker can change th...
As you are writing the query as follows that takes value from a textbox, 100% there is posibility for sql injection. ``` string query = "select * from ViewTeacher where FID = " + txtName.Text; ```
SQL Injection on Views
[ "", "sql", "sql-injection", "3-tier", "" ]
I require data to be returned from table in following format. ``` <Root> <Property name="test1">text1</Property> <Property name="test2">text2</Property> <Property name="test3">text3</Property> <Property name="test4">text4</Property> </Root> ``` I've tried the code from other post [SQL Server for xml path add ...
The element name used i path is repeated for each row returned. If you want to repeat the same element name for one row you need to specify the element name in the column alias and you need to separate the different elements with a empty column value. ``` select 'test1' as [Property/@name], 'text1' as Property,...
You can achieve your desired output using following query: ``` select T.Name as 'Property/@name', T.[Text] as 'Property' from ( select 'test1' as Name, 'text1' as [Text] union all select 'test2', 'text2' union all select 'test3', 'text3' union all select '...
SQL FOR XML Path, returning multiple child elements
[ "", "sql", "sql-server", "xml", "xpath", "" ]
Lets say I have a table like this: ``` ID_COMPANY ID_EMPLOYEE SALARY COMP0001 EMP0001 200 COMP0001 EMP0002 100 COMP0001 EMP0003 300 COMP0002 EMP0001 200 COMP0002 EMP0003 200 COMP0003 EMP0002 200 ``` I want to add a column to my table so it can `SUM` salary from...
You can pre-calculate amounts groupped by employee in CTE and then join that CTE in your query: ``` ;with cte_Totals as ( select ID_EMPLOYEE, sum(SALARY) as TOTAL from your_table group by ID_EMPLOYEE ) select ID_COMPANY, ID_EMPLOYEE, SALARY, T1.TOTAL from your_Table as T left outer j...
``` select id_employee, sum(salary) from [table] group by id_employee ``` This will not 'add' the column to the table, but will output the result. Since this data would change if a new record is added it would be better to generate it dynamically with a query. If you must store it, you should store the result in a mat...
How to Select X, SUM (X)?
[ "", "sql", "sql-server-2008", "" ]
I need the sum of the employees Money made but grouped into the months between two dates, however I have a date field and want the name of the months and year as two separate fields. This query is showing the un-grouped information - minus the year and month in the formats required. Once I have the Employees money ma...
Here is a query: ``` SELECT Employee.Name , Employee.ID , Sum(Sales.Money) , Year(Sales.Date) , Month(Sales.Date) FROM Database.Sales.Sales INNER JOIN Database.Employee.Employee ON Sales.ID=Employee.ID WHERE Sales.Date BETWEEN '2000-01-01' AND '2001-01-01' g...
There is a `Month()` and `Year` functions you can use and group by. Incorperate something like this into your query: ``` SELECT Employee.Name, Employee.ID, MONTH(Sales.Date) as `month`, YEAR(Sales.Date) as `year`, SUM(Sales.Money) FROM Database.Sales.Sales INNER JOI...
SQL Grouping by Month on dates fields
[ "", "mysql", "sql", "sql-server", "t-sql", "date", "" ]
I have to display a table of data sorted by the following condition First should be Private field1 and field2 Match Private field1 Match Private Non-Private field1 and field2 Match Non-Private field1 Match Non-Private I'm very weak in SQL and only order by I know is ``` select * from sampleTable order by ...
You could try something like: ``` SELECT * FROM sampleTable ORDER BY private DESC, CASE WHEN field1 IS NULL THEN 1 ELSE 0 END, CASE WHEN field2 IS NULL THEN 1 ELSE 0 END ``` I'm assuming 'Match' means 'Not Null'? **UPDATE** I should point out that if non-null values in field1 and field2 are to be sorted too,...
I completely misunderstood your question at first, here a new answer: ``` SELECT * from sampleTable ORDER BY private desc, CASE WHEN field1=field2 THEN 2 WHEN field1>'' THEN 1 END desc ``` Again the meaning of `'Match'` is unclear. But seeing you have accepted Michael's answer already I guess what you really mea...
ORDER BY using specific order in SQL Server 2012
[ "", "sql", "sql-server-2012", "" ]
I have the following SELECT statements in a stored procedure: ``` SELECT COUNT(*) AS TotalCreditDenied FROM Table1 WHERE StatusId = 8 AND ManufacturerId = 1; SELECT COUNT(*) AS TotalCreditApproved FROM Table1 WHERE StatusId = 7 AND ManufacturerId = 1; SELECT SUM(CreditInvoiceAmount) AS TotalCredi...
You can do this with a `SELECT ... WHERE ManufacturerId = 1` and `CASE` ``` SELECT COUNT(CASE WHEN StatusId = 8 THEN 1 END) AS TotalCreditDenied, COUNT(CASE WHEN StatusId = 7 THEN 1 E...
You should be able to consolidate those into something like the following: ``` Select SUM(CASE StatusId WHEN 8 THEN 1 ELSE 0 END) as TotalCreditDenied , SUM(CASE StatusId WHEN 7 THEN 1 ELSE 0 END) as TotalCreditApproved , SUM(CreditInvoiceAmount) as TotalCreditPaid , SUM(CASE StatusId WHEN 3 THEN Appro...
Least costly method of combining multiple select statements to output one row
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table of `posts` like this ``` +--------------------+--------------+ | Field | Type | +--------------------+--------------+ | id | int(11) | | title | varchar(255) | | body | text | | published_at | datetime | +-----------...
Solution without using UNION/CASE ``` SELECT * FROM posts ORDER BY DATE(published_at)=DATE(NOW()) DESC, DATE(published_at)<DATE(NOW()) DESC, DATE(published_at)>DATE(NOW()) ASC` ``` check if this works. Its working fine with stimulated data. You can change desc to asc according to your sorting requirement ...
There is a possible solution without UNION (ALL): ``` select id, title, published_at, case when date(published_at) = curdate() then '1-now' when date(published_at) < curdate() then '2-past' else '3-future' end as order_group from t order by order_group asc, published_at asc; ``` <http://sqlfiddle.com/#!...
Sorting data according to current date
[ "", "mysql", "sql", "" ]
I support a SQL database for a third party software package. They have a lot of what they call "Shadow Tables", really just audit tables. This is all fine and good but their system does not clean up these tables so it is up to me to do so. They also add new "Shadow Tables" without notice with every upgrade. The old way...
I do not know of anyway to get away from dynamic SQL when you do not know the table names ahead of time. SQL Server has a feature where you can do variable assignment in a `select` statement, once for each row returned. This can be used to eliminate the cursor and pass one string with all the `delete` statements to SQL...
I don't think using using `cursor` and `dynamic query` here is a bad idea One way is to append the delete queries and execute it at the end after generating all the delete queries. Btw, cursor is just used for framing dynamic query so it is not a big deal ``` DECLARE @workingTable varchar(128); DECLARE @sqlText nvar...
Run the same query against multiple tables without dynamic sql
[ "", "sql", "sql-server", "t-sql", "dynamic-sql", "" ]
I'm storing UUID v4 values in a PostgreSQL v9.4 table, under column "id". When I create the table, is there any difference in following write or read performance whether I define the "id" column as [VARCHAR(36), CHAR(36)](http://www.postgresql.org/docs/9.4/static/datatype-character.html), or [UUID](http://www.postgres...
Use `uuid`. PostgreSQL has the native type for a reason. It stores the uuid internally as a 128-bit binary field. Your other proposed options store it as hexadecimal, which is very inefficient in comparison. Not only that, but: * `uuid` does a simple bytewise sort for ordering. `text`, `char` and `varchar` consider ...
UUID would be the fastest because its 128 bits -> 16 bytes and comparisons are done numerically. Char(36) and varchar(36) seems to be the same and slow: <http://www.depesz.com/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/>. The server should check EOF to determine the job of reading the value has finished or not f...
Performance difference between UUID, CHAR, and VARCHAR in PostgreSql table?
[ "", "sql", "postgresql", "database-performance", "sqldatatypes", "" ]
I am a software developer and I was recently approached by DBA to optimize the query that an app of mine is using. DBA reported that query takes about 50% of CPU and high I/O operations when it runs. The query is pretty straight forward and I am unsure how to optimize it. **Question 1:** How can I optimize this query?...
It seems like you have a misconception about indexes. Indexes don't combine with each other, so it's not a question of having a column "indexed" or "not indexed". It's not good to have a separate index for individual columns. It's about having indexes with several columns that much up with individual queries. An index ...
I would see if I got better results with ISNULL instead of COALESCE. The other thing is looking at the indexes. You listed the fields that are indexed. If those fields are covered by several indexes, I suggest making one good covering index for this query. A covering index is one where all of the data needed by the q...
Optimize SQL query, TSQL
[ "", "sql", "sql-server", "t-sql", "query-optimization", "" ]
I am trying to create a table using following code in oracle 10g and each time I am getting the following error: > ORA-00923: FROM keyword not found where expected The query is as follows: ``` Create table Tab2 nologging as select /*+parallel(a,6)*/ Tab1col1, Tab1col2, MAX(case when tab1Col5 = '21-aug-2015' then Ta...
try ``` Create table Tab2 nologging as select /*+parallel(a,6)*/ Tab1col1, Tab1col2, MAX(case when tab1Col5 = '21-aug-2015' then Tab1Col3 end) "21AUGBALANCE", MAX(case when tab1Col5 = '22-aug-2015' then Tab1Col3 end) "22AUGBALANCE", MAX(case when tab1Col5 = '23-aug-2015' then Tab1Col3 end) "23AUGBALANCE" from Tab1 ...
you have problem with column aliases try use double quotes "" like this ``` Create table Tab2 nologging as select /*+parallel(a,6)*/ Tab1col1, Tab1col2, MAX(case when tab1Col5 = '21-aug-2015' then Tab1Col3 end) "21AUGBALANCE", MAX(case when tab1Col5 = '22-aug-2015' then Tab1Col3 end) "22AUGBALANCE", MAX(case whe...
Error - Keyword not found where expected
[ "", "sql", "oracle", "ddl", "" ]
I have one table with contains foreign key "columnA" column and one more column "columnB". I want to prevent adding same values in "columnB" but only for same value in "columnA"... ``` columnA columnB 1 'a' 1 'a' - this is not allowed 2 'a' - this is allowed ``` From my perspective ...
A Unique constraint would work. ``` alter table TableName add constraint UQ_consrtaint unique(columnA, columnB); ``` That should do it.
It looks like you need to create a primary key like this: ``` DECLARE @DataSource TABLE ( [A] TINYINT ,[B] CHAR ,PRIMARY KEY([A], [B]) ); INSERT INTO @DataSource ([A], [B]) VALUES (1, 'a'); -- ok INSERT INTO @DataSource ([A], [B]) VALUES (2, 'a'); -- ok INSERT INTO @DataSource ([A], [B]) VALUES (1, 'a'); ...
How to add unique constraint that depends of the foreign key values?
[ "", "sql", "sql-server", "t-sql", "" ]
I need to round off couple of fields that I extract from Teradata SQL assistant. Currently I am using CAST(Field1 as numeric(20,2)) as Field1 18.529 is rounded to 18.53 but 36.425 is rounded to 36.42 instead I am expecting 36.43 How can this be achieved?
The rounding rules for CASTs depend on a global setting, *RoundHalfwayMagUp* in dbscontrol. You might try the ROUND function which defaults to the rounding rules you prefer: ``` ROUND(36.425,2) ```
I found an old post on a forum [here](https://forums.teradata.com/forum/database/how-to-use-round-function-in-teradata) which states that the `RoundHalfwayMagUp` controls whether .5 rounds up or down. See [the docs](http://www.info.teradata.com/HTMLPubs/DB_TTU_13_10/index.html#page/Utilities/B035_1102_109A/DBScontrol.1...
Issue in rounding off the values extracted from Teradata SQL assistant
[ "", "sql", "decimal", "rounding", "teradata", "" ]
I need to find duplicate record (with master record id and duplicate record ids): ``` select ciid, name from ( select ciid, name, row_number() over ( partition by related_id, name order by updatedate desc) rn ) where rn = 1; ``` This gives me the master record IDs, but it also includes records without duplicates. ...
I haven't tested this (because I don't have real data and am too lazy to create some), but it seems something along these lines might work: ``` with has_duplicates as ( select related_id, name from yourtable group by related_id, name having count (*) > 1 ), with_dupes as ( select y.ccid, y.name, row_...
I ended up using similar query in my question: ``` select ciid, name from ( select ciid, name, row_number() over ( partition by related_id, name order by updatedate desc ) rn, count(*) over ( partition by related_id, name desc ) cnt ) where rn = 1 and cnt > 1; ``` Works surprisingly well. The master rec...
How to select both row_number and count over partition?
[ "", "sql", "oracle", "window-functions", "" ]
I have done a very simple example with 2 tables: **Table A: user\_client** ``` id | username --------------- 2222 | test ``` **Table B: user\_client\_contact** ``` client_id | country -------------------- 2222 | latvia 2222 | estonia ``` I get the result: ``` id ----- 2222 2222 ``` but the result wha...
Just use the [distinct](http://www.w3schools.com/sql/sql_distinct.asp) keyword to eliminate the duplicate: ``` select distinct user_client.id from user_client left join user_client_contact on user_client_contact.client_id = user_client.id ``` if you only want `user_client.ids` that have an entry in the `user_clie...
That's what a left join does. If you don't want information from table B, it sounds like maybe you want a semi-join. Like this: ``` select user_client.id from user_client where exists ( SELECT 'contact' FROM user_client_contact WHERE user_client_contact.client_id = user_client.id ) ``` Or, if you only want a sin...
Left join brings every row from table B
[ "", "sql", "" ]
i just want to create an sql query and the result is something like on the image., something like Fibonacci sequence in SQL. Ex. Column 1: 10 , then the value of Result column is Result: 10 , since that is the first row. , then assuming that the value of column1 2nd row is 50, then the value of Result 2nd row will be...
If you are using `MSSQL2012` or higher you can use `OVER` clause. ``` SELECT t2.id, t2.value, SUM(t2.value) OVER (ORDER BY t2.id) as [Result] FROM Test01 t2 ORDER BY t2.id; ``` **`sql fiddle demo`**
You can try this ``` CREATE TABLE #TEST(ID INT,VALUE INT) INSERT INTO #TEST VALUES (1,10),(2,20),(3,30),(4,40),(5,50),(6,60),(7,70) ;WITH CTE as ( SELECT ID,VALUE,VALUE AS RESULT FROM #TEST WHERE ID=1 UNION ALL SELECT T.ID,T.VALUE,T.VALUE+C.RESULT FROM #TEST T INNER JOIN CTE C ON T.ID = C.ID+1 ) SELECT *...
How to continously add values of starting row and next row to it
[ "", "sql", "sql-server-2012", "cumulative-sum", "" ]
I have a table with ID and Dept. Table is ``` id dept salary date 1 30 2000 8/25/2015 12:06:54.870 PM 2 20 5500 7/12/2015 12:06:54.870 PM 3 30 6700 11/21/2013 12:06:54.870 PM 4 30 8900 4/16/2009 12:06:54.870 PM 5 30 9900 6/29/2014 12:06:54.870 PM 6 10 1120...
This is the best way I know. Please do post if anyone knows a better solution: I have named your table `sal` ``` DECLARE @id INT , @max INT , @dep INT , @all VARCHAR(255) SELECT @id = 1 , @max = MAX(id) FROM sal SELECT * INTO #tmp FROM sal WHILE (1=1) BEGIN SELECT @...
A bit simpler solution for those who want this to work for particular query: ``` DECLARE @res_csv VARCHAR(10000) BEGIN SELECT SomeIntField INTO #tmp FROM YourTblName WHERE 1=1 -- a hardcoded query UPDATE #tmp SET @res_csv = @res_csv + case when @res_csv is not NULL then ',' end + CONVERT(VARCHAR, Som...
Sybase: How do I concatenate rows in sybase column
[ "", "sql", "t-sql", "concatenation", "sybase", "" ]
<http://sqlfiddle.com/#!9/ea4d2/1> Here is the SQLfiddle to look at. storepkid 16 is repeated 2 times. But I want it only one time. I tried DISTINCT but it eliminate entire duplicate row so it's not working in this case. What changes do I need to make in query to get proper result? Please help. NOTE: forgot to mentio...
You can use `max` function. Use the below query ``` SELECT p.storepkid, max(p.selldate) AS recentselldate FROM (SELECT storepkid, purchasedatetime AS selldate FROM t_product_purchase UNION ALL SELECT storepkid, starttime AS selldate FROM t_service_purchase UNION ALL SELECT storepkid, sellda...
Here Is Correct Code i tried it at your fiddle [Fiddle](http://sqlfiddle.com/#!9/ea4d2/7) I also ran into a similar problem ---> [Joining Two Tables](https://stackoverflow.com/a/32178452/4947143) ``` SELECT p.storepkid, p.selldate AS recentselldate FROM (SELECT storepkid, purchasedatetime AS selldate FROM t_product_...
Want to eliminate duplicate record based on only column value
[ "", "mysql", "sql", "" ]
I have a date value as below in my table. ``` 2015-05-25 ``` I want to convert the values as below. ``` 05/25 ``` How to do this? Date value is having date datatype.
Use the `CONVERT` function to change it to `mm/dd/yy` (style 1) And the `LEFT` function to only select `mm/dd` (integer\_expression 5) ``` SELECT LEFT(CONVERT(date, 1), 5) FROM yourtable ``` Input: ``` 2015-05-25 ``` Output: ``` date 05/25 ```
Try: ``` select convert(varchar(5),getdate(),101) ```
change the date format in sql server
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table with data in the following format ``` col1 col2 a1 a2;a3;a4 b1 b2 c1 c2;c3 d1 null ... ``` I'm trying to split the strings, get unique combinations of col1/col2 and insert them into tableB. So the expected outcome should look like this: ``` a1 a2 a1 a3 a1 a4 b1 b2 c1 c...
Don't use connect by to split string into rows. Use a PL/SQL procedure that does varchar2 -> collection split. For a ad-hoc kind of query, stick with `xmltable` as a simple way to split string into rows (it is a bit slower than PL/SQL). The following kind of query is expected to take 3-4 seconds for each input 1000 ...
One thing you can try is to select all the `distinct` values. ``` INSERT INTO tableB (col1, col2) SELECT distinct col1, (regexp_substr(col2,'[^;]+', 1, LEVEL)) FROM tableA CONNECT BY regexp_substr(col2, '[^;]+', 1, LEVEL) IS NOT NULL; commit; ``` You should also `commit` the transaction if you need the changes to b...
SQL insert with regexp
[ "", "sql", "oracle-sqldeveloper", "oracle11gr2", "" ]
Assume I have table `exection_records` which has the data: ``` +----+----------+---------------------+ | id | handle | finishedAt | +----+----------+---------------------+ | 1 | task_foo | 2015-08-16 03:10:33 | | 2 | task_foo | 2015-08-15 04:00:27 | | 3 | task_foo | 2015-08-14 02:10:25 | | 4 | task_bar ...
In MySQL, the simplest way is to have a sub-query that finds the last finished time for each handle, then join those results back on to your table to pick out the whole row. ``` SELECT execution_records.* FROM ( SELECT handle, MAX(finished_at) AS max_finished_at FROM execution_records GROUP BY hand...
``` select * from exection_records join (select handle, max(finishedAt) max from exection_records group by handle) m on exection_records.finishedAt=max ``` [Demo on sqlfiddle](http://sqlfiddle.com/#!9/b782d/1)
How to query a row with a unique identifier with their respective max value?
[ "", "mysql", "sql", "select", "max", "" ]
Using PostgreSQL 9.4, I store data as JSON array in plpgsql code, for example: ``` j := '[1,2,3,4,5]'::json ``` Next I loop through this array and do something with digits. ``` FOR i1 IN 0..(json_array_length(j)-1) LOOP RAISE NOTICE 'i1=%', j->>(i1); END LOOP; ``` I get this output: ``` 1 2 3 4 5 ``` How can I...
Keep it simple, just use `json_array_elements_text` and `ORDER BY random()`. ``` DECLARE item text BEGIN FOR item IN SELECT json_array_elements_text('[1,2,3,4,5]'::json) ORDER BY random() LOOP RAISE NOTICE 'item is %',item; END LOOP; END; ```
1. Make new array of keys (from 0 to 4) ``` SELECT INTO intarray array_agg(s.n) FROM (SELECT generate_series(0,json_array_length(j)-1) AS n ORDER BY random()) s ``` 2. In main loop get values from j array by value from new array ``` FOR i1 IN 0..(json_array_length(j)-1) LOOP RAISE NOTICE 'i1=%', j->>(intarray[i1...
Get elements from JSON array in random order
[ "", "sql", "json", "postgresql", "plpgsql", "" ]
My following SQL query has errors from MySQL workbench, and error is table "new\_table" not recognized. Does it mean MySQL does not support select into statement? ``` SELECT student_id into new_table FROM students; ``` thanks in advance, Lin
The problem is that [MySQL does not support the SELECT ... INTO ... syntax](https://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html). You have to use it like this: ``` Insert into new_table Select * FROM students; ```
Use ``` CREATE TABLE new_table as SELECT student_id FROM students; ``` If the table already exists: ``` INSERT INTO new_table SELECT * FROM students; ``` [This thread](https://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html) has some details on the syntax differences.
MySQL does not support select INTO?
[ "", "mysql", "sql", "" ]
Consider a table like with the following data ``` column_a (boolean) | column_order (integer) TRUE | 1 NULL | 2 NULL | 3 TRUE | 4 NULL | 5 FALSE | 6 NULL | 7 ``` I would like to write a queries...
You can use a handy trick where you `sum` over a `case` to create partitions based on the divisions between null and non-null series, then `first_value` to bring them forward. e.g. ``` select *, sum(case when column_a is not null then 1 else 0 end) OVER (order by column_order) as partition from table1; colu...
I'm more familiar with SqlServer, but this should do what you need. ``` update tableA as a2 set column_a = b2.column_a from ( select a.column_order, max(b.column_order) from tableA as a inner join tableA as b on a.column_order > b.column_order and b.column_a is not null where a.column_a is null group by a.col...
Update ordered row with last not-null value
[ "", "sql", "postgresql", "" ]
I have **Payments** table with multiple columns, including **Student,** **Value** and **Payment\_type.** I want to create a query that will calculate the sum of values, if *all the records* of the same student have only NULL as *Payment type*. If a student has at least one Payment type different than NULL, that student...
``` select student, sum(value) from payments group by student having sum(case when Payment_type is not null then 1 else 0 end) = 0 ```
[SQL Fiddle](http://sqlfiddle.com/#!9/1e58a/1) **MySQL 5.6 Schema Setup**: ``` CREATE TABLE Payments (`Student` int, `Payment` int, `Value` int, `Payment_type` varchar(4)) ; INSERT INTO Payments (`Student`, `Payment`, `Value`, `Payment_type`) VALUES (1, 1, 100, NULL), (1, 2, 200, NULL), (2, 1, ...
SQL: How to find the sum of values where all the records has the same value in a column?
[ "", "sql", "select", "where-clause", "" ]
I'm trying to restore a database from a dump generated with `mysqldump`. However it contains binary data. I made an `mysqldump` of a database which have an entity framework migration history table. > mysqldump.exe --opt --user=root foo > dump.sql This table has a column with binary data (longblob) and it's causing m...
Found the problem! I was running `mysqldump` via a powershell script which was causing the dump.sql file to be encoded incorrectly. Switched to a bat script instead and now it works
**do not use** IO redirect, use mysqldump option instead. > -r, --result-file=name > Direct output to a given file. This option should be used > in systems (e.g., DOS, Windows) that use carriage-return > linefeed pairs (\r\n) to separate text lines. This option > ensures that only a single newline is used. the OS IO ...
Restore mysqldump with binary data from EF migration history table
[ "", "sql", "mysql", "entity-framework-migrations", "" ]
I have a question to query tuple(s) that have latest date of each name. This is my example table. ``` ID || NAM E || DATE || INFOA || INFOB || INFOC 1 || Alice || 2015-08-20 12:0:0 || Y || N || Y 2 || Bob || 2015-08-20 12:0:0 || Y || N || Y 3 || Cheschire || 2015-08-20 12...
Please try with the below code snippet. ``` DECLARE @userData TABLE( ID INT NOT NULL, Name VARCHAR(MAX) NOT NULL, [Date] DATETIME NOT NULL, INFOA VARCHAR(MAX) NOT NULL, INFOB VARCHAR(MAX) NOT NULL, INFOC VARCHAR(MAX) NOT NULL ); INSERT INTO @userData VALUES ('1','Alice','2015-08-20 12:0:0','Y'...
Use `NOT EXISTS` to return a row if there are no other row with same name but a later date: ``` select * from tablename t1 where NOT EXISTS (select 1 from tablename t2 where t2.name = t1.name and t2.date > t1.date) ```
How to query the latest date from each duplicated name
[ "", "sql", "oracle", "" ]
In PostgreSQL, what is the `ROW()` function used for? Specifically what is the difference between ``` SELECT ROW(t.f1, t.f2, 42) FROM t; ``` where `f1` is of type `int`, `f2` is of type `text` and ``` CREATE TYPE myrowtype AS (f1 int, f2 text, f3 numeric); ```
You are confusing levels of abstraction. As other answers already point out, `CREATE TYPE` only registers a (composite / row) type in the system. While a `ROW` constructor actually returns a row. A row type created with the `ROW` constructor does not preserve column names, which becomes evident when you try to convert...
Row constructors can be used to build composite values to be stored in a composite-type table column, or to be passed to a function that accepts a composite parameter. Also, it is possible to compare two row values or test a row with IS NULL or IS NOT NULL. [4.2.13. Row Constructors](http://www.postgresql.org/docs/9.4...
What is a row constructor used for?
[ "", "sql", "postgresql", "types", "row", "" ]
``` select * from employees where last_name between 'A' AND 'E'; ``` Why the is answer coming till 'D' not 'E', is there any other way to fetch the details
> where last\_name between 'A' AND 'E'; **String comparison** is not similar as comparing numbers. String comparison is done on their **ASCII** values. So, you are comparing the ASCII value of **last\_name** with a **single character**, which will not give your desired output. ``` SQL> SELECT ename, ASCII(ename), AS...
Your command is perfect for "employees whose names *are* (not start with) from A to E". `"E"` would be in. `"Einstein"` is out, as it is *later* than `"E"`. ``` WHERE last_name >= 'A' AND last_name < 'F' ``` will give you what you want. Alternately, you can do ``` WHERE SUBSTR(last_name, 1, 1) BETWEEN 'A' AND 'E' `...
String comparision in Oracle SQL
[ "", "sql", "oracle", "oracle11g", "oracle10g", "string-comparison", "" ]