Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a posts table like this: ----- POSTS ----- - id - ..etc.. - category1 - category2 - category3 Any of these categories could be filtered, and I was planning to build SQL statements like: ``` SELECT * FROM posts WHERE category1='..sth..' AND category1='..sth..' OR category1='..sth..'...
If your database is well designed then no, this is not bad practice and is in fact the ideal way to select your data. The best thing to do is to think about how your data is going to be used and design the storage to make it easy to access the data you will need most often. There are lots of posts here about the specif...
try this ``` SELECT * FROM posts WHERE category1 in ('sth','sth') OR category2 in ('sth','sth') OR category3 in ('sth','sth') ..... ```
Is using AND & OR statements too much a bad practice for MySQL?
[ "", "mysql", "sql", "database", "" ]
``` $query="SELECT a.pk_i_id,a.i_price,b.s_title,c.pk_i_id AS img_id,c.s_extension,d.s_city,d.s_city_area from zl_t_item a, zl_t_item_description b, zl_t_item_resource c, zl_t_item_location d where a.fk_i_category_id=$cat_id and a.pk_i_id=b.fk_i_item_id and a.pk_i_id=c.fk_i_item_id and a.pk_i_id=d.fk_i_item_id ORDER BY...
It is invalid use of DISTINCT keyword. You can only apply it on a set of columns and not for a specific column skipping other columns
`DISTINCT` should be applied right after `SELECT` for a column or set of columns you cannot use `DISTINCT` between the columns ``` SELECT DISTINCT c.pk_i_id AS img_id, a.pk_i_id,a.i_price,b.s_title,c.s_extension,d.s_city,d.s_city_area from zl_t_item a, zl_t_item_description b, zl_t_item_resource c, zl_t_item_locat...
DISTINCT with as clause
[ "", "mysql", "sql", "distinct", "" ]
I would like to ask for help in understanding this piece of code... Am a beginner to mysql so I found it hard to read what this code does... ``` SELECT b.bcode FROM (SELECT bcode FROM tbl_items UNION SELECT bcode FROM tbl_items_bulk ) b left outer join tbl_reservation r on b.bcode = r.bcode ...
Ok, I'll try explain, hope you understand it; ``` SELECT b.bcode // Selecting the bCode from tbl_items and tbl_items_bulk FROM (SELECT bcode FROM tbl_items UNION SELECT bcode FROM tbl_items_bulk ) b left outer join // join to tbl_reservation where the bcod...
Effectively your query is showing you all of the bcode values from the tables `tbl_items` and `tbl_bulk_items` that do not have a match in the bcode column of the `tbl_reservations` table. This query could be done more effeciently as so: ``` SELECT t.bcode FROM ( SELECT bcode FROM tbl_items UNION SEL...
Query: I dont understand this piece of code
[ "", "mysql", "sql", "select", "" ]
I have looked over numerous tutorials, manuals and documentations, but I still can not get this to work. I am trying to create a stored procedure using phpMyAdmin. I cant seem to find the errors here, the sql errors are so vague... ``` CREATE PROCEDURE insertToonOneShot(IN locale CHAR(2), IN name VARCHAR(16), IN rea...
This does the trick: ``` CREATE PROCEDURE insertToonOneShot(IN locale CHAR(2), IN name VARCHAR(16), IN realm VARCHAR(24), IN faction CHAR(1), IN toon_level INT, IN class_name VARCHAR(12)) BEGIN SELECT @realmID := id FROM realms WHERE realms.name = realm; SELECT @classID := id FROM classes WHERE classes.name = class_na...
This question, and its answers, seem to be confusing session variables (which are prefixed with `@`) with procedural variables (which are not prefixed.) See the answers to [this question](https://stackoverflow.com/q/1009954/1255289) for more information. The [accepted solution](https://stackoverflow.com/a/18834683/125...
MYSQL Stored Procedures: Variable Declaration and Conditional Statements
[ "", "mysql", "sql", "stored-procedures", "variable-declaration", "" ]
``` SELECT DISTINCT HouseHoldMembers.FamilyID, Year(GetDate())-Year(DOB) as Age, FirstName+' '+LastName 'HeadOfHousehold', FamilyFolder.HouseNo from HouseHoldMembers left outer join FamilyFolder on FamilyFolder.FamilyID=HouseHoldMembers.FamilyID WHERE HouseHoldMembers.FamilyID in (select familyid from HouseHoldMe...
If your DBMS supports OLAP functions it's a simple ROW\_NUMBER: ``` SELECT * FROM ( SELECT HouseHoldMembers.FamilyID ,YEAR(GetDate()) - YEAR(DOB) AS Age ,FirstName + ' ' + LastName 'HeadOfHousehold' ,FamilyFolder.HouseNo ,ROW_NUMBER() OVER(PARTITION BY FamilyId ORDER BY YEAR(GetDate...
I think you can use `max(age)` and `group by(FamilyID)` to get your answer. Like this: ``` select FamilyID,max(Age) from (SELECT DISTINCT HouseHoldMembers.FamilyID,Year(GetDate())-Year(DOB) as Age, FirstName+' '+LastName 'HeadOfHousehold',FamilyFolder.HouseNo from HouseHoldMembers left outer join FamilyFolder on ...
sql query is not showing proper output for my requirement
[ "", "sql", "" ]
I have a scenario whereby I need to use multiple values in my where clause if a param passed to the query is 99999 otherwise I just use the param itself. I am using "IN" as part of the where clause but I get the following error "Incorrect syntax near the keyword 'CASE'". Any one provide an alternative to the incorrect ...
Perhaps you want: ``` DECLARE @IPD_NEWS_TYPE_PARAM decimal (18,0) SET @IPD_NEWS_TYPE_PARAM = 99999 SELECT n.id, n.headline, n.news_type_id FROM news n WHERE (n.news_type_id IN ('1','2','3','4','5') AND @IPD_NEWS_TYPE_PARAM = 99999) OR (n.news_type_id = @IPD_NEWS_TYPE_PARAM AND @IPD_NEWS_TYPE_PARAM <...
Use an IF statement: ``` DECLARE @IPD_NEWS_TYPE_PARAM decimal (18,0) SET @IPD_NEWS_TYPE_PARAM = 99999 IF (@IPD_NEWS_TYPE_PARAM = 99999) SELECT n.id, n.headline, n.news_type_id FROM news n WHERE n.news_type_id IN (1,2,3,4,5) ELSE SELECT n.id, n.headline, ...
Case statement with "where in" clause
[ "", "sql", "sql-server", "t-sql", "case", "where-clause", "" ]
I want to dynamically declare the range of my partition function. I don't want to hard-code the range value,like below: > CREATE PARTITION FUNCTION PartFun(smallint)AS RANGE LEFT FOR VALUES (1,2,3,4,5) The problem is:The column(ID in IDMASTER table) on which I want to create partition is of smallint datatype. ``` De...
May not be an exact solution to what you are looking for. Here is the scenario I am faced with: We have a DB that has multiple tables partitioned on a column named 'PriceListDate', but strangely, the data type is Varchar(8). We are in the middle of redesigning the application and the DB, so decided to change the data ...
Thanks, got idea. This is how I have solved it: ``` DECLARE @sqlcmd nvarchar(400),@ids nvarchar(100); SET @sqlcmd = N'CREATE PARTITION FUNCTION PartFun(smallint) AS RANGE LEFT FOR VALUES (' + @ids + N')' ; --PRINT @sqlcmd EXEC SP_EXECUTESQL @sqlcmd ``` So the solution is:Dynamic SQL and making everything as NVARCHAR!
How to dynamically declare PARTITION RANGE IN Partition function in sql server
[ "", "sql", "sql-server", "partitioning", "" ]
We have table with companies names and a numeric primary key identity. We are cleaning up the data and we have discovered the name column is full of similar names that represent the same company. E.g. BA and Ba or GTC Ltd and GTC Limited. Is there anyway using SQL server that we can get counts and summary of all item...
The basic answer is "No". Name rectification is a hard problem. Two names like "GTC Ltd" and "GTC Limited" are more different than "GTC" and "GTE" (by more obvious measures). There are outside service bureaus and special-purpose software for this purpose. If you are dealing with a smallish amount of data, I would sugg...
Your answer lies in the [`SoundEx()`](http://technet.microsoft.com/en-us/library/ms187384.aspx) and [`Difference()`](http://technet.microsoft.com/en-us/library/ms188753.aspx) functions. ``` DECLARE @a varchar(50) = 'BA' , @b varchar(50) = 'Ba' ; SELECT @a , @b , SoundEx(@a) , SoundEx(@b) , D...
Data cleansing - how to decide which names are misspellings or are equivalent but slightly different?
[ "", "sql", "sql-server", "data-analysis", "data-cleaning", "" ]
Suppose i have 2 tables for user & task. have user\_id & status in task with status having possible values "complete" & "not complete". Now I want to retrieve users who have not completed even 1 task. The most crude way is to first find users who have atleast 1 complete task and run a "not in" query. Any better ways t...
``` SELECT * FROM users u WHERE NOT EXISTS ( SELECT * FROM tasks t WHERE t.user_id = u.user_id AND t.status = 'complete' ); ```
When `task.user_id` cannot contain NULL (i.e. has a `NOT NULL` constraint), `LEFT JOIN` with `IS NULL` is your [best choice](http://planet.mysql.com/entry/?id=24888): ``` SELECT user.* FROM user LEFT JOIN task ON (task.user_id = user.id AND task.status = 'complete') WHERE task.user_id IS NULL ```
mysql join query that needs to return negative set
[ "", "mysql", "sql", "join", "" ]
First of all, I'm not an SQL expert, so probably I'm missing some brackets or something else that's stupid simple ;-) Can anyone please tell me why this works and returns 4 rows: ``` SELECT ppa.products_id FROM products_propattributes ppa WHERE ( (options_id = "11" AND options_values_id = "18") OR (options_id = "4"...
Because there can only be one possible value in a column in every row. If you want to get the `ID` that has both condition to return true using `OR` ``` SELECT ppa.products_id FROM products_propattributes ppa WHERE (options_id = "11" AND options_values_id = "18") OR (options_id = "4" AND options_values_id = "...
In the second query you have only `AND`s, so it's impossible that `options_id = "11"` AND `options_id = "4"` both match. And of course the same with `options_values_id = "18"` AND `options_values_id = "4"`.
Multiple where clause working with OR, not with AND
[ "", "mysql", "sql", "" ]
I have a text field in MS Access and it has text like this: ``` bla bla bla [hhh] bla bla bla [kkkd] blo blo blo blo [ttt] blo blo blo [ppp] jh asdjahsuz uizasdui asudz j jksdf ``` I'm trying to search for all records that have '[somthing]' in that field. ``` SELECT pruefhinweis FROM tb_bauteile WHERE pruefhinweis ...
Try this: ``` SELECT pruefhinweis FROM tb_bauteile WHERE pruefhinweis LIKE '*[[a-z]]*'; ``` **Or** ``` SELECT b.pruefhinweis FROM tb_bauteile AS b WHERE b.pruefhinweis Like '*[[]*]*'; ```
Matching square brackets in a pattern is not intuitive. See the help topic *"Using Wildcard Characters in String Comparisons"*: *You can use the special characters opening bracket ([ ), question mark (?), number sign (#), and asterisk (\*) to match themselves directly only if enclosed in brackets. You cannot use the c...
How to filter data with square brackets?
[ "", "sql", "ms-access", "pattern-matching", "" ]
I am using SQL Server 2012. I am new to T-SQL. I have a table called `tblEmp` where phone no of some employee is NULL. I want to copy all these data to a new table using `INTO` clause, but in the new table it should replace all the NULL phone nos with a string 'NA' I think this can be done by `CASE` statement.
You can use [ISNULL](http://technet.microsoft.com/en-us/library/ms184325.aspx) statement Query: ``` INSERT INTO table_name (column1,column2,column3,...) SELECT isnull(phone_no, 'NA') AS phone_no, name, ..... FROM tblEmp ``` OR [SELECT-INTO](http://technet.microsoft.com/en-us/library/ms188029.aspx) Sta...
``` INSERT INTO NewTable(col1,col2,....) SELECT case when phone_no is null then 'NA' else phone_no end, name,.... FROM tblEmp ```
How to insert data to a new table based on condtion using INTO CLAUSE?
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I have 2 tables in my database, one is `tablea`, and the other is `tableb`. ``` SELECT * FROM TABLEA ``` Results in: ``` ╔═════════════════════════════════════════════════════╗ ║ ip mac ║ ╠═════════════════════════════════════════════════════╣ ║ 1.10.0.0.97 ...
You should remove `'` before `replace` and after `)` and the quotes around `b.mac`. Also you can't replace `0` with `00` because for `c0` it will return `c00` you should use **[LPAD](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_lpad)** instead. ``` INSERT INTO TABLEC SELECT A.IP, A.MA...
you should lpad (with 0) tableb.mac before doing your replace.
Joining 2 tables in which the common row has different data formats
[ "", "mysql", "sql", "" ]
How many times will this nested sub-query be executed? ``` SELECT CID, CNAME FROM CUSTOMER WHERE EXISTS ( SELECT CID FROM RENTALS WHERE CUSTOMER.CID = RENTALS.CID AND PICKUP = 'CARY' ) ``` This is a theoretical question i.e. it is found in my book. The prov...
As others point out, this correlated subquery can be rewritten as a join, but that is not entirely the complete story because the execution plan for an untransformed EXISTS is going to look pretty much like a join anyway. So this is not really a syntax question but a query optimisation issue. EXISTS is really just syn...
There's no correct *theoretical* answer to this question. A smart query optimizer can transform the query into a JOIN: ``` SELECT CID, CNAME FROM Customer LEFT JOIN (SELECT DISTINCT CID FROM Rentals WHERE PICKUP = 'CARY') as Rentals ON Customer.CID = Rentals.CID WHERE Rentals.CID IS NOT NULL ``` Now the sub-query is ...
Number of times a nested query is executed
[ "", "sql", "database-agnostic", "" ]
I need my query to select unix timestamps which range from a particular past date till now?For example I need to select '2013-01-01' till current date. I was able to do it for a particular year. Any help would be appreciated. ``` SELECT mdl_user_info_data.data, mdl_user.firstname, mdl_user.lastname, mdl_user.id AS ...
Simply replace this line: ``` AND YEAR(FROM_UNIXTIME(mdl_grade_grades.timemodified)) = 2013 ``` to: ``` AND FROM_UNIXTIME(mdl_grade_grades.timemodified) BETWEEN '2012-01-01 12:00' AND now() ``` It seems that you are storing unix timestamp in your `timemodified` column. You should consider changing it to `time...
To check for a timestamp value between a given datetime in the past, and the current datetime, something like this: ``` AND mdl_grade_grades.timemodified >= '2013-07-25 15:30' AND mdl_grade_grades.timemodified < NOW() ```
select certain date till now mysql
[ "", "mysql", "sql", "" ]
I have a very complicated table I'd like to take a temporary backup of whilst I make some changes. Normally, I'd just do the following: ``` SELECT * INTO temp_User FROM dbo.[User] AS u ``` Unfortunately I'm using Azure, and it appears this isn't supported: > Msg 40510, Level 16, State 1, Line 2 Statement 'SEL...
The new [Azure DB Update preview](http://azure.microsoft.com/en-us/documentation/articles/sql-database-preview-whats-new/) has this problem resolved: > The V12 preview enables you to create a table that has no clustered > index. This feature is especially helpful for its support of the T-SQL > SELECT...INTO statement ...
Azure requires a clustered index on all tables, therefore `SELECT INTO` is not supported. You'll have to: ``` CREATE TABLE temp_User () --fill in table structure INSERT INTO temp_User SELECT * FROM dbo.[User] ``` To script table easily you can write your own or use one of the answers to this question: [Script CREAT...
SQL Azure doesn't support 'select into' - Is there another way?
[ "", "sql", "t-sql", "azure", "azure-sql-database", "" ]
I have two tables as below - Sale Record: ``` Date | Customer | ItemSold ----------------------------------------- 11/01/2013 | Alex | Pen 12/01/2013 | Rony | Paper 13/01/2013 | Alex | Eraser 14/01/2013 | Marty | Eraser 15/01/2013 | Alex | ...
Statistically, the term for what you are looking for is the `mode`. Here is one way to calculate it using window/analytic functions: ``` select customer, ItemSold from (select customer, ItemSold, count(*), row_number() over (partition by customer order by count(*) desc, p.priority ...
[SQL Fiddle](http://sqlfiddle.com/#!12/76e5c/1) ``` select distinct on (customer) customer, itemsold, total from ( select customer, itemsold, count(*) total from sales group by customer, itemsold ) s inner join priority on itemsold = itemname order by customer, total desc, prior...
SQL query to get most prevalent value in a column
[ "", "sql", "postgresql", "" ]
We have some tables which keep track of processed transactions. These tables have millions of rows. Often times I want to look at the most recent X transactions, so I have a query like this to pull the info I want from a few tables: ``` select a.id, b.field_one, c.field_two from trans a, table_two b, table_three c whe...
Your method is probably obsuring the fact that only a maximum of 100 rows are being selected from trans. Try this: ``` with cte_last_trans as ( select id from (select id from trans where id > (select max(id)-100 from trans) order by id desc) where rownum <= 100) select ...
You can use a NO\_MERGE hint which will force Oracle to execute the inner query first and not try to merge the two queries. Here's an example: ``` SELECT /*+NO_MERGE(seattle_dept)*/ e1.last_name, seattle_dept.department_name FROM employees e1, (SELECT location_id, department_id, department_name FROM de...
How can I get Oracle to have a better execution plan for this query?
[ "", "sql", "oracle", "query-optimization", "" ]
I want to execute this query ``` select * from locations where region=1 or region=2 ``` but in certain cases I don't want to include the second clause in the WHERE (`or region=2`) Is there a way to conditionally run the or statement?
Check for the condition in the where statement ``` select * from locations where region=1 or (region=2 and @checkRegion2=1) ```
If you want genralizable query, you can declare table variable for this (I assuming you're using SQL server): ``` declare @regions table (id int primary key) ``` and then fill it depending on condition: ``` insert into @regions select 1 if @use2 = 1 insert into @regions select 2 ``` now you can run this query: ...
Dynamic WHERE clauses in SQL Query
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have the following tables ``` CREATE TABLE Foos ( [Id] INT IDENTITY, -- Other fields ) CREATE TABLE Boos ( [Id] INT IDENTITY, [FooId] INT, -- Other fields ) ``` I am trying to execute a very simple query: ``` SELECT f.Id, COUNT(*) FROM Foos f JOIN Boos b on f.Id = b.FooId GROUP BY b.FooId ``` ...
SQL Server cannot consistently reason about such key relationships - if boos.FooId is nullable and your query is: ``` SELECT f.Id, COUNT(*) FROM Foos f LEFT JOIN Boos b on f.Id = b.FooId GROUP BY b.FooId ``` you have a set of records where b.fooId is NULL and f.Id can be different between them. You can also join o...
SQL Server simply doesn't take these facts into account and therefore it can't infer that `b.FooId` will always be the same as `f.Id` in this particular query.
Do I outsmart SQL Server or there is a reason for this?
[ "", "sql", "sql-server", "select", "join", "group-by", "" ]
I have the following SQL query (SQL Server 2005): ``` Select TOP 1000 col1, LTRIM(RTRIM(cast(col2 as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(col3 as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(col4 as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(col5 as varchar))) + SPA...
Wrap the fields in `ISNULL()` ``` Select TOP 1000 col1, LTRIM(RTRIM(cast(ISNULL(col2,'') as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col3,'') as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col4,'') as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col5,...
You can have some other value when there is a NUll, through ISNULL function. Here is a sample query: ``` Select TOP 1000 col1, LTRIM(RTRIM(cast(ISNULL(col2,'SOMEVALUE') as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(ISNULL(col3,'SOMEVALUE') as varchar))) + SPACE(2) + '|' + SPACE(2) + LTRIM(RTRIM(cast(I...
Avoiding NULL values - CONCATENATION
[ "", "sql", "sql-server", "" ]
I have a table like this ``` | customer_id | item_id | price | amount | ``` I want to retrieve the amount of money each customer has spent in a single query. I have tried: ``` SELECT SUM(price * amount) AS total FROM table GROUP BY customer_id ``` but this spits out astronomically high values for `total`. It canno...
Your initial query is correct: ``` SELECT SUM(price * amount) AS total FROM table GROUP BY customer_id; ``` (although I would include `customer_id` in the `SELECT` clause.) If you have "astronomically high values" then the issue is your data. Quite possibly, the issue is that "price" is really "total" on each row.
You have to add customer id to your select clause.
Calculate proper total in query?
[ "", "mysql", "sql", "innodb", "" ]
I'm building a stock keeping system and decided to store each product's balance (everytime it's updated) into the following table: ``` +------------+--------------+---------+------+ | Product_id | Warehouse_id | Balance | Date | +------------+--------------+---------+------+ ``` Example: Staff adds 10 pieces to prod...
Assuming that products' balances are being maintained per warehouse you can do it like this ``` SELECT t.product_id, t.warehouse_id, t.balance, t.date FROM table1 t JOIN ( SELECT warehouse_id, product_id, MAX(date) date FROM table1 WHERE date <= '2013-09-25' GROUP BY warehouse_id, product_id ) q ON ...
``` SELECT * FROM TABLE WHERE (PRODUCT_ID, DATE) IN (SELECT PRODUCT_ID, MAX(DATE) FROM TABLE WHERE DATE <= '2013-09-25' GROUP BY PRODUCT_ID ) ```
MySQL Select one row with unique attribute value
[ "", "mysql", "sql", "database", "" ]
I have 3 tables with mainly string data and unique id column: ``` categories ~45 rows clientfuncs ~800 rows serverfuncs ~600 rows ``` All tables have unique primary AI column 'id'. I try to count rows in one query: ``` SELECT COUNT(categories.id), COUNT(serverfuncs.id), COUNT(clientfuncs.id) FROM categories, serverf...
You're doing a cross join of 45\*800\*600 rows, you'll notice that when you check the result of the counts :-) Try this instead: ``` SELECT (SELECT COUNT(*) FROM categories), (SELECT COUNT(*) FROM serverfuncs), (SELECT COUNT(*) FROM clientfuncs); ```
The queries are doing [cartesian product](http://en.wikipedia.org/wiki/Cartesian_product) since no join condition is applied so: ``` 1 query : 800*600*45 = 21,6 mil 2 query : 45*600 = 27 k 3 query : 45*800 ... ```
Counting rows in multiple tables cause large delay
[ "", "mysql", "sql", "" ]
Please somebody suggest me with a SQL Server Select query to get values from a table column if only the values are not in another table, this is what I want to do: ``` SELECT t.TeacherID FROM Teacher t ...... (Who are not in Class c, c.TeacherID Column) ```
``` select teacherID from Teacher Except select teacherID from Class ``` or you can also go for: ``` select teacherID from Teacher where TeacherId not in(select teacherID from Class) ```
Teachers who ***do not*** have classes: ``` SELECT * FROM teacher WHERE NOT EXISTS ( SELECT * FROM class WHERE class.teacherid = teacher.teacherid ) ``` If you want to do the inverse (find teachers who ***do*** have classes) then all you have to do is reverse the condition: rem...
Select query to get values from a table column only if the values are not in another table
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
As far as i know according to mathematics rounding should work as below when rounding number is 5. ``` 2.435 => 2.44 (Round Up, if rounding to digit(3) is odd number) 2.445 => 2.44 (Round Down, if rounding to digit(4) is even number) ``` if we do summation all fine, ``` 2.435 + 2.445 = 4.88 2.44 + 2.44 = 4.88 ``` ...
If you do want to use banker's rounding in SQL Server... ``` CREATE FUNCTION BankersRounding(@value decimal(36,11), @significantDigits INT) RETURNS MONEY AS BEGIN -- if value = 12.345 and signficantDigits = 2... -- base = 1000 declare @base int = power(10, @...
You're looking for *Banker's Rounding* - which is the default rounding in C# but is not how SQL Server ROUND() works. See [Why does TSQL on Sql Server 2000 round decimals inconsistently?](https://stackoverflow.com/questions/7852892/why-does-tsql-on-sql-server-2000-round-decimals-inconsistently/7852940#7852940) as well...
SQL Server Rounding Issue where there is 5
[ "", "sql", "sql-server", "sql-server-2008", "" ]
One of my table stores the UserAgent from the user's browser along with the corresponding UID associated with it, with some other data. This occurs every time a user logs in. So they will have many entries per user. I am trying to query this table to find some unique users based on qualities. For example, I am trying ...
Select user with user agent `like '%MSIE 6.%'` who do not have any other user agent. The inner query returns users who have not used `'%MSIE 6.%'` ``` select distinct tb1.UID from TABLE1 tb1 where tb1.UserAgent like '%MSIE 6.%' and NOT EXISTS ( select tb2.UID from TABLE1 tb2 where tb1.UID = tb...
``` select distinct (tb1.UID) from TABLE1 tb1 where not exists ( select 1 from TABLE1 where UID = tb1.UID and UserAgent not like '%MSIE 6.%' ) ```
Joining same table on itself
[ "", "sql", "sql-server-2000", "user-agent", "" ]
I have a normal select query which results following output. ``` select cid,x1,x2,x3,x4,fy from temp_table; cid x1 x2 x3 x4 fy ---------------------------- 6657 100 0 0 200 2014 6658 300 0 0 400 2015 6659 500 0 0 600 2016 ``` I want it to rewrite it print following output. ``` 201...
Here is a way to do this with just subqueries and aggregation: ``` select name, sum(case when fy = 2014 then x end) as "2014", sum(case when fy = 2015 then x end) as "2015", sum(case when fy = 2016 then x end) as "2016" from (select fy, (case when n.n = 1 then 'x1' ...
More general solution is with [UNPIVOT and PIVOT](http://www.oracle-developer.net/display.php?id=506). Your `temp_table` is already a pivot table with *(x1 x2 x3 x4)* as **x-axis** and *fy* as **y-axis**. First we need to UNPIVOT `temp_table` into `unpivoted_temp_table` and then PIVOT it with *fy* as x-axis and *(x...
Transpose a query output
[ "", "sql", "oracle11g", "transpose", "" ]
I have the below data in a table **A** which I need to insert into table **B** along with one computed column. TABLE A: ``` Account_No | Balance | As_on_date 1001 |-100 | 1-Jan-2013 1001 |-150 | 2-Jan-2013 1001 | 200 | 3-Jan-2013 1001 |-250 | 4-Jan-2...
Here's a way to achive this using analytical functions. ``` INSERT INTO tableb WITH tablea_grouped1 AS (SELECT account_no, balance, as_on_date, SUM (CASE WHEN balance >= 0 THEN 1 ELSE 0 END) OVER (PARTITION BY account_no ORDER BY...
Try this and use `gone_negative` to computing specified column value for insert into another table: ``` select temp.account_no, temp.balance, temp.prev_balance, temp.on_date, temp.prev_on_date, case WHEN (temp.balance < 0 and temp.prev_balance >= 0) THEN 1 ...
Query for getting previous date in oracle in specific scenario
[ "", "sql", "oracle", "" ]
I am trying to select from one table a list of products ordered by price, year, name, and others.... The problem is that I must make zero values come last when sorting ascending. My code is: ``` SELECT * FROM Product P ORDER BY CASE WHEN @OrderBy='Date ASC' THEN Date END ASC, CASE WHEN @OrderBy='Price AS...
You can do it by testing for price-ordering twice: ``` SELECT * FROM Product P ORDER BY CASE WHEN @OrderBy='Date ASC' THEN Date END ASC, CASE WHEN @OrderBy='Price ASC' THEN CASE WHEN Price = 0 THEN 1 ELSE 0 END ASC, CASE WHEN @OrderBy='Price ASC' THEN Price END ASC, CASE WHEN @OrderBy=...
You can try with this syntax: ``` SELECT *, CASE WHEN @OrderBy = 'Price ASC' AND Price = 0 THEN 1 ELSE 0 END AS OrderPriceZeroLast FROM Product P ORDER BY OrderPriceZeroLast, CASE WHEN @OrderBy = 'Date ASC' THEN Date END ASC, CASE WHEN @OrderBy = 'Price ASC' THEN Price END ASC, CASE WHEN @OrderBy = 'T...
0 come last when sorting ascending
[ "", "sql", "sorting", "select", "sql-order-by", "" ]
I am trying to build a vb.net application with a where clause to filter data using a DateTime field. My table contains 5 fields and more than 10000 rows. I wanna use a DateTime field to find all the rows older than 7 years from now. But this script will be re-used many times. So I don't wanna use this kind of where cl...
Just make use of `DateTime`: ``` Dim dateTime As DateTime dateTime = DateTime.Now.AddYears(-7); ``` When you're building your SQL string just call `ToString` on your date (you can obviously format it however you need): ``` dateTime.ToString("MM/dd/yyyy"); ```
i think better would be provided you have SQL Server ``` strQuery = "select * from myTable WHERE myDateTimeField <= DATEADD(YEAR, -7, GETDATE())" ```
filter DateTime field with now as reference in WHERE clause
[ "", "sql", "vb.net", "datetime", "where-clause", "" ]
I would like to count the number of sorted subgroups in the table below : ``` id nmb 1 11 2 12 3 13 4 22 5 23 6 31 7 32 8 33 9 11 10 12 11 13 12 12 13 13 14 21 15 22 16 11 17 12 18 13 19 14 ``` And want to obtain something like this in postgresql 8.4 : ``` id nmb local 1 11 1 2 ...
It appears that you are trying to enumerate the groups, where a group starts with a lower `nmb` value than the previous row ("previous" defined by the `id` order). The idea is to identify the start of a group by using `lag()`. Then take the cumulative sum to get the group identifier that you want: ``` select id, nmb,...
I though i finally understood what you want, consecutively growing values: ``` select id, nmb, sum(flag) over (order by id rows unbounded preceding) as local from ( select id, nmb, case when lag(nmb) over (order by id) < nmb then 0 else 1 en...
Counting number of sorted subgroups inpostgresql
[ "", "sql", "postgresql", "" ]
I've got a few different SQL tables that I need to perform some counts on. This is for my job, so obviously the data is confidential, but I'll try to abstract it to something analogous. Imagine a University registrar's office... Our first table contains a list of all courses that students have completed. Table: `stud...
Based on both suggestions, I came up with the following. I performed the join on the coalesced values, so that the null rows would actually line up across the tables. Note, I was able to insert rows into the courses tables. If I wasn't, I'd UNION the zero value rows in the query. ``` INSERT INTO math_courses (0, NULL...
I'm not shure if i understood correctly, but is this what you want? ``` select coalesce(max_math_year, 0) ,coalesce(max_science_year, 0) ,coalesce(max_general_year, 0) ,count(*) from #student_maximums group by coalesce(max_math_year, 0) ,coalesce(max_science_year, 0) ,coalesce(max_general_year, 0) ```
Counting zero-values when joining in T-SQL
[ "", "sql", "sql-server", "database", "join", "null", "" ]
We're running into a problem here and I can't figure out why it behaves how it behaves. Given the following two (simplified) stored procedures in TSQL (SQL Server 2008R2) ``` create procedure [datetransaction1] as begin begin try begin transaction declare @a datetime exec datetransaction2...
The reason is: SQL Server dooms the transaction WHENEVER an error occurs, whatever the error is, whether it is in a TRY block or not, whether you saved a transaction state or not, whether the error occurs in a procedure or not, whatever you do. When the error occurs in one of the procedure calls, the transaction is do...
Since the second call to datetransaction2 function caused severity level 16 error SQL Server automatically rolled back your transaction. That's the reason for the error you are seeing. Here is a [really nice article](http://blogs.msdn.com/b/sqlserverfaq/archive/2011/05/11/errors-raised-with-severity-level-16-may-cause...
SQL Transaction uncommittable while using try..catch.. Why?
[ "", "sql", "sql-server", "transactions", "sql-server-2008-r2", "try-catch", "" ]
What is best approach **Approach-I** ``` SELECT SUM(CASE WHEN CODE = 'A' THEN ISNULL(UNIT,0.00)+ISNULL(UNIT_1,0.00) END) AS UNIT_SUM FROM tblA ``` **Approach-II** ``` SELECT ISNULL(SUM(CASE WHEN CODE = 'A' THEN UNIT+UNIT_1 END),0.00) AS UNIT_SUM FROM tblA ``` 1) my concern is Do i have to place ISNULL inside CAS...
**Answer to the original question:** > *Do I have to place ISNULL inside CASE statement...?* No you don't. [`SUM()`](http://technet.microsoft.com/en-us/library/ms187810%28v=sql.105%29.aspx) ignores `NULL`s. Therefore the presence of NULL values won't affect the result of summation. The exception is when all values ar...
You have other answers pointing out that you better put your filter `= 'A'` into where clause to speed up the query, and that's right thing to do. I also want to note that your queries produce different results in case there's no rows to sum: ``` SELECT ISNULL(SUM(CASE WHEN CODE = 'A' THEN UNIT END),0.00) AS UNIT_SUM...
T-SQL help needed regarding CASE statement in SELECT clause
[ "", "sql", "sql-server", "t-sql", "" ]
I am writing a MySQL query where I can get all records from the user table with duplicate email addresses. This is the query I have so far.. my PHPMyAdmin keeps loading: ``` select personal_email, userid from user where personal_email in ( select personal_email from user group by personal_email having count(personal_...
Try the query with a JOIN instead of `IN`: ``` SELECT user.personal_email, user.userid FROM user INNER JOIN ( SELECT personal_email FROM User GROUP BY personal_email HAVING COUNT(*) > 1 ) dupe ON dupe.personal_email = user.personal_emai...
Perhaps the most efficient way to do this in MySQL is to use an `exists` clause: ``` select u.* from user u where exists (select 1 from user u2 where u.personal_email = u2.personal_email and u.userid <> u2.userid ); ``` For optimal performance, create an in...
Get all users with duplicate email addresses
[ "", "mysql", "sql", "" ]
let me explain my situation, it really clearer than the title! I have two tables. Let give a look here and than I will you explain what I would like to do. First table (lesson table) ``` +------------------+----------------+ | LessonCode | SubjectCode | +------------------+----------------+ | 1 ...
To get all lessons of teacher X, you will have to join both tables: ``` select LessonCode from lesson l inner join subject s on s.subjectCode = l.SubjectCode where s.teacherCode = x ``` This basically does the following: It creates the cross product of the two tables and then deletes all lines which do not comply wit...
Try this: ``` select * from lesson l join subject s on s.subjectCode=l.SubjectCode where s.teacherCode=20 ```
Select a value in a first table according to another value of a second table (sql)
[ "", "mysql", "sql", "" ]
I have two tables that I need to pull data from. The first table is applications and the second is verification\_status. Each application has 20 steps and the verification\_status contains a date of when that step was completed. I am trying to pull the application along with the completion dates from a number of specif...
Give this a go: ``` SELECT a.*, ad.*, vs.date as steponedate FROM applications a LEFT JOIN verification_status vs ON vs.application_id = a.id AND vs.verification_step_id = 1 LEFT JOIN application_details ad ON ad.application_id = a.id WHERE ad.application_status_id != 1 AND ad.application_statu...
I am not certain that this is the problem, but you seem to be mixing ANSI89 and ANSI92 syntax in your query. I have never written a working query mixing the two together. Also, it seems as if the subquery you ran was supposed to be run for each row of data, not as a table. I think the following query will likely work ...
Mysql query with multiple sub queries for each row
[ "", "mysql", "sql", "" ]
I have to establish a connection using connection string to DB. I am using **SQL Server 2008 R2**, for which i need connection string. It is not **SQLEXPRESS**. Current String: ``` <connectionStrings> <add name="ApplicationServices" connectionString="server=USER-PC\SQL Server;database=TLE;Connection Ti...
The following connection string should probably work: ``` connectionString= "server=USER-PC;Integrated Security=True;Initial Catalog=TLE;Connection Timeout=40;providerName=System.Data.SqlClient" ```
Identify the sql server instance name. While installing SQL Server Express, you might have installed it under the default instance name (SQLEXPRESS). In that case you should use USER-PC\SQLEXPRESS If you have not given the instance name and still you are unable to connect then try to give the IP address like this: ```...
SQL string connection issue
[ "", "sql", "sql-server", "sql-server-2008", "connection-string", "sqlconnection", "" ]
I have the following data in a table called: dbo.DecodedCSVMessages\_Staging **Here is a sample of the data:** ``` MMSI Message_ID Time Ship_Type Vessel_Name Latitude Longitude 2102930 3 2012-06-01 NULL NULL 56.528003 85.233443 2102930 5 2012-07-01 70 R...
Something like this should do it: ``` ; WITH positions AS ( SELECT MMSI , Message_ID , "Time" , Latitude , Longitude FROM dbo.DecodedCSVMessages_Staging WHERE Message_ID IN (1, 3) AND Latitude > 55 AND Latitude < 85 AND Longitude > 50 AND Longitude < 141 ) , d...
I would think it relatively simple... something like.. ``` select MS.MMSI, MS.Message_ID, MS.Time, Ship.Ship_Type, Ship.Vessel_Name, MS.Latitude, MS.Longitude from dbo.DecodedCSVMessages_Staging MS JOIN dbo.DecodedCSVMessages_Staging Ship on MS.MM...
SQL AdvancedQuery
[ "", "sql", "sql-server-2008", "" ]
I have following table structure: ``` MID AutoID MikatName 1 3 ABC 4 17 XYZ 9 20 MNS 15 26 MNVS ``` Now i want to form a query so that i can get or select next record against particular AutoID. Means what query i have to form if i want r...
You want to add a `limit` clause and `order by`: ``` select * from ejamatPass where AutoID>17 order by AutoID limit 1; ``` By the way, SQL tables are inherently unordered. When you do a `select` there is no guarantee on the order of the results returned. You need an `order by` to ensure ordering.
``` SELECT * FROM ejamatPass WHERE AutoID>17 ORDER BY AutoID ASC LIMIT 1; ```
select next record against particular ID
[ "", "sql", "sqlite", "" ]
I am hoping someone wouldn't mind helping with something that I am stuck on. I need to produce a report which gives a count of items which have been created over a certain date range. For example, when a user would run this report on the 15/09/2013 it would show a count of any records which has a creation date of the ...
For "a creation date of the 1st of the current month, or before." use the following WHERE clause. The second piece of this will always returnt he first day of the current month. `WHERE CREATIONDATE <= DATEADD(m, DATEDIFF(m, 0, getdate()), 0)`
This will get all records up through 8/31. ``` SELECT RECORDTYPE, COUNT(RECORDTYPE) AS 'COUNT OF RECORDS' FROM VIEW_GLOBALSEARCH WHERE Year(CREATOINDATE) ```
SQL: Datepart searches
[ "", "sql", "t-sql", "" ]
I have a Table name stocks with following colums; ``` Stockcode Hig low Close Date MSFT | 100 | 90 | 95 |2013-09-18 MSFT | 105 | 96 | 97 |2013-09-17 MSFT | 104 | 92 | 91 |2013-09-16 MSFT | 101 | 88 | 100 |2013-09-13 ``` I want to list the lowest value from the Low colum for last ...
By the looks of your data you're looking for the lowest value over the last three trading days: ``` select min(low) from( SELECT `LOW` FROM `stocksdata` WHERE `STOCKSYMBOL` = "MSFT" ORDER by TIMESTAMP DESC LIMIT 3) ltd ```
``` SELECT LOW FROM stocksdata WHERE STOCKSYMBOL = 'MSFT' AND date BETWEEN DATE_ADD(NOW(),INTERVAL -3 DAY) AND NOW() ORDER by date DESC LIMIT 1 ```
How to get the Smallest value from the Top 3 rows of the table in mysql
[ "", "mysql", "sql", "" ]
I am trying to return just the first result of a query after it is sorted in alphabetical order: ``` SELECT MIN(DisplayName) FROM [User] GROUP BY DisplayName ``` I believed the above would do the trick. But it is still returing all results in alphabetical order. How do I get the desired results?
You don't need to `GROUP BY`: ``` SELECT MIN(DisplayName) FROM [User] ``` OR: ``` SELECT TOP 1 DisplayName FROM [User] ORDER BY DisplayName ``` `GROUP BY` will return each distinct value/combination of values for the fields listed.
Only the first row? Simply remove the group by: ``` SELECT MIN(DisplayName) FROM [User] ```
Return only the first alphabetical result of SELECT
[ "", "sql", "sql-server", "" ]
The first table: ``` day | title 1 | "Lorem" 2 | "Ipsum" ``` The second table: ``` day | title 2 | "Amor" 3 | "Zeus" ``` Now I need such a result: ``` day | title 1 | "Lorem" 2 | "Amor" 3 | "Zeus" ``` How to do that with a single query? **Edit:** "Zeus" added to the second table.
<http://sqlfiddle.com/#!2/0dc08/1> ``` SELECT t1.Day, COALESCE(t2.Word, t1.Word) AS Word FROM Table1 t1 LEFT JOIN Table2 t2 ON t2.Day = t1.Day UNION ALL SELECT t2.Day, t2.Word FROM Table2 t2 LEFT JOIN Table1 t1 ON t1.Day = t2.Day WHERE t1.Day IS NULL ``` The code above prefers t2 to t1 when a day is found in both tab...
``` SELECT t1.day, COALESCE(t2.title, t1.title) title FROM t1 LEFT JOIN t2 on t1.day = t2.day ``` ## Edit: Following @Glavić comment, here a solution where there is data in `t2` not in `t1` that should be considered: ``` SELECT t1.day, COALESCE(t2.title, t1.title) title FROM t1 LEFT JOIN t2 on t1.day = t2.day UN...
MySQL How can I select data from two tables so that rows from the second one overwrote those from the first one?
[ "", "mysql", "sql", "database", "" ]
i have a situation where i want to add unique constaint only when there is a certain value in other field for example the table is ID CategoryName Name Value CategoryID the constraint will be on ID, CategoryName and Name only is CategoryID is 0 is it possible?
``` CREATE UNIQUE NONCLUSTERED INDEX [UQ_ID_CategoryName_Name, CategoryName, Name] ON TableName ( ID, CategoryName, Name ) WHERE (CategoryID = 0) ```
One way to achieve this would be to have two tables, one for `categoryId` 0 and one for the rest. You can define the uniqueness constraint on the first table, and use a view and union any time you want to use them as a single table.
Add unique constraint depending on value in SQL
[ "", "sql", "sql-server", "" ]
Using a SQL tool like SQL Developer / Toad for Oracle Is it possible to write a SQL query that will do the following ``` SELECT * FROM TABLE WHERE COLUMN1 IN CSV_FILE ``` The CSV file is just one column of data with no delimiters. How can I achieve this? **Constraints** I cannot create a temp table to insert CSV ...
Creating external table is the best way. If you dont have permission then the other way is to move the file to the path of any oracle directory(Oracle object - Directory). And with help of utl\_file read the file, loop through it and do your operation inside a PL/SQL block which is too tedious. See the eaxmples for us...
1. Toad for Oracle data import (uses sqlldr internally) * Create a temp table and load the data using this utility and select the values 2. External tables * Create external table, load the data through the same and select the values.
Finding rows in table using input from a CSV file - SQL
[ "", "sql", "oracle-sqldeveloper", "toad", "" ]
I have two user tables with same schema. ``` | useraward_new | | useraward_his | | User | Award | | User | Award | | user1 | 5 | | user1 | 1 | | user2 | 2 | | user1 | 3 | | | | | user2 | 4 | | | | | user3 | 5 ...
``` SELECT n.[User], n.Award + ISNULL(SUM(h.Award),0) AS Award FROM useraward_new n LEFT JOIN useraward_his h ON h.[User] = n.[User] GROUP BY n.[User], n.Award ```
You need to select from the new table and do an inner join on the historical table: ``` SELECT User, SUM(Award) FROM useraward_new N INNER JOIN useraward_his H ON N.User = H.User GROUP BY User ``` edit: I guess that assumes that there is always going to be an equivalent user in the historical table. Otherwise Markus'...
merge two tables and get sum without select all from huge table
[ "", "sql", "sql-server", "sum", "" ]
Here is what my data looks like: ``` item_ID | group_ID | count_of_items_in_group 2|ABC|3 5|ABC|3 9|ABC|3 29|DEF|3 3|DEF|3 4|DEF|3 200|XYZ|2 300|XYZ|2 600|GHI|1 ``` **SQL Filddle:** <http://sqlfiddle.com/#!2/dfe09/1> For each group, I want to limit the number of item\_IDs returned to a max of 2. I do not ca...
What about using [ROW\_NUMBER()](http://technet.microsoft.com/en-us/library/ms186734.aspx) to enum the number of fields of your data set, partitioned by each group\_id. And after that just return when is just less or equal to 2? or any number that you want ``` SELECT * FROM ( select item_id, group_id, count_of_it...
Use the `ROW_NUMBER()` function for this: ``` SELECT * FROM (select *,ROW_NUMBER() OVER (PARTITION BY group_id ORDER BY item_id) as RowRank from items_in_groups )sub WHERE RowRank <=2 ``` Demo: [SQL Fiddle](http://sqlfiddle.com/#!3/dfe09/13/0) The `ROW_NUMBER()` function assigns a number to each row. `P...
SQL - Restrict the number of rows returned based on a count of rows
[ "", "sql", "sql-server", "sql-server-2005", "" ]
## The goal Concatenate a parameter with a `%` operator of LIKE using MySQL. ## The problem There's the following query on my database and it returns me the results very well: ``` SELECT people.LOGIN, people.EMAIL FROM people WHERE people.LOGIN LIKE 'o%' ORDER BY people.LOGIN ASC LIMIT 10; ``` But I want to call t...
Often what actually gets passed in is not what we think. Check that the parameter: * is not null * does not have leading or trailing whitespace Try this to guard against the above: ``` WHERE people.LOGIN LIKE CONCAT(TRIM(IFNULL(expression, '')), '%') ```
You need to use [prepared statements](http://dev.mysql.com/doc/refman/5.6/en/sql-syntax-prepared-statements.html). Create a string with a query, and execute it using prepared statements. Something like this - ``` SET @query = CONCAT('SELECT * FROM table1 WHERE column1 LIKE ''', expression, '%'''); PREPARE stmt FROM @...
Concatening LIKE with Stored Procedure's parameter using MySQL
[ "", "mysql", "sql", "stored-procedures", "" ]
I have following query on mysql, query logic is correct however issue is since there are over 10,000+ seeker emails and 24,000+ guest emails it take long time to execute, is there a better way to do this same this ? ``` SELECT g.email, g.name FROM guest g WHERE g.type='guest' AND g.email NOT IN (SELECT email FROM ...
Try this: ``` SELECT g.email, g.name FROM guest g LEFT JOIN seeker s ON s.email = g.email WHERE g.type = 'guest' AND s.email IS NULL GROUP BY g.email; ``` <http://sqlfiddle.com/#!2/d94bf/5>
``` SELECT DISTINCT g.email, g.name FROM guest g WHERE g.type='guest' AND NOT EXISTS (SELECT 1 FROM seeker s WHERE g.email = s.email) ``` And be sure you have an index on seeker.email, guest.type, guest.email, which would be awesome if the columns are `NOT NULL` on top of that.
MySQL optimize a NOT IN query how to?
[ "", "mysql", "sql", "" ]
``` select country_olympic_name, SUM(part_gold) as 'Number of Gold Medals' From games.country, games.participation where participation.country_isocode = country.country_isocode group by country_olympic_name; ``` I have been getting the error ORA-00923: FROM keyword n...
Identifiers need to be quoted with double quotes (`"`). Single quotes (`'`) denote a character *value* (not a "name"). Therefor you need to use: ``` SUM(part_gold) as "Number of Gold Medals" ``` More details in the manual: * [Database Object Names and Qualifiers](https://docs.oracle.com/database/121/SQLRF/sql_eleme...
## Add comma after SELECT QUERY --- In my case, I had this query ``` SELECT BANK_NAME DECODE (SWIFT_CODE, 'BRDEROBU', 'BRD', 'NO RESULT') RESULT FROM BANK_GAR; ``` As you may see, **I didn't had the comma** after the `SELECT BANK_NAME` line. The correct query is: ``` SELECT BANK_NAME, DECODE (S...
Error (ORA-00923: FROM keyword not found where expected)
[ "", "sql", "oracle", "" ]
I've been trying to count the number of columns in a table in my database using the below statement: ``` rs = st.executeQuery("SELECT COUNT(*) FROM information_schema.columns WHERE table_name = '"+TableName+"'"); while (rs.next()) { i = rs.getInt(1); } ``` For the below table table ...
The following query returns the number of columns that you have. If you want to get 12 you would have to multiply by the number of rows in the table: ``` SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='Yourdatabase' AND `TABLE_NAME`='yourtable'; ``` See it in [sqlfiddle](http://sqlfidd...
Also specify the db,you might have a table with the same name in other db ``` ...FROM information_schema.columns WHERE table_schema = 'myDB'... ```
Counting the number of columns in the database
[ "", "mysql", "sql", "" ]
I have a table that contains a text field (summary). I recently received a request to query that field for any occurrences of a long list of strings. For example, I'd like to search the "summary" field for *any* occurrences of these strings: * apple * banana * carrot * dog * elephant * ... x 50 more items * zebra Is ...
You could put them in one giant regular expression: ``` select t.* from t where summary similar to '%((apple)|(banana)|(carrot)|(dog)| . . .|(zebra))%'; ``` An alternative, if you want more flexibility and care even less about performances: ``` with tosearch as ( select '%apple%' as pattern union all . ....
The simplest way that comes in my mind is something like this: ``` SELECT "ID" FROM table WHERE "summary" IN ('apple', 'banana', 'carrot', 'dog', ....) ``` Try this out. **EDIT AFTER COMMENT:** use the [similar to](http://www.postgresql.org/docs/8.3/static/functions-matching.html) operator: ``` select "ID" from tab...
Postgresql query to search text field for multiple strings
[ "", "sql", "postgresql", "" ]
Is it possible to just create a table in MSSQL without columns? I'm asking this because I'll have to check for every columns if it already exists or not. ``` IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].Tags( [Id...
I think you can acheive what you're trying using the following: Create the table with the ID and only check for the existence of the `Id` column if you didn't have to create the table. ``` IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U')) BEGIN CREATE TABLE...
This code ``` create table tab ``` raises an error > Incorrect syntax near 'tab'. and this code ``` create table tab1 ( id int ) alter table tab1 drop id ``` raises an error > ALTER TABLE 'tab1' failed. Dropping all columns in a table is not > allowed. so a table without columns is not possible.
Create Table if not exists without columns
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Say suppose I have two mysql queries which are something like this ``` if(!empty($company)) { $q1="SELECT * FROM TABLE1 WHERE company='$company'"; } else { $q1="SELECT * FROM TABLE1; } $r1=mysqli_query($q1); if(!empty($color)) { $q2="SELECT * FROM TABLE1 WHERE color='$color'"; } else { $q2="SELECT * FROM TABLE1; } $r2...
If your application variables are blank when unassigned, you may combine the two conditions, *and* all of your application logic (testing for blank in app code), with this single, simple but elegant query: ``` SELECT * FROM TABLE1 WHERE '$company' IN ('', company) AND '$color' IN ('', color) ``` Note how by reversing...
Usually this is done with `INTERSECT`. MySQL however do not support `INTERSECT` so you have to use `JOIN` `SELECT * FROM TABLE1 a WHERE company='$company' INNER JOIN (SELECT * FROM TABLE1 WHERE color='$color') b ON (a.pid = b.pid)` Of course, if your case is so simple, you can just add the WHERE clauses `SELECT * FR...
How to fetch the common result of two queries?
[ "", "mysql", "sql", "" ]
Using [this solution](https://stackoverflow.com/questions/16062825/combine-two-columns-in-one-column), I tried to use COALESCE as part of a MySQL query that outputs to a csv file using SELECT As to name the column names when exporting the data. ``` SELECT FirstName AS First_Name , LastName AS Last_Name , Con...
If both columns can contain `NULL`, but you still want to merge them to a single string, the easiest solution is to use [**CONCAT\_WS()**](http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_concat-ws): ``` SELECT FirstName AS First_Name , LastName AS Last_Name , CONCAT_WS('', ContactPhoneA...
You don't need to list ContactPhoneAreaCode1 and ContactPhoneNumber1 ``` SELECT FirstName AS First_Name, LastName AS Last_Name, COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone FROM TABLE1 ```
MySQL SELECT AS combine two columns into one
[ "", "mysql", "sql", "" ]
I'm using Microsoft Sql Server Management Studio. I currently have an existing database with data in it, which I will call DatabaseProd And I have a second database with data used for testing, so the data isn't exactly correct nor up to date. I will call this database DatabaseDev. However DatabaseDev now contains newl...
You can use [Red-Gate SQL Compare](http://www.red-gate.com/products/sql-development/sql-compare/), this will allow you to compare both DB's and generate a script to run on the source DB. You have to pay for a license, but you will get a `14-day trial period`. This tool, along with [Data Compare](http://www.red-gate.co...
You need an ALTER TABLE statement ``` ALTER TABLE tableA ADD PhoneNum Varchar(10) --Insert variable of choice here ``` Looked like no changes to TableB Add TableC ``` CREATE TABLE TableC (ColumnID int, Document Varvhar(50)) ``` DO you need to copy constraints, Indexes or triggers over?
Copy database schema to an existing database
[ "", "sql", "sql-server", "database", "" ]
I have two tables **Table 1** ``` Column1 _______ 1 2 3 4 5 6 ``` **Table 2** ``` Column 1 ________ 4 NULL //This NULL value added after answering the question, to show the real problem 5 6 7 8 9 ``` This is an example case. When I tried, ``` SELECT column1 FROM Table...
Check the documentation for [`IN`](http://technet.microsoft.com/en-us/library/ms177682.aspx), specifically: > Any null values returned by *subquery* or *expression* that are compared to *test\_expression* using IN or NOT IN return UNKNOWN. Using null values in together with IN or NOT IN can produce unexpected results....
That may happend if you have `null` values in your Table2. Use this query instead: ``` select * from Table1 as t1 where not exists (select * from Table2 as t2 where t2.column1 = t1.column1); ``` **`sql fiddle demo`** Test query: ``` -- Table2 doesn't have null values, works good SELECT column1 FROM Table1 WHERE col...
Is IN and NOT IN mutually Exclusive?
[ "", "sql", "sql-server", "" ]
If I have for example an model: ``` User :firstname :lastname joseph smith anna bauer ... ... ``` And an input field where you can search for an **user**. The different search queries could be: ``` searchquery1: smith joseph searchquery2: joseph smith searchquery3: jo...
Yes, you have to search it on both first name and last name like this ``` select('(firstname || " " || lastname) as \'full_name\', *') where ['firstname LIKE :s OR lastname LIKE :s OR full_name LIKE :s', :s => "%#{search}"] ``` but if the data is too big. You can use the full text search engines like Solr or thinkin...
To make search on firstname, lastname and fullname; Member.where ['first\_name LIKE :s OR last\_name LIKE :s OR CONCAT(first\_name,last\_name) LIKE :s', :s => "#{search.delete(' ')}"] It works!
How to make SQL search query for firstname, lastname
[ "", "sql", "ruby-on-rails", "ruby-on-rails-3", "" ]
I have two tables that join easily and a third that is giving me trouble. First, the tables: ``` tbl_customer id dt value group a 2013-01-01 10 cavalry a 2012-06-01 20 lance a 2011-03-01 10 infantry b 2013-01-01 20 court b 2012-07-01 5 maiden b 2005-06-01 10 ...
First, some actual table schema would be helpful as the table data you have provided is missing some key elements. What are the keys in each of the tables? I.e., what can be used to uniquely identify a row in each of the tables? What does the `id` column in the customer and title table represent? Surely not a customer ...
Try this: ``` SELECT * FROM ( SELECT id, dt, value, titles.title, group.rank MAX(rank) OVER(PARTITION BY cust.id) AS MAX_RANK FROM tbl_customer AS cust INNER JOIN tbl_title AS titles ON titles.id = cust.id AND dt BETWEEN titles.dt_active AND titles.dt_inactive INNER JOIN tbl_group AS group ON gr...
Difficult SQL join across tables
[ "", "sql", "sql-server", "" ]
I'm trying to join two fields in SQL with the below command; ``` SELECT [NUM] & [ITEMNUM] AS LINKCODE FROM mydatabase ``` When I run this I get the error; ``` Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value 'O00000001' to data type int. ``` This is probably something ...
You can't just add a number and a string together. You have to bring them on the same data type first. Cast to `varchar` first ``` SELECT cast([NUM] as varchar) + [ITEMNUM] AS LINKCODE FROM mydatabase ```
If you are on SQL Server 2012+ you can use ``` SELECT CONCAT([NUM],[ITEMNUM]) AS LINKCODE FROM mytable ``` This treats `NULL` as empty string and does the casting of numeric values to string.
Error when trying to run join command in SQL
[ "", "sql", "" ]
I have a set of dates that are in the format DD-MMM-YYYY. I need to be able to compare dates by using only the DD-MMM part of the date, since the year isn't important. How would I achieve this? I have tried reading up on the DATEPART function (edit: which evidently wouldn't work) but I can only theoretically get that...
If your column is of type `DATE` then it doesn't have a format. If I understand you right, then you want to view the `mon-dd` part only, so you need to convert it with `TO_CHAR` function, i.e.: ``` select to_char(your_date_column, 'mon-dd') from your_table ```
Convert your dates using the following format, it will only month and the date part. You have to replace getdate() with you date fields.: ``` select convert(varchar(5),getdate(),110) ```
Getting only day and month from a date field
[ "", "sql", "oracle", "" ]
I have two date for example 08/08/2013 and 11/11/2013 and I need last date of each month starting from August to November in a table so that i can iterate over the table to pick those dates individually. I know how to pick last date for any month but i am stucked with a date range. kindly help, it will be highly appr...
You can use [CTE](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) for getting all last days of the month within the defined range ``` Declare @Start datetime Declare @End datetime Select @Start = '20130808' Select @End = '20131111' ;With CTE as ( Select @Start as Date,Case When DatePart(mm,@...
``` DECLARE @tmpTable table (LastDates DATE); DECLARE @startDate DATE = '01/01/2012'; --1 Jan 2012 DECLARE @endDate DATE = '05/31/2012'; --31 May 2012 DECLARE @tmpEndDate DATE; SET @startDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startDate)+1,1)); SET @tmpEndDate = DATEADD(DAY, 1, @endDate); WHILE (@startDate <=...
tsql: How to retrieve the last date of each month between given date range
[ "", "sql", "sql-server", "sql-server-2008", "" ]
How do I split file on batches using powershell? I have a sql post deploy file with multiple batches. Below is example of my postDeployment.sql file. ``` IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'StoredProc') AND type in (N'P', N'PC')) BEGIN DROP PROCEDURE [dbo].[StoredProc] END ** GO **...
I have found solution but it does not cover all cases like GO inside of sql: ``` $file = "D:\PostDeployment.sql" $SQLCommandText = @(Get-Content -Path $file) # loads content foreach($SQLString in $SQLCommandText) { if($SQLString -ne "go") # if string is not equal to go then add it to existing st...
this: ``` $a = ( [system.io.file]::ReadAllText( "c:\file.sql" ) -split '(?:\bGO\b)' ) | % { $_ + "`r`nGO" } ``` create an array whit batch then you can try: ``` $a | % { ExecuteBatch $__} ```
How do I split file on batches using powershell
[ "", "sql", "powershell", "" ]
I have a query that returns many rows: ``` SELECT c.id AS courseID, c.fullname AS courseName, c.continuingeducationcredits AS cec, cc.name AS catName, IFNULL(ccp.name, '-No Parent Category-') AS catParent, ue.userid AS userID, CONCAT(u.firstname, ' ', u.lastname) AS name, ud.data AS employeeid, ...
I finally figured out the issue ... the application is Moodle, and it loads queries into an array, using a function called get\_records\_sql. It *requires* the first row of the results to be a unique key. It uses that row as the index of the array. So ... to make that happen: Begin the SELECT like this- ``` SELECT ...
To be fair... my comment with this answer was first :) ``` WHERE courseID = 8946 ``` Is in the second query. Remove it and it should work.
mysql subquery only returning one row
[ "", "mysql", "sql", "" ]
I need to do some simple calculations counting the percentage ranges of each project. It seems as if this should be a very simple straightforward query but my results (counts of percentages <10%, >50%, and >100% are coming back incorrect and I'm having trouble figuring out why. I'm working in db2 and here is a sample o...
It looks like your values are being stored as strings (hence the `'%'`) rather than as numbers. Here is a method to compare them as numbers, and do the ranges at the same time: ``` SELECT (case when cast(replace(PERCENTAGE_USED, '%', '') as float) <= 10 then '<10' when cast(replace(PERCENTAGE_USED, '%', ...
I'm not too sure what you are expecting or what the field data types are set as, but could this be down to you comparing a string value rather than a numeric one for the comparison > '100.00%'
Count and percentage ranges
[ "", "sql", "db2", "aggregate-functions", "" ]
I need to get list of ids of duplicate rows in my table so I can delete them using `where id in`. Here is my table : ``` id|col1|col2 1 |22 | text 2 |22 | text 3 |23 | text 4 |22 | text2 ``` So in here ids `1` and `2` are duplicates other are not. So I know how to get them by using `group by and having count(*) >...
Try something like: ``` delete from table_name where id not in (select min(id) from table_name group by col1, col2); ``` It will delete all rows with non minimal `id` in every `col1, col2` group. Alternative query: ``` delete from table_name t1 where exists (select * ...
Igor Romanchenko gave good solutions, another one could be: ``` with cte as c ( select id, row_number() over(partition by col1, col2 order by id) as rn from Table1 ) delete Table1 as t from cte as c where c.id = t.id and c.rn > 1 ```
Filtering out duplicates from database but preserving the originals
[ "", "sql", "postgresql", "" ]
I have a database with 5 columns (`A1,A2,A3,A4,A5`) which store 5 numbers. The 5 numbers are `"1,2,3,4,5"`. ``` A1 A2 A3 A4 A5 ------------------------------- 2 4 5 Null Null ``` I want get the missing number which is "1" and "3". How do I find the missing number from 5 numbers?
An elegant solution that is extensible beyond the 5 values presented in your question makes use of a [numbers table](https://dba.stackexchange.com/questions/11506/why-are-numbers-tables-invaluable) (as shown in the link, a numbers table is invaluable for a multitude of tasks). Here's the setup for the numbers table, w...
``` Select Replace(Replace(Replace(Replace( Replace('12345',(Cast(Coalesce(A5,0) as varchar(1))),''), (Cast(Coalesce(A4,0) as varchar(1))),''), (Cast(Coalesce(A3,0) as varchar(1))),''), (Cast(Coalesce(A2,0) as varchar(1))),''), (Cast(Coalesce(A1,0) as varchar(1))),'') from Table1 ``` [**Sql Fiddle Demo**](http://sqlfi...
Find missing number from not sequence number
[ "", "sql", "sql-server", "vb.net", "" ]
I've got 3 tables: `Movies`, `Actors`, and `MovieActors`. `MovieActors` is a many-to-many relationship of `Movies` and `Actors` with columns `MovieActorId`, `MovieId`, and `ActorId` How do I find movies that have a certain set of actors in it? For example I want to find all movies that have both Michael Fassbender (ac...
To keep it simple, you can just do two `in` clauses: ``` select * from Movies m where m.MovieId in (select MovieId from MovieActors where ActorId = 1) and m.MovieId in (select MovieId from MovieActors where ActorId = 2) ``` Performance may not be as good as a single `join`, but it's clean and easy to read.
One way is to join the tables. Filter for the actors and then insure the count has the number of actors you want in it (2 in this case) ``` SELECT m.MovieID FROM Movies m INNER JOIN MovieActors ma ON m.MovieID = ma.MovieID WHERE ma.ActorID IN (1,2) GROUP BY m.MovieID HAVING COUNT(DISTINCT ma.A...
SQL select on a many-to-many table
[ "", "sql", "sql-server", "" ]
I am creating four database tables by the following schemas but am getting an integrity constraint violation error. Here is my entire schema along with the queries to populate the tables: ``` create table Employee( Lastname varchar(10), FirstName varchar(10), MidInitial char(1), gender char(...
Ok. Few errors noted... ``` insert into Works values('Gill', 'Mary', 'L', 'Union Pacific (UP)', 48700); insert into Works values('Harrison', 'Susan', 'M', 'Union Pacific (UP)', 54320); ``` -- Changed 'Union Pacific' to 'Union Pacific (UP)' ``` insert into Manages values('Anderson', 'Susan', 'L', 'Dale',...
This is your problem: ``` insert into Works values('Gill', 'Mary', 'L', 'Union Pacific', 48700); ``` 'Union Pacific' is not one of your companies, you have 'Union Pacific (UP)' As an aside, this is a really shabby way to do it anyway. Duplicating your data across tables like this is going to mean you have problems l...
Integrity constraint error again
[ "", "sql", "oracle", "referential-integrity", "" ]
I am implementing a competition where there might be a lot of simultaneous entries. I am collecting some user data, which I am putting in one table called entries. I have another table of pre-generated unique discount codes in a table called discountCodes. I am then assigning one to each entry. I thought I would do thi...
Something can be done like *The following example sets the TRANSACTION ISOLATION LEVEL for the session. For each Transact-SQL statement that follows, SQL Server holds all of the shared locks until the end of the transaction.* **Source:MSDN** ``` USE databaseName; GO SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; GO...
I would recommend building a bridge table instead of having the `EntryId` in the `DiscountCodes` table with an `EntryId` and a `DiscountCodeId`. Place a `Unique Constraint` on both of those fields. This way your entry point will encounter a constraint violation when it tries to enter a duplicate.
MS SQL locking for update
[ "", "sql", "sql-server", "t-sql", "" ]
I am having problems with has\_and\_belongs\_to\_many relation. I have 2 models, Doctors and PatientMeeting. ``` class Doctor < ActiveRecord::Base has_and_belongs_to_many :patient_meetings end class PatientMeeting < ActiveRecord::Base has_and_belongs_to_many :doctors end ``` The problem is to show the patient mee...
Assuming you're using `mysql`. Try this ``` Doctor.joins(:patient_meetings).where("patient_meetings.meeting_date <= CURDATE() + INTERVAL 1 DAY AND patient_meetings.meeting_date >= CURDATE()").order("patient_meetings.meeting_date DESC").limit(50) ```
Try this: ``` PatientMeeting.joins(:doctors).where(doctors: {top50: true}) ```
has_and_belongs_to_many and joining tables
[ "", "sql", "ruby-on-rails", "ruby", "" ]
Is it possible to have an `OR` statement in an SQL query without having to repeat information that doesn't change? Take this as an example: ``` SELECT * FROM table WHERE a = 1 AND b = 1 AND c = 1 AND x = 1 AND y = 2 OR a = 1 AND b = 1 AND c = 1 AND x = 2 AND y = 1 ``` This is the only way I can figure out how to do i...
``` WHERE a = 1 AND b = 1 AND c = 1 AND ( ( x = 1 AND y = 2 ) OR ( x = 2 AND y = 1 ) ) ``` Alternative option (which is clearer IMO): ``` SELECT * FROM ( SELECT * FROM table WHERE a = 1 AND b = 1 AND c = 1 ) As a_subqu...
``` SELECT * FROM table WHERE a = 1 AND b = 1 AND c = 1 AND ( (x = 1 AND y = 2) OR (x = 2 AND y = 1) ) ```
SQL OR statement without having to repeat
[ "", "sql", "" ]
I have two tables (bold=PK): log: [**id**,type, value] totals: [**type**,total] Where the "total" value at "totals" is the sum of the values of all entries in the log with the same type. I want to update the totals table so I run a query: ``` INSERT INTO totals (type,total) (SELECT type,sum(value) AS total FROM log...
You want: ``` ON DUPLICATE KEY UPDATE total = VALUES(total) ```
As Gordon already said, you use VALUES(`field`) to get the value that would be inserted, or just `field` to get the old value ``` INSERT INTO .... ON DUPLICATE KEY UPDATE `field` = VALUES(`field`) ``` <http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html> In your case - the complete query should look some...
On duplicate key update with the new value
[ "", "mysql", "sql", "" ]
I have been working on a query: ``` SELECT P.[Name]+' - '+P.[Description] AS Sprint, S.[Number] AS Story, T.[Name] AS Task FROM DailyTaskHours D INNER JOIN Task T ON D.TaskId = T.PK_Task INNER JOIN Story S ON T.StoryId = S.PK_Story INNER JOIN Sprint P ON S.SprintId = P.PK_Sprint GROUP BY P.[Name], P.[Description],...
Change `S.Number` to `ISNULL(S.Number, 'KanBan')`. This will add 'Kanban' in case no matching sprintID is found in the Sprint table. Change `INNER JOIN Sprint P ON S.SprintId = P.PK_Sprint` to `LEFT JOIN Sprint P ON S.SprintId = P.PK_Sprint`. This ensures that all other records will still show, even in case of no matc...
``` SELECT ISNULL(P.[Name]+' - '+P.[Description],'KanBan') AS Sprint, S.[Number] AS Story, T.[Name] AS Task FROM DailyTaskHours D INNER JOIN Task T ON D.TaskId = T.PK_Task INNER JOIN Story S ON T.StoryId = S.PK_Story LEFT OUTER JOIN Sprint P ON S.SprintId = P.PK_Sprint GROUP BY P.[Name], P.[Description], S.[Number]...
SELECT using multiple JOINS needs to return even if one compairson is not equal
[ "", "sql", "sql-server", "" ]
I have a table with numbers in a `varchar(255)` field. They're all greater than one and have multiple decimal places. I'd like to convert them to integers. According to every web site I've consulted, including [this one on StackOverflow](https://stackoverflow.com/questions/728833/convert-a-string-to-int-using-sql-quer...
Converting a `varchar` value into an `int` fails when the value includes a decimal point to prevent loss of data. If you convert to a `decimal` or `float` value first, then convert to `int`, the conversion works. Either example below will return 7082: ``` SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172')); ...
Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even: ``` select cast ('7.0' as int) select cast ('7.' as int) ``` will fail but both are fine for floats.
tSQL - Conversion from varchar to numeric works for all but integer
[ "", "sql", "sql-server", "number-formatting", "" ]
I have a table `test_table` as below ``` test_id varchar2(10) new_test_id number ``` Though test\_id is `varchar` it stored numbers, now I want to store the negative of the current value in test\_id to new\_test\_id. The statement I tried is as below: ``` update test_table a set a.new_test_id = TO_NUMBER(-a.test_id)...
I just figured out it was not working because the test\_id column unexpectedly had a couple of records with alphabets. To\_number was failing for only those records under update and was fine for others which had numbers.
`update test_table a set a.new_test_id = -1 * TO_NUMBER(a.test_id);`
To_number fails to convert varchar to number in update statement
[ "", "sql", "oracle", "" ]
I got this "single-row subquery returns more than one row" and my Query is ``` Select contact_ID from contact where ( Select b.Contact_ID from company a, contact b where a.Company_ID = b.Company_ID and a.IS_ACTIVE <> 'N' and b.IS_ACTIVE <> 'N' and a.CREATED_DATE >= '01-Jun-2013') = ( Select b.Contact_ID from compa...
try this ``` Select contact_ID from contact where Contact_ID in ( Select b.Contact_ID from company a inner join contact b on a.Company_ID = b.Company_ID where a.IS_ACTIVE <> 'N' and b.IS_ACTIVE <> 'N' and a.CREATED_DATE >= '01-Jun-2013' ) ; ``` ...
Try this: Removed sub select and replaced with union. ``` Select b.Contact_ID from company a, contact b where a.Company_ID = b.Company_ID and a.IS_ACTIVE <> 'N' and b.IS_ACTIVE <> 'N' and a.CREATED_DATE >= '01-Jun-2013' union Select b.Contact_ID from company a, contact b where a.Company_ID = b.Company_ID and ...
SQL error sign (single-row subquery returns more than one row
[ "", "sql", "oracle", "select", "" ]
I have probably in excess of 100 databases on this one SQL Server (2005) instance. I'd like to list them in order of their create dates, or even better, in the order of the date of the latest modification to any table. Is there a SELECT query I can write, and just as importantly, from what context do I write it and wi...
You can easily write this query against the `sys.databases` catalog view ``` SELECT * FROM sys.databases ORDER BY create_date ``` but unfortunately, there's no equivalent for the "last modification date" that I'm aware of ... This should work from any database on that server - doesn't matter which database you're in...
``` create table #db_name (db_name nvarchar(128), last_change datetime); exec sp_MSForEachDB 'Use ?; insert into #db_name (db_name, last_change) select ''?'', max(modify_date) from sys.tables' select * from #db_name order by last_change desc ``` this is not exactly one select but at least you got what you want. I'm db...
List all the databases on one SQL Server in the order they were created
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
I need to do the following without using a #Temp table or a table variable. Can't do CTE with a GROUP BY. Is there a way to do this? ``` select Title, count(*) as PlayCount into #Temp from LC l join Play p on p.lcID = l.lcID group by Title declare @Max int select @Max = max(PlayCount) from #Temp select Title, Play...
Use a subquery/cte and `MAX() OVER()`: ``` SELECT Title, PlayCount, PlayCount*1.0 / Max_CT AS WEIGHT FROM (SELECT Title , COUNT(*) AS PlayCount , MAX(COUNT(*)) OVER() AS Max_CT FROM LC l JOIN PLAY P ON P.LCID = L.LCID GROUP BY Title )sub ``` (Assuming MS SQL 2005 or newer...
sub query? perhaps not the cleanest ``` select Title, count(*) as PlayCount , count(*) / tot from LC l join Play p on p.lcID = l.lcID , (select max(a) as tot from (select count(*) as a from LC group by lcid)) group by Title , tot ``` not entirely sure which table is doing what, but above should give you an idea
Making an in-line statement without a table or a cte
[ "", "sql", "sql-server", "t-sql", "" ]
I am using sybase. I have two tables like this: ``` USER | HITS ------------ A | 2 B | 1 C | 4 E | 3 USER | HITS ------------ A | 2 B | 8 C | 1 D | 2 ``` I want to combine them on USER and SUM the HITS column to get a result like this: ``` USER | HITS ------------ A | 4 B | ...
Try this: ``` SELECT USER, SUM(HITS) HITS FROM (SELECT USER, HITS FROM Tbl1 UNION ALL SELECT USER, HITS FROM Tbl2) A GROUP BY USER ```
Not sure if Sybase has `with`, if not you can nest the subquery as per Hamlet's solution. ``` ;with x (user, hits) as ( select user, hits from table1 union all select user, hits from table2 ) select user, sum(hits) as hits from x group by user; ```
Aggregating 2 Tables in tSQL
[ "", "sql", "t-sql", "sybase", "" ]
**Database -** Microsoft Adventureworks **Tables -** Sales.SalesOrderHeader **Problem -** Which customers (ie customerID's) ordered something in March 2003 or April 2003 but not both. **Concept -** Get the blue parts, ie elements/rows *unique* to A and those *unique* to B. ![Image Credits - Jeff Atwood of CodingHor...
``` SELECT Cust.CustomerID FROM Sales.Customer AS Cust INNER JOIN Sales.SalesOrderHeader AS Soh ON Cust.CustomerID = Soh.CustomerID WHERE Soh.OrderDate >= '2003-03-01' AND Soh.OrderDate < '2003-05-01' GROUP BY Cust.CustomerID HAVING COUNT(DISTINCT CASE WHEN MONTH(Soh.OrderDate) = 3 AND ...
``` CREATE TABLE table_a ( id INTEGER NOT NULL PRIMARY KEY , OrderDate DATE NOT NULL DEFAULT '2003-03-15'); CREATE TABLE table_b ( id INTEGER NOT NULL PRIMARY KEY , OrderDate DATE NOT NULL DEFAULT '2003-04-15'); INSERT INTO table_a(id) VALUES (0),(2),(4),(6),(8),(10),(12),(14),(16),(18),(20); INSERT INTO table_b...
Get combined difference (not common/"intersecting" records) from two queries
[ "", "sql", "" ]
**Preamble** As of late, I see too many geeks commenting on Oracle questions saying "Do not use (+) operator, rather use JOIN syntax". **Question** I do see that both work well. But what is the real difference between using them? I would welcome answers more from experience. 1. Is there anything to do with limitati...
**Grouping answers together** 1. Use explicit JOINs rather than implicit (regardless whether they are outer joins or not) is that it's much easier to accidently create a cartesian product with the implicit joins. With explicit JOINs you cannot "by accident" create one. The more tables are involved the higher the risk ...
If your 200+ packages work as intended with "old fashioned" syntax, let it be. SQL will not start to perform better after migration to ANSI syntax - it's just different syntax. All that being said, ANSI syntax is cleaner - you are not going to normal join if you forget (+) in some multi-column outer join. In ...
Oracle Joins - Comparison between conventional syntax VS ANSI Syntax
[ "", "sql", "oracle", "oracle11g", "oracle10g", "oracle12c", "" ]
How to insert a default value in all columns after inserting a value in a single column, Example: I created a `product` table and the columns are `id (autoincrement)`, `product_name`, and `item`. ``` CREATE TABLE product ( id int AUTOINCREMENT, product_name varchar(255), item int ); ``` How can I insert ...
Set Default for item: ``` CREATE TABLE product ( id int AUTOINCREMENT, product_name varchar(255), item int DEFAULT 30); ```
``` CREATE TABLE product ( id int AUTOINCREMENT, product_name varchar(255), item int ); ``` in mssql server use the following query: ``` ALTER TABLE product ADD item int CONSTRAINT DF_TestTable_NewCol DEFAULT 30 not null GO ```
INSERT in a single column, the rest of the column will have a default value
[ "", "mysql", "sql", "" ]
If I run this query on my oracle database: ``` SELECT COLUMN_NAME, DATA_DEFAULT, DATA_TYPE FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'MY_TABLE' AND DATA_DEFAULT IS NOT NULL; ``` The result I'm getting is: ``` STOICHIOMETRY NULL NUMBER ``` My Question is WHY? I've asked for not NULL. If I...
I think NULL is your default value? For example I have a table and I've altered the default value to NULL: ``` ALTER TABLE UNIQUEVALTEST MODIFY ZIP DEFAULT NULL; ``` Now when I select: ``` SELECT COLUMN_NAME, DATA_DEFAULT FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = 'UNIQUEVALTEST' AND data_default IS NOT NULL; ``` I ge...
The nullability of a column is stored in `NULLABLE`, not in `DATA_DEFAULT`. The `DATA_DEFAULT` stores the default value for a column (and if you haven't provided a default value in the `CREATE TABLE` statement, all columns get `DEFAULT NULL` (even non-nullable ones!) Try: ``` SELECT COLUMN_NAME, DATA_DEFAULT,...
Oracle, NULL but not NULL
[ "", "sql", "oracle", "null", "oracle-sqldeveloper", "isnull", "" ]
When I try to insert a value which has '&' in TOAD I get a prompt for a substitution variable. So when I try: ``` insert into x values('hello & world'); ``` it throws a prompt for substituting the variable 'world'. I have tried right clicking in the editor and disabling prompt for substitution variables but this se...
Try putting `set define off` at the beginning of your script. It should work with `F5`: ``` set define off; insert into x values('hello & world'); set define on; ```
In TOAD version 12.120.39 Right click in Editor and Click in Substitution Variable Prompting and select none This worked for me.
How to escape ampersand in TOAD?
[ "", "sql", "plsql", "toad", "" ]
I have a sql table : Levels ``` LevelId Min Product 1 x 1 2 y 1 3 z 1 4 a 1 ``` I need to duplicate the same data into the database by changing only the product Id from 1 2,3.... 40 example ``` LevelId Min Product 1 x 2 2 y 2 3 z 2 4 ...
You're most of the way there - you just need to take one more logical step: ``` INSERT INTO dbo.Levels (LevelID, Min, Product) SELECT LevelID, Min, 2 FROM dbo.Levels WHERE Product = 1 ``` ...will duplicate your rows with a different product ID. Also consider that `WHERE Product = 1` is going to be more reliable ...
You can generate the product id's and then load them in: ``` with cte as ( select 2 as n union all select n + 1 from cte where n < 40 ) INSERT INTO dbo.Levels(`min`, product) SELECT `min`, cte.n as product fROM dbo.Levels l cross join cte where l.productId = 1; `...
Populate a sql table with duplicate data except for one column
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
Can anyone help? I have a table which has a datetime field and duration.. what I need is to merge the records that happened on one day... As below, My first column shows the date, the second the amount of hours available and then the minutes... As you can see there is a morning and afternoon, what I need is to select j...
The idea is that you want to convert the date time to a date and group by that. Then you want to sum the hours and minutes. It is easy to sum them as minutes `60*h + m`. However, to split this back into hours and minutes requires a bit of arithmetic. Here is one method: ``` select cast(dt as date), cast(sum(h ...
In case you're using some database which supports the `SUM` and `GROUP BY` commands, try this: This works fine for sqlite3: ``` SELECT date(date), (sum(hours)*60+sum(minutes))/60, sum(minutes)%60 FROM dates GROUP BY date(date) ``` This is the answer to the follow-up question in the comments: ``` SELECT date(free.da...
SQL to Merge Date fields
[ "", "sql", "date", "merge", "group-by", "" ]
Imagine we have a table such as: ``` Number Value GroupValue 1 FOO GR1 22 BAR GR2 100 FOO3 GR1 20 BAR23 GR2 ``` I want to get the sum values of these rows based on group value,but also ,i want to see which rows it has grouped by in another column such as: ``` SUM values groups 101 FOO,FOO3...
You can't use an alias created in the `SELECT` list in your `GROUP BY`. You can fix this by separating your listing from your aggregation (cte/subquery): ``` WITH cte AS (SELECT * ,STUFF(( SELECT ',' + Value FROM Table1 AS T2 WHERE ...
You just need to make a small change, stick your SQL **without** the group into another select with the group. I think I converted your SQL right: ``` SELECT SUM(ID) as IdSum, B FROM ( SELECT ID, STUFF(( SELECT ',' + A FROM dbo.Table_1 AS T2 WHERE A = T2.A F...
Concatenating rows using group by and aggregate functions
[ "", "sql", "sql-server", "" ]
how to search data from month to month if : > txtbox1.text = "m/y" or "06/2013" > > txtbox2.text = "m/y" or "09/2013" mysql query code : > SELECT \* FROM tb\_user WHERE dateregister ?..... and if, record in table is: > id name dateregister > > 1 abc 05/05/2013 > > 2 ccc 06/05/2013 > > 3 ddd 01/06/2013 > > 4 ggg 01...
``` SELECT * FROM tableName WHERE STR_TO_DATE(dateregister, '%d/%m/%Y') BETWEEN STR_TO_DATE(CONCAT('01/', '06/2013'), '%d/%m/%Y') AND LAST_DAY(STR_TO_DATE(CONCAT('01/', '09/2013'), '%d/%m/%Y')) ``` * [SQLFiddle Demo](http://sqlfiddle.com/#!2/43d5e/2) OUTPUT ``` ╔════╦══════╦════════════...
You just have to use the `BETWEEN` keyword. ``` SELECT * FROM tb_user WHERE dateregister between @textBox1Value and @textBox2Value ``` Make sure the dates you parsing (@textBox1Value and @textBox2Value) is well typed. Refer to this link for the [date formatting](http://dev.mysql.com/doc/refman/4.1/en/date-and-tim...
vb.net - mysql query select record from month to month
[ "", "mysql", "sql", "vb.net", "" ]
I'm trying to execute a query with union and then put an additional condition on the result. Basically, I want to have something like > SELECT \* FROM (A UNION B) WHERE condition Is this possible to do? When I try to execute > SELECT \* FROM (A UNION B) SQL Management Studio complains about the closing bracket: > ...
``` SELECT * FROM ( SELECT * FROM A UNION SELECT * FROM B ) temp WHERE condition ```
Here is the correct syntax: ``` SELECT * FROM (select from A UNION select from B ) ab WHERE condition; ``` I agree that the original syntax "looks right" for a `from` statement, but SQL doesn't allow it. Also, you need an alias on the subquery (requirement of SQL Server). Finally, you might consider ...
SQL condition on unioned tables
[ "", "sql", "sql-server-2008-r2", "union", "" ]
I am trying to execute the sql query: ``` select * from table where column like '%value%'; ``` But the data is saved as 'Value' ( V is capital ). When I execute this query i don't get any rows. How do i make the call such that, it looks for 'value' irrespective of the casing of the characters ?
use LOWER Function in both (column and search word(s)). Doing it so, you assure that the even if in the query is something like %VaLuE%, it wont matter ``` select qt.* from query_table qt where LOWER(column_name) LIKE LOWER('%vAlUe%'); ```
If you want this column be case insensitive : ``` ALTER TABLE `schema`.`table` CHANGE COLUMN `column` `column` TEXT CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'; ``` Thus, you don't have to change your query. And the MySQL engine will process your query quicker than using lower() function or any other tricks. An...
SQL SELECT LIKE (Insensitive casing)
[ "", "mysql", "sql", "sql-like", "case-insensitive", "" ]
I have two tables: Table 1: ``` ------------------------------ |Country |Emp Level |Name| |-----------|-----------|----- |UK |Staff |A |US |Admin Staff|B |CA |Staff |C |NL |Admin Staff|D |MN |Intern |E |IN |Staff |F |UK |Staff |G |US...
Try this one ``` CASE WHEN EXISTS(SELECT level_guid FROM table_2 T WHERE u.emp - levels = T.level_name AND u.country IN ( 'UK', 'US' )) THEN (SELECT MAX(level_guid) FROM table_2 T WHERE u.emp - levels = T.level_name AND u.count...
Here there are two queries: ``` SELECT T2.[Level Guid] [Level ID], T1.[Emp Level] Level, T1.Country, COUNT(*) Count FROM Table1 T1 INNER JOIN Table2 T2 ON T1.[Emp Level] = T2.[Level name] AND CASE T1.Country WHEN 'UK' THEN 'UK' WHEN 'US' THEN 'US' ELSE 'Global' END = T2.[Country code] GROUP BY T2...
Count number of people in each country in SQL server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a database in SQL Server 2008 R2, and I want to copy this database onto another machine. How do I make a copy? And how do I restore it? Thanks
There are probably more ways to do this but I usually right-click the database and choose "Tasks → Back up..." with Backup type "Full". After that you can copy the created file to your target machine, connect to its SQL Server in SQL Server Management Studio, right-click the "Databases" folder and choose "Restore Datab...
You can't copy Database to another machine. Yes you can take back up to same machine and copy it to another machine and do restore. To take backup follow procedure: 1. Right Click on the database you want to take backup. 2. Choose Task -> Back Up. 3. In Destination, Choose Add. 4. In File Name click on `...` button a...
How to copy SQL Server 2008 R2 database from one machine to another
[ "", "sql", "sql-server-2008-r2", "" ]
I have a field in a table I am querying that looks similar to this: ``` Name Phone Category_IDS Category_Labels Sample 1111111111 ["1"] ["foo", "bar"] ``` I am trying to use the FIND\_IN\_SET function to find all rows that contain one of the values listed in the c...
If data is stored exactly how you showed it then you can use [`REPLACE()`](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace) to strip double quotes and brackets before feeding `category_ids` to `FIND_IN_SET()`. ``` SELECT * FROM Table1 WHERE FIND_IN_SET(1, REPLACE( ...
try below sql query with like operator SELECT \* FROM factual\_usplaces WHERE category\_ids LIKE '%1,2%' Hope This help you
MySQL FIND_IN_SET With Array String
[ "", "mysql", "sql", "" ]
I have a resturant db and I need to total up the total value of all the items sold individually. So if I sold a hamburger that has a base price of $10.00 with bacon which costs $1.00 and a hambuger(again $10.00) with avacado that costs $0.50 I need to get $21.50 returned. My invoice table looks like this: ``` invoice_...
``` SELECT item_num, sum(i.price) + sum(nvl(x.ingred_price,0)) FROM invoices i LEFT OUTER JOIN (SELECT parent_item_id , sum(price) ingred_price FROM invoices WHERE parent_item_id IS NOT NULL GROUP BY parent_item_id) x ON x.parent_item_id = i.item_id WHERE i.parent_item_id ...
Not clear based on your question (see my comment) but as I understand it a simple group by will give you what you want. If not please explain (in the original question) why does this query does not work --- what is it missing from your requirements? ``` SELECT item_num, SUM(price) FROM invoices GROUP BY item_num ```
subquery the same table in select statement
[ "", "sql", "" ]
I want to preserve the record order, which is provided as comma delimited string. The 5th item in by delimited string is a null. I need the 5th row to be null as well. ``` with test as (select 'ABC,DEF,GHI,JKL,,MNO' str from dual ) select rownum, regexp_substr (str, '[^,]+', 1, rownum) split from test ...
Order **is** preserved by your expression, but your regular expression doesn't match nulls correctly, so the 5th item disappears. The 6th row is a `NULL` because there are no more match after the 5th match. You could do this instead: ``` SQL> with test as 2 (select 'ABC,DEF,GHI,JKL,,MNO' str from dual 3 ) 4...
Try Something like this: ``` SELECT STR, REPLACE ( SUBSTR ( STR, CASE LEVEL WHEN 1 THEN 0 ELSE INSTR ( STR, '~', ...
Preserve order when converting a delimited string to a column
[ "", "sql", "oracle", "oracle11g", "" ]
I'm trying to pull the `ClientID` from the following sub-query with a group by and having clause but I get the following error: > Msg 116, Level 16, State 1, Line 1 > Only one expression can be specified in the select list when the subquery is not introduced w ith > EXISTS. Query: ``` select ClientID from ...
Remove the **count()** from the select clause ``` select ClientID from SurveyResponses where ClientID in (select ClientID from SurveyResponses where SurveyID in (1988,1989,2750,3206,15561) group by ClientID having count (SurveyResponseID) > 1) and SurveyID = 1989 ```
You are pulling two columns in your sub query and can only pull one, because you are telling sql, check where client ID exists in the count of survey responses AND the clientIDs in the SurveyResponses table. Try this, it is untested ``` select ClientID from SurveyResponses where ClientID in (select ClientID from Su...
How do you use a group by / having clause in a sub-query for?
[ "", "sql", "sql-server", "" ]
I have a query for getting search results, which works fine. ### Example of successful query: ``` SELECT individuals.individual_id, individuals.unique_id, TIMESTAMPDIFF(YEAR,individuals.day_of_birth,CURDATE()) AS age, individuals_dynamics.id, individuals_achievements.degree FROM individuals...
This is your `from` clause: ``` FROM individuals as individuals LEFT JOIN individuals_dynamics AS individuals_dynamics ON individuals.unique_id = individuals_dynamics.individual_id INNER JOIN ( SELECT degree, MAX(id) AS latest_record FROM individuals_achievements ...
`PDO::query` returns a `FALSE` if there's an error while processing your query, and applying `rowCount` to `FALSE` as a member function will result in the error you're seeing. Check your query for syntax errors and parse any error messages `PDO` would return you.
Using sub-query to SELECT MAX value along with LEFT JOIN
[ "", "mysql", "sql", "join", "subquery", "" ]